Powershell参数似乎可以截断值

问题描述 投票:1回答:2

我有一个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
...
}
powershell get-childitem
2个回答
0
投票

Get-ChildItem:找不到路径'D:\ A',因为它不存在。

这里的反斜杠(\)在我看来就像一个转义字符。请尝试\\


0
投票

在Windows上,PowerShell-必须-rebuilds命令行,以便调用外部程序

[值得注意的是,大多数外部程序无法通过其CLI理解用single引用的字符串('...'),因此在执行了自己的解析之后,PowerShell re-quotes结果(字符串化)使用double引号("..."如果认为有必要的话。]]

不幸的是,此重新引用在几个方面都破碎

  • 如果参数值不包含空格

    ,则使用no引号。 没有空格但带有特殊字符的值因此可能会破坏命令,尤其是在调用另一个shell,例如cmd.exe时。
    • 例如,cmd /c echo 'a&b'中断,因为a&b最终被传递了无]引号,并且&cmd.exe中具有特殊含义>
    • 如果参数具有embedded

    • 双引号("字符),则重新引用会自动<< [not
    << escape >>
  • ,以便在语法上正确嵌入[ C0]或未引用的文字使用:
      例如"..."转换为foo.exe 'Nat "King" Cole'-请注意,内部foo.exe "Nat "King" Cole"字符没有转义。 -大多数应用程序在解析时会生成一个
    • different
    字符串,即"(无双引号)。

    您必须进行转义

  • 手动
  • 除了 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是可选的,则只需省略后者。
© www.soinside.com 2019 - 2024. All rights reserved.