Powershell 复制文件时无法传递路径变量

Powershell 复制文件时无法传递路径变量,powershell,Powershell,我正在尝试将一个文件从本地计算机复制到服务器路径。当我硬编码路径时,它会用相同的语法复制文件,但是当通过变量传递时,它会出错 Cannot bind argument to parameter 'Path' because it is null. + CategoryInfo : InvalidData: (:) [Copy-Item], ParameterBindingValidationException + FullyQualifiedErrorId :

我正在尝试将一个文件从本地计算机复制到服务器路径。当我硬编码路径时,它会用相同的语法复制文件,但是当通过变量传递时,它会出错

Cannot bind argument to parameter 'Path' because it is null.
    + CategoryInfo          : InvalidData: (:) [Copy-Item], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.CopyItemCommand
    + PSComputerName        : localhost
代码如下:

$SourcePath ="C:\Temp\Test.txt"
$DestinationPath ="\\ServerPath\Apps"

write-host $SourcePath 
write-host $DestinationPath 

Copy-Item $SourcePath $DestinationPath

你知道我为什么会得到这个吗。

如果你真的写了$DestinationPath=“\ServerPath\Apps”,那么这应该是正确的:

$DestinationPath ="\\ServerPath\Apps"
Serverpath总是以双反斜杠开始,并且根据转义序列(不同的语言,如C#),您必须将反斜杠加倍,因此

DestinationPath ="\\\\ServerPath\\Apps"

使用
Copy Item-whatif$SourcePath$DestinationPath
显示复制要使用的路径。仔细检查输入的路径是否正确。另外,使用
set strictmode-version'latest'
捕捉输入错误的变量名和未初始化的变量。谢谢您的回答。我试过了,但收到了相同的错误信息。不,你没有。WhatIf参数将使复制项的输出类似于
What if:对目标“item::”执行操作“copy File”
,即使目录不存在。如果变量未初始化,您将得到
无法检索变量“”,因为它尚未设置。
您是否只执行了以“复制项…”开头的行?如果是这样,变量是未知的。执行整个代码以测试它是否有效。Powershell的转义是backtick(`),因此不需要转义反斜杠。我像您提到的那样尝试了DestinationPath=“\\\\ServerPath\\Apps”。。但这似乎也不起作用,你只需要两个反斜杠。C#代码需要四个。vonPryz说powershell中的转义字符是`。。。顺便提一下您提供服务器的登录凭据了吗?请告诉我服务器的确切语法是什么DestinationPath@Ashis,我在Powershell中并不完美,但据我所知,答案中的第一个代码示例应该可以。