If you use the PowerShell pipeline binding function, you can make it much simpler and eliminate the need for an explicit Foreach-Object for example:
ls *.gif | Move-Item -Destination {$_ -replace '\[|\]',''} -WhatIf
This works because the LiteralPath parameter LiteralPath configured to bind ByPropertyName . However, you may wonder where it gets the property named "LiteralPath" from at the output of Get-ChildItem (alias ls). Well, he does not find this property name, however the LiteralPath parameter has a LiteralPath alias defined, which exists for every object displayed by Get-ChildItem . This is due to the LiteralPath parameter. Another tip of the speed here is that since the Destination parameter is also associated with the pipeline (ByPropertyName), you can use scriptblock to provide the value. And inside this script block, you have access to the pipeline object.
Inside the script block, the -replace operator is used to come up with a new name based on the original name. Although I could use $_.FullName or even $_.Name in this case (assuming you want to essentially rename files in the same directory), I only use $_ . Since -replace is a string operator, it will force $_ to the string before using it. You can see what it will be by doing:
ls *.gif | Foreach {"$_"}
What is the full path in this case, but you have to be careful because you do not always get the full path, for example:
ls | Foreach {"$_"}
only displays the file name. In your examples (rename to the same directory) this does not matter, but in other cases this happens. It's probably a good practice to just be explicit and use $_.Name or $_.FullName in the script, but when hacking this stuff on the console, I usually use only $_ . Saying: this is a sharp stick, do not poke your eye. :-)
Keith hill
source share