Powershell Copy-item 在带有 space 和符号的 unc 路径上失败

Powershell Copy-item fails on unc path with space and ampersand

我正在尝试使用 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

在此先感谢您的帮助。

尝试:

$InvokeExpressionPath = '\servername\This Folder Has Spaces & Ampersand\Folder'

应该做这份工作

路径中的符号或空格不是问题。您正在尝试使用 Invoke-Expression 提供路径作为参数,这不是有效命令。摆脱 $TransfersSharePath 行并直接使用 $InvokeExpressionPath 中的内容。以防万一,只需将双引号更改为单引号即可。另外,我建议您使用 Join-Path 而不是连接字符串来创建路径。

非常感谢 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