I need to replace square brackets in filenames, and I've successfully created (and validated at the console) a -replace
. Now I'm trying to Move-Item
to a new directory because this bug in Powershell 2.0 prevents me from doing a simple file rename.
Here's my script:
$txtPath = "c:\users\xxxxxx\desktop\cgc\tx" #source files
$txtPath2 = "c:\users\xxxxxx\desktop\cgc\tx2" #renamed files
Get-ChildItem $txtPath | foreach {
Move-Item -literalpath C:\users\xxxxxx\desktop\test001 ($_.Name -replace '\{|}','_')
}
Here's what's happening: I was using the $txtPath2
variable, but kept getting "cannot bind to null directory" errors, so I explicitly coded to the path to see if there was something odd with how the variable parsed. Now, I get this error:
Move-Item : Cannot move item because the item at 'C:\users\xxxxxx\desktop\test001' does not exist.
At C:\users\xxxxxx\desktop\cgc\rni.ps1:5 char:10
+ Move-Item <<<< -literalpath C:\users\xxxxxx\desktop\test001 ($_.Name -replace '\{|}','_')
+ CategoryInfo : InvalidOperation: (:) [Move-Item], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.MoveItemCommand
Here's what's odd: I create the new directory. I run the script, watch it vanish from my desktop as the script fails. WTF? I've quit and restarted the console application to flush any variables. I've tried different flavors of variable vs. constant in the Move-Item
line. Unless there's a Move-Item
parameter that I'm missing, I really have no idea what's going on. Does anyone else see anything that would cause my file to be deleted?
EDIT: After editing to
Get-ChildItem $txtPath | % { [system.io.file]::Move($_.fullname, ($i.FullName -replace '\[|\]', '') ) }
I get a new error:
Exception calling "Move" with "2" argument(s): "Empty file name is not legal.
Parameter name: destFileName"
At C:\users\x46332\desktop\cgc\rni.ps1:6 char:52
+ Get-ChildItem $txtPath | % { [system.io.file]::Move <<<< ($_.fullname, ($i.FullName -replace '\[|\]', '') ) }
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException