I am trying to use the powershell Copy-Item command to copy a file to a UNC Path. Unfortunately, the UNC path on this production server has both spaces and an ampersand in the name. I've tried a bunch of things, but haven't had any luck yet. Could you please suggest a way to resolve this issue.
$InvokeExpressionPath = "\\servername\This Folder Has Spaces & Ampersand\Folder"
$TransfersSharePath = Invoke-Expression $InvokeExpressionPath
$TransfersSharePathFile = $InvokeExpressionPath + "\" + $FileName
Copy-Item -Path $CheckFileExists -Destination $TransfersSharePathFile -Force -ErrorAction SilentlyContinue
This is the error message that I get:
Invoke-Expression : At line:1 char:41
+ \\servername\This Folder Has Spaces & Ampersand\Folder
+ ~
The ampersand (&) character is not allowed. The & operator is reserved for future use; wrap an ampersand in double quotation marks ("&") to pass it as part of a string.
At E:\Scripts\CopyFile_Test.ps1:33 char:27
+ $TransfersSharePath = Invoke-Expression $InvokeExpressionPath
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ParserError: (:) [Invoke-Expression], ParseException
+ FullyQualifiedErrorId : AmpersandNotAllowed,Microsoft.PowerShell.Commands.InvokeExpressionCommand
If I try to wrap the ampersand in double-double quotes (""&""), I get this error when the code runs.
\\servername\This : The term '\\servername\This' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was
included, verify that the path is correct and try again.
At line:1 char:1
+ \\servername\This Folder Has Spaces "&" Ampersand\Folder
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (\\servername\This:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
DEBUG: This is the value of TransfersSharePathFile - \\servername\This Folder Has Spaces & Ampersand\Folder\file.zip
Copy-Item : Illegal characters in path.
At E:\Scripts\CopyFile_Test.ps1:36 char:5
+ Copy-Item -Path $CheckFileExists -Destination $TransfersSharePathFile -Force ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Copy-Item], ArgumentException
+ FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.CopyItemCommand
Thanks in advance for your help.