IT漫步

技术生活札记©Yaohui

Powershell: Copy-Item doesn’t work when file name contains square bracket ([]) characters

I have a file whose name contains square bracket characters, and I want to copy the file to another location via Powershell.

So I use the Copy-Item founcation to do this. like this:

Copy-Item -Path "C:\FileTest\1\[Control]Test.txt" -Destination "C:\FileTest\2\[Control]Update.txt"

No errors occurred when executing the script, but the target file was not copied either.

After looking through the official document, I found that changing the -Path parameter to the -LiteralPath parameter will make the script work. It is because the -Path parameter allows wildcard characters, square bracket characters will be treated as special usage. For example:

Copy-Item -LiteralPath "C:\FileTest\1\[Control]Test.txt" -Destination "C:\FileTest\2\[Control]Update.txt"

References:
– https://docs.microsoft.com/zh-cn/powershell/module/microsoft.powershell.management/copy-item
– https://stackoverflow.com/questions/19000033/copy-item-a-file-with-strange-characters-in-filename-i-e

Leave a Reply

Your email address will not be published.

Proudly powered by WordPress