Windows Command Line PowerShell Rename – How to Rename with Variable and Special Characters in PowerShell

command linepowershellrenamewindows

I’m trying to rename some files. In the path and filename there are symbols like [, ] and spaces.
The rename command says it can´t find the file.

There is a main file with the symbols and a "temp" file. The main file should be deleted and the name of the temp file should be from the original.

my code is:

$onlypath = Split-Path -Path $_.FullName
Rename-Item $onlypath + "\TEMP" $_.Name

and testet many other syntax like

Rename-Item -Path "$onlypath\TEMP" -NewName $_.Name 
or
Rename-Item -Path $onlypath"\TEMP" -NewName $_.Name 
or
Rename-Item -Path $onlypath + "\TEMP" -NewName $_.Name 

the error is everytime, that the file is not at this place.
i tried the command in a shell and the same error but if i add ` as escape char before the symbols it works.

greetings

Best Answer

Looking at your code, I think you do not want to rename the file, but Move it to a new path. Rename-Item is for well.. renaming a file where it actually is located. You then give it a new file name, it is not for changing the path.

Also, if the file has symbols like [,], you need to specify -LiteralPath instead of -Path

Try

$sourcePath  = 'X:\Somewhere\Here[123]'
$destination = Join-Path -Path $sourcePath -ChildPath 'Temp'
# make sure the destination folder exists
$null = New-Item -Path $destination -ItemType Directory -Force
# get the files and move them to the destination
Get-ChildItem -LiteralPath $sourcePath -File | ForEach-Object {
    Move-Item -LiteralPath $_.FullName -Destination $destination
}