我正在尝试使用powershell Copy-Item命令将文件复制到UNC路径。遗憾的是,此生产服务器上的UNC路径名称中包含空格和与号。我试过很多方法,但都还没成功。你能建议一下解决这个问题的方法吗?
$InvokeExpressionPath = "\\servername\This Folder Has Spaces & Ampersand\Folder"
$TransfersSharePath = Invoke-Expression $InvokeExpressionPath
$TransfersSharePathFile = $InvokeExpressionPath + "\" + $FileName
Copy-Item -Path $CheckFileExists -Destination $TransfersSharePathFile -Force -ErrorAction SilentlyContinue
这是我得到的错误消息:
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
如果我试图用双引号(""&"")把“”和“”括起来,代码运行时就会出现这个错误。
\\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
提前感谢您的帮助。
发布于 2020-06-30 17:17:43
路径中的和号或空格不是问题。您正在尝试使用Invoke-Expression
提供路径作为参数,这不是有效的命令。去掉$TransfersSharePath
行,直接使用$InvokeExpressionPath
中的内容。只需将双引号改为单引号,以防万一。另外,我建议您使用Join-Path
创建路径,而不是连接字符串。
发布于 2020-07-01 12:46:48
非常感谢AdamL和dread1的帮助。我使用了这两个建议。作为参考,这就是工作代码现在的样子。
$InvokeExpressionPath = "\\servername\This Folder Has Spaces & Ampersand\Folder"
$TransfersSharePathFile = Join-Path -Path $InvokeExpressionPath -ChildPath $FileName
$TransfersSharePathFile = $InvokeExpressionPath + "\" + $FileName
Copy-Item -Path $CheckFileExists -Destination $TransfersSharePathFile -Force -ErrorAction SilentlyContinue
发布于 2020-06-30 17:12:52
尝试:
$InvokeExpressionPath = '\\servername\This Folder Has Spaces & Ampersand\Folder'
应该能胜任这项工作
https://stackoverflow.com/questions/62653883
复制相似问题