1

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

3
  • What problems are you having with this code? Commented Feb 3, 2023 at 12:36
  • Your syntax is all wrong. Please read about Rename-Item before asking a question. Commented Feb 3, 2023 at 12:44
  • i read this and i tried diffrent types of syntax. (i updated the question). every time the same error Commented Feb 3, 2023 at 12:54

1 Answer 1

1

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 } 
2
  • 1
    thanks! i switched to move with -force. and the -LiteralPath fixed it :-) Commented Feb 3, 2023 at 15:31
  • @Err0r Sorry, forgot to add -Force to the New-Item cmdlet. Added it now Commented Feb 3, 2023 at 15:36

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.