Additional Text Added to Filename Using Powershell Rename-Item - windows

I am using Powershell 7.2.1 on a stand alone Win10 machine.
The test is renaming 3 text files from a script. Everything is working except the renamed file names have text strings True/False prepended to the intended file names. The filenames should NOT have "True False" or "True True" before them.
True False AALTONEN-ALLAN_PENCARROW_PAGE
True False COVER_PAGE_PENCARROW_1981
True True BARTLETT-BEDGGOOD-BEECH-BEST_PENCARROW_PAGE_-
These names have been copied/pasted from File Explorer (view Details, sort Name) The .txt extension is not shown.
They were renamed from these names:
Copy of 31832_226140__0001-00002
Copy of 31832_226140__0001-00003
Copy of 31832_226140__0001-00006
The relevant line in my Powershell script is:
# use the filename to rename this file
Rename-Item -Path $item -NewName $fileName
I have used -Whatif parameter Rename-Item -Path $item -NewName $fileName -Whatif Here's the output split over two lines.
What if: Performing the operation "Rename File" on target "Item: C:\test\test3\Copy of 31832_226140__0001-00003.txt
Destination: C:\test\test3\True False AALTONEN-ALLAN_PENCARROW_PAGE_1".
I have added Write-Host lines throughout the process to check the variable outputs. And everything is correct up until the Rename-Item code.
I have looked at the documentation and can't see that any additional parameters are required for the Rename-Item cmdlet in my application. But I could be missing something here.
Any suggestions would be appreciated.

Related

Powershell dir command options not working

I was trying to use dir command to list recursively all files that end with .cpp in a given directory, I tried to follow various solutions but my powershell seems not to accept any options after '/' sign as seen on the picture bellow:
Example
The command I initially tried was 'dir sourcefolder "*.cpp"' but it only lists files in a given folder (because I cant provide any additional options as seen in microsoft doc), also any example command provided there does not work for me giving the same error as shown in example above.
here is how I will bring out all the files in .cpp.
Here is a small program in powershell :
$path = "C:\temp\"
$filter = "*.cpp"
$files = Get-ChildItem -Path $path -Filter $filter
Write-Host "here, all the .cpp files in '$path' :"
Write-Host $files -Separator "`r`n"
I prefer to use the cmdlet "Get-ChildItem" rather than "dir".
Here the content folder for my test
And, why so many / ?

Windows Compare filenames and delete 1 version of the filename

