首页 > 解决方案 > 从 CMD 使用时如何正确引用 PowerShell 命令路径

问题描述

正常工作的基线命令:

以下命令正在 CMD 提示符下执行并成功运行。

"C:\Program Files\PowerShell\6.0.4\pwsh.exe" -NoLogo -NoProfile -NonInteractive -Command "&{D:\FooBar\myscript.ps1 -DependentAssembliesDirectoryPath 'D:\FooBar' -OutputPath 'D:\Baz Qux\output' -DocumentVersion 'whatever' -VisualStudioXmlDocumentationPaths 'D:\Baz Qux\input\my.xml' -AssemblyPaths  'D:\Baz Qux\input\my.exe','D:\Baz Qux\input\my1.dll','D:\Baz Qux\input\my2.dll','D:\Baz Qux\input\my3.dll' -MajorOpenApiSpecificationVersion 3 -MinorOpenApiSpecificationVersion 0 -Format YAML -DocumentDescriptionFilePath 'D:\Baz Qux\input\my.md'}; EXIT $LASTEXITCODE"

但是,当在 的路径中引入空格时myscript.ps1,该命令不再起作用。这是意料之中的,因为我需要正确引用路径。我无法弄清楚引用的正确方式。

引用命令的尝试无效:

我认为这可以基于在我的命令中引用其他路径的技术来工作,但这不起作用。

"C:\Program Files\PowerShell\6.0.4\pwsh.exe" -NoLogo -NoProfile -NonInteractive -Command "&{'D:\Foo Bar\myscript.ps1' -DependentAssembliesDirectoryPath 'D:\Foo Bar' -OutputPath 'D:\Baz Qux\output' -DocumentVersion 'whatever' -VisualStudioXmlDocumentationPaths 'D:\Baz Qux\input\my.xml' -AssemblyPaths  'D:\Baz Qux\input\my.exe','D:\Baz Qux\input\my1.dll','D:\Baz Qux\input\my2.dll','D:\Baz Qux\input\my3.dll' -MajorOpenApiSpecificationVersion 3 -MinorOpenApiSpecificationVersion 0 -Format YAML -DocumentDescriptionFilePath 'D:\Baz Qux\input\my.md'}; EXIT $LASTEXITCODE"

此命令会导致一堆错误,例如,

At line:1 char:119
+ ... ionsDocumentGeneration.ps1' -DependentAssembliesDirectoryPath 'D:\Ope ...
+                                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unexpected token '-DependentAssembliesDirectoryPath' in expression or statement.

At line:1 char:153
+ ... rectoryPath 'D:\Foo Bar' -OutputPath ...
+                 ~~~~~~~~~~~~
Unexpected token ''D:\Foo Bar'' in expression or statement.

同样,由于可能有点难以看出差异,因此基线命令和第二个命令的增量&{D:\FooBar\myscript.ps1更改为&{'D:\Foo Bar\myscript.ps1'在路径中引入空格并尝试引用。

请注意

我无法在 PowerShell 中调用该命令,因为它超出了我的控制范围。它必须在 cmd.exe 提示符下调用。

标签: powershellcmd

解决方案


问题是您需要&在 PowerShell 中使用才能调用通过变量引用和/或指定的命令名称/可执行文件路径:

因此,替换:

"&{'D:\Foo Bar\myscript.ps1' ... }; exit $LASTEXITCODE"

和:

"& { & 'D:\Foo Bar\myscript.ps1' ... }; exit $LASTEXITCODE"

也就是说,没有理由将*.ps1脚本的调用包装在脚本块调用 ( & { ... }) 中,因此您可以将命令简化为:

"& 'D:\Foo Bar\myscript.ps1' ...; exit $LASTEXITCODE"

推荐阅读