powershell - Powershell 参数似乎截断了值
问题描述
我有一个在 VSCode 中运行良好的 Powershell 脚本,但是从 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
正如您在输出的第 2 行所看到的,我对要发送的参数值进行了写入输出,并且它是正确的。当我执行 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
...
}
解决方案
在 Windows 上,PowerShell(必须)重建命令行以调用外部程序。
值得注意的是,大多数外部程序无法通过其 CLI理解单引号字符串 ( ),因此在执行了自己的解析之后,PowerShell在认为有必要时使用双引号 ( )重新引用生成的(字符串化的)参数。'...'
"..."
不幸的是,这种重新引用在几个方面被破坏了:
如果参数值不包含空格,则不应用引用。因此,没有空格但带有特殊字符的值可能会破坏 commands,尤其是在调用另一个shell时。
cmd.exe
- 例如,
cmd /c echo 'a&b'
breaks,因为最终不带引号a&b
传递,并且在&
cmd.exe
- 例如,
如果参数嵌入了双引号 (
"
chars.),则重新引用不会自动转义它们以在语法上正确嵌入"..."
或不带引号的文字使用:例如,
foo.exe 'Nat "King" Cole'
被翻译为foo.exe "Nat "King" Cole"
- 注意内部"
字符没有转义。- 当被大多数应用程序解析时,这会导致不同的字符串,即Nat King Cole
(没有双引号)。除了PowerShell 自己的转义要求(如果适用)之外,您还必须手动执行转义:或者,使用双引号(原文如此)。
foo.exe 'Nat \"King\" Cole'
foo.exe "Nat \`"King\`" Cole"
同样 - 就像你的情况一样 -如果参数有空格并以 结尾
\
,那么尾随不会在生成的双引号 string 中转义\
,这会破坏参数语法:例如,
foo.exe 'a b\' c
变成foo.exe "a b\" c
- 然而,大多数程序 - 包括 PowerShell 自己的 CLI - 将 解释\"
为转义"
字符。而不是结束双引号,导致对参数的误解,将其与下一个参数合并以导致a b" c
您必须再次手动执行转义,方法是加倍
\
:foo.exe 'a b\\' c
- 或者,如果参数恰好是尾随
\
是可选的目录路径,则只需省略后者。
- 或者,如果参数恰好是尾随
推荐阅读
- php - 从 PHP 调用 Ajax
- c - 睡眠时信号处理比旋转慢?
- javascript - 如何将 FontAwesome 放在 select 标签的值中
- linux - 如何使用进程 ID 和端口来识别网站?
- asp.net-core - ASP.NET Core 2.2 已删除用户已授权
- php - 使用 Sessions 在 PHP 中显示不同的登录错误
- php - 比较数组中的值并将其从数组中删除 - php
- angular - 以角度形式预先填充输入
- google-apps-script - 如果单元格 = 0 Google 表格,则一次删除多行
- google-bigquery - 在 BigQuery 界面中使用变量名称创建表