I have several hundred folders where I will have multiple files called filename.ext but also another file called filename.ext.url
I need a way of checking if filename.pdf.url exists does filename.ext exist. If they both exist delete filename.ext.url
I can't just do a search and delete all *.url files as they will be needed if the normal file does not exist
I then need to repeat that in all subdirectories of a specific directory.
I don't mind its its a batch script, powershell script that does it or any other way really. I'm just stumped on how to do what I want.
Currently I'm doing it folder by folder, manually comparing file names, file size and file icon.
foreach ($file in ls -Recurse c:\files\*.url) {
if (ls -ErrorAction Ignore "$($file.PSParentPath)\$($file.basename)") {
remove-item $file.fullname -whatif
}
}
remove whatif when ready to delete.
the basename removes the extension, so if they are all .ext.url then it will check if that file exists. It also removes the path, so we pull that as well.
an alternative way (that more matches what you're explaining) is something like
foreach ($file in ls -Recurse "c:\files\*.url") {
### replacing '.url$' means .url at the end of the line in Regex
if (ls -ErrorAction Ignore ($file.FullName -replace '\.url$')) {
remove-item $file.fullname -whatif
}
}
for /r "startingdirectoryname" %b in (*.url) do if exist "%~dpnb" ECHO del "%b"
This is expected to be executed directly from the prompt. If the requirement is as a batch line, each % needs to be doubled (ie. %%).
This also assumes that the whatever.ext file is to be in the same directory as the whatever.ext.url file.
Note that the filenames that are to be deleted will merely be echoed to the console. To actually delete the files, remove the echo keyword.
Test against a test directory first!
[untested]
To check for "filename.ext", check for "filename.ext.", they are the same file.
In CMD.EXE, you can do "IF EXIST "filename.ext." CALL :DoIt

Attempting to search and replace a few lines in an XML file in every user's appdata/roaming folder

I'm still kind of new to windows administration and very new to powershell so please forgive my ignorance. I wrote the following one-liner and I'm attempting to adapt it so that it can modify every existing user's FTRSettings.xml file on a PC. I'm worried that using the following path with a wildcard in place of the username would only replace the first file it finds.
C:\users\*\appdata\Roaming\FTR\GoldMain\FTRSettings.xml
Tested and working one liner executed from the appdata\Roaming\FTR\GoldMain\ directory.
((Get-Content -Path .\FTRSettings.xml -Raw) -replace '<Setting name="audioLevelsVisible" type="11">0</Setting>','<Setting name="audioLevelsVisible" type="11">-1</Setting>' -replace '<Setting name="inputLevelsVisible" type="11">0</Setting>','<Setting name="inputLevelsVisible" type="11">-1</Setting>' -replace '<Setting name="logSheetPaneViewState" type="11">0</Setting>','<Setting name="logSheetPaneViewState" type="11">-1</Setting>')
I was wondering if anyone could point me in the right direction.
To process each file individually:
Use Get-ChildItem with your wildcard-based path to find all matching files.
Loop over all matching files with ForEach-Object and perform the string replacement and updating for each file.
Note: I'm using a single -replace operation for brevity.
Get-ChildItem -Path C:\users\*\appdata\Roaming\FTR\GoldMain\FTRSettings.xml |
ForEach-Object {
$file = $_
($file | Get-Content -Raw) -replace 'foo', 'bar' |
Set-Content -Encoding utf8 -LiteralPath $file.FullName -WhatIf
}
Note: The -WhatIf common parameter in the command above previews the operation. Remove -WhatIf once you're sure the operation will do what you want.
Note the use of -Encoding to control the character encoding explicitly, because the original encoding is never preserved in PowerShell; instead, the cmdlet's own default applies - adjust as needed.

Appending date/time to file AND updating last modified/save date

I am trying to automate some file renaming but also need the file to update it's "last modified" time as I have a field inserted within the Word document that dynamically updates the last time the file was edited.
copy C:\path\to\file\test\test.docx "C:\path\to\file\test2\test-%date:~-7,2%-%date:~-10,2%-%date:~-4,4% %time:~-11,2%%time:~-8,2%.docx"
I tried to integrate the following syntax:
copy /b filename.ext +,,
That I got from:
https://superuser.com/questions/10426/windows-equivalent-of-the-linux-command-touch/764716
However it did not output anything when I put the + after the source file.
copy /b "C:\path\to\file\test\test.docx" + "C:\path\to\file\test2\test-
%date:~-7,2%-%date:~-10,2%-%date:~-4,4% %time:~-11,2%%time:~-8,2%.docx"
I also tried invoking a PowerShell script within the batch file to update last modified date:
$file = Get-Item C:\Path\TO\test.docx
$file.LastWriteTime = (Get-Date)
copy C:\path\to\file\test\test.docx "C:\path\to\file\test2\test-
%date:~-7,2%-%date:~-10,2%-%date:~-4,4% %time:~-11,2%%time:~-8,2%.docx"
powershell -file C:\path\to\powershell.ps1
Can't get it to work either way, I'm new to this so probably missing something simple.
I was able to figure this one out. My batch file is now as follows:
powershell -command "(Get-Item "C:\path\to\file\test\test.docx").LastWriteTime = (Get-
Date)"
copy C:\path\to\file\test\test.docx "C:\path\to\file\test2\test-%date:~-7,2%-
%date:~-10,2%-%date:~-4,4%%time:~-11,2%%time:~-8,2%.docx"
Which first modifies the last edited date of the file, and then copies it over to test 2 folder with the time and date appended.
I'm a bit curious what you mean with:
I have a field inserted within the Word document that dynamically updates the last time the file was edited.
If you copy a file it's content is not altered and the LastWriteTime stays the same,
so why do you want to set LastWriteTime to current date&time?
As per your attempt with copy in cmd.exe you did omit the two commas, this should do:
copy /b "C:\path\to\file\test\test.docx" + , , "C:\path\to\file\test2\test-%date:~-7,2%-%date:~-10,2%-%date:~-4,4% %time:~-11,2%%time:~-8,2%.docx"
The PowerShell suggestion from my comment:
'C:\path\to\file\test\test.docx' |
Get-Item |
Copy-Item -Destination {'{0}\{1}-{2:MMddyyyy\ HHmm}{3}' -f `
$_.Directory, $_.Basename,
$_.LastWriteTime, $_.Extension} -WhatIf
Could be modified to rename all files with date time appendix to reflect the actual LastWriteTime.
Get-ChildItem -File -Filter *.docx |
Where BaseName -Match '-\d{8} \d{4}$' |
Rename-Item -NewName {'{0}-{1:MMddyyyy\ HHmm}{2}' -f `
$_.Basename.Replace($Matches[0],''),
$_.LastWriteTime, $_.Extension} -WhatIf
If the NewName is the same, Rename-Item ignores it.
In contrast to Copy-Item, Rename-Item doesn't allow a directory.

Rename multiple files in a folder and its subfolders to a fixed pattern

I have a large number of files to be renamed to a fixed pattern on my Windows 8 computer.
I am looking for a way so that I can rename the files in a quick way, any way: like any software that does it or any command on command window.
Following is what I need to do:
Original file name: Body Begger Power.docx.htm
Need this to be: body-begger-power.html
From the root directory you can try this:
Get-ChildItem -Force -Recurse | Move-Item -Destination {$_.FullName.ToLower() -replace ' ', '-'}
I don't see any pattern for removing the extension. If all files are docx.html and you want them changed to html, you could simply do another replace like this:
Get-ChildItem -Force -Recurse | Move-Item -Destination {($_.FullName.ToLower() -replace ' ', '-') -replace '.docx.htm$', '.html'}
for /r %i in (.) do if exist "%i\body begger power.docx.htm" ECHO ren "%i\body begger power.docx.htm" body-begger-power.html
from the prompt will scan the tree from . (the current directory - or substitute the directoryname from which you want to start). This will simply ECHO the filenames detected to the screen - you need to remove the ECHO keyword to actually rename the file.

Resources