$folderItems = Get-ChildItem "C:\Users\John Doe\Music\iTunes\iTunes media\Music\" -Recurse
$newFolder = "C:\Users\John Doe\My Documents\MusicTemp\"
$foreach( $item in $folderItems )
{
if( $item.Attributes -eq "Archive" )
{
Copy-Item $item.FullName $newFolder
}
}
The code above kept failing due to PowerShell's de-escaping the strings multiple times internally and using special characters for pattern matching. Getting PowerShell to correctly recognize a literal square bracket in a path string turned out to be more complex than I thought.
I googled around and found a suitable workaround for this problem. Basically you would have to escape both open-square-bracket "[" and close-square-bracket "]" with backtick characters "`".
When using single-quote for string, two backticks are needed in front of a bracket in the string.
For double-quoted string, four backticks are needed in front of a bracket in the string.
The workaround PowerShell script is show below. I used double backticks to properly escape the square brackets.
$folderItems = Get-ChildItem "C:\Users\John Doe\Music\iTunes\iTunes Media\Music\" -Recurse
$newFolder = "C:\Users\Jone Doe\Music\iTunes\iTunes Media\MusicTemp\"
foreach($item in $folderItems)
{
if( $item.Attributes -eq "Archive")
{
$escapedFullName = $item.FullName.Replace('[', '``[').Replace(']', '``]')
Copy-Item $escapedFullName $newFolder
}
}
Here is the link that I got the workaround idea from.
No comments:
Post a Comment