如何在命令行的路径中运行带有空格的powershell脚本?

Aws*_*ike 9 powershell scripting cmd

所以我尝试了一些不同的方法从命令行运行PowerShell脚本,每一个都返回一个错误.

这是这条路:

C:\Users\test\Documents\test\line space\PS Script\test.ps1
Run Code Online (Sandbox Code Playgroud)

我试过这些:

powershell -File '"C:\Users\test\Documents\test\line space\PS Script\test.ps1"'

powershell "& ""C:\Users\test\Documents\test\line space\PS Script\test.ps1"""

Powershell "& 'C:\Users\test\Documents\test\line space\PS Script\test.ps1'"

Powershell -File 'C:\Users\test\Documents\test\line space\PS Script\test.ps1'"
Run Code Online (Sandbox Code Playgroud)

我收到所有这些错误:

&:术语"C:\ Users\test\Documents\test\line space\PS Script \"不被识别为cmdlet,函数,脚本文件或可操作程序的名称.检查名称的拼写,或者如果包含路径,请验证路径是否正确,然后重试.

处理-File''C:\ Users\test\Documents\test\line space\PS Script \''失败:不支持给定路径的格式.为-File参数指定有效路径.

任何帮助将不胜感激!

vrd*_*dse 20

-File 参数

如果要从命令行运行powershell.exe -File,则必须在doubleqoutes(")中设置带空格的路径.单引号(')仅由powershell识别.但是,当命令行调用powershell.exe(因此处理文件参数)时,您必须使用".

powershell.exe -File "C:\Users\test\Documents\Test Space\test.ps1" -ExecutionPolicy Bypass
Run Code Online (Sandbox Code Playgroud)

-Command 参数

如果您使用的-Command参数,而不是-File,该-Command内容是由PowerShell的处理,因此,你可以-在这种情况下必须-使用'里面".

powershell.exe -Command "& 'C:\Users\test\Documents\Test Space\test.ps1'" -ExecutionPolicy Bypass
Run Code Online (Sandbox Code Playgroud)

双引号由命令行处理,并且& 'C:\Users\test\Documents\Test Space\test.ps1'是PowerShell实际处理的命令.

解决方案1显然更简单.

请注意-Command,如果您未指定任何参数,那么它也是使用的默认参数.

powershell.exe "& 'C:\Users\test\Documents\Test Space\test.ps1'" -ExecutionPolicy Bypass
Run Code Online (Sandbox Code Playgroud)

这也行得通.

-EncodedCommand 参数

您可以将命令编码为Base64.这解决了许多"引用"问题,有时(但不是在你的情况下)是唯一可行的方法.

首先,您必须创建编码命令

$Command = "& 'C:\Users\test\Documents\Test Space\test.ps1'" 
[Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($Command))
Run Code Online (Sandbox Code Playgroud)

然后你可以-EncodedCommand像这样使用参数

powershell.exe -EncodedCommand JgAgACcAQwA6AFwAVQBzAGUAcgBzAFwAdABlAHMAdABcAEQAbwBjAHUAbQBlAG4AdABzAFwAVABlAHMAdAAgAFMAcABhAGMAZQBcAHQAZQBzAHQALgBwAHMAMQAnAA== -ExecutionPolicy Bypass
Run Code Online (Sandbox Code Playgroud)

  • 做得很好; 另外:在PowerShell _Core_中,`-File`现在是默认值(这个改变是支持Unix shebang行所必需的). (2认同)
  • 我觉得这是一个比接受的答案更好的答案。仅使用 -file 参数将文件路径放在引号中对我来说根本不起作用。 (2认同)

小智 18

尝试这个:

& "C:\Users\test\Documents\test\line space\PS Script\test"
Run Code Online (Sandbox Code Playgroud)

  • 他试图使用`cmd`,所以我假设他是从`.cmd` 或`.bat` 文件调用它。PS Invoke (`&`) 操作符对他没有任何好处。 (4认同)

The*_*le1 8

在您的示例中,您无缘无故地混合了引号和双引号。

IF EXIST "C:\Users\test\Documents\test\line space\PS Script\test.ps1" (
  powershell -ExecutionPolicy Unrestricted -File "C:\Users\test\Documents\test\line space\PS Script\test.ps1"
)
Run Code Online (Sandbox Code Playgroud)