我有一个Powershell脚本,可以在VSCode中正常运行,但是从Powershell提示中,我遇到了错误。下面是输出。
→ C:\WINDOWS\system32› powershell.exe -file 'D:\Source\Repos\Powershell Scripts\SD-Report-Archive.ps1' -sourcePath 'D:\Archives\' -targetPath 'D:\Archives2\'
D:\Archives\
Get-ChildItem : Cannot find path 'D:\A' because it does not exist.
At D:\Source\Repos\Powershell Scripts\SD-Report-Archive.ps1:25 char:14
+ $files = Get-ChildItem -Recurse -File -Path $sourcePath
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (D:\A:String) [Get-ChildItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
正如您在输出的第二行看到的那样,我对要发送的参数值进行写输出,这是正确的。当我执行Get-ChildItem时,似乎将值截断为'D:\ A',但我不知道为什么。
Param(
[Parameter(Mandatory = $true)]
[string]$sourcePath,
[Parameter(Mandatory = $true)]
[string]$targetPath
)
function Copy-FilesIntoFolders {
param()
Write-Output $sourcePath;
$files = Get-ChildItem -Path $sourcePath -Recurse -File
...
}
Get-ChildItem:找不到路径'D:\ A',因为它不存在。
这里的反斜杠(\)在我看来就像一个转义字符。请尝试\\
在Windows上,PowerShell-必须-rebuilds命令行,以便调用外部程序。
[值得注意的是,大多数外部程序无法通过其CLI理解用single引用的字符串('...'
),因此在执行了自己的解析之后,PowerShell re-quotes结果(字符串化)使用double引号("..."
)如果认为有必要的话。]]
不幸的是,此重新引用在几个方面都破碎
:如果参数值不包含空格
,则使用no引号。 没有空格但带有特殊字符的值因此可能会破坏命令,尤其是在调用另一个shell,例如cmd.exe
时。cmd /c echo 'a&b'
中断,因为a&b
最终被传递了无]引号,并且&
在cmd.exe
中具有特殊含义>如果参数具有embedded
"
字符),则重新引用会自动<< [not"..."
转换为foo.exe 'Nat "King" Cole'
-请注意,内部foo.exe "Nat "King" Cole"
字符没有转义。 -大多数应用程序在解析时会生成一个"
(无双引号)。您必须进行转义
除了 PowerShell自身的转义要求,如果适用:Nat King Cole
或带双引号的foo.exe 'Nat \"King\" Cole'
(原文如此)。
foo.exe "Nat \`"King\`" Cole"
结尾,则尾随的\
在所产生的双引号字符串中是not
\
变为foo.exe 'a b\' c
-但是,大多数程序-包括PowerShell自己的CLI-都将foo.exe "a b\" c
解释为\"
字符。而不是用双引号引起来,导致对参数的误解,将其与下一个参数合并以产生"
同样,您必须通过[a b" c
:\
]
手动
。或者,如果参数碰巧是目录路径,其后缀foo.exe 'a b\\' c
是可选的,则只需省略后者。