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

问题描述 投票:3回答:3

所以我尝试了一些不同的方法从命令行运行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"'

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'"

我收到所有这些错误:

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

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

任何帮助将不胜感激!

powershell cmd scripting
3个回答
2
投票

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

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"
)

11
投票

-File Parameter

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

powershell.exe -File "C:\Users\test\Documents\Test Space\test.ps1" -ExecutionPolicy Bypass

-Command Parameter

如果你使用-Command参数而不是-File,那么-Command内容由PowerShell处理,因此你可以 - 并且在这种情况下必须 - 在'中使用"

powershell.exe -Command "& 'C:\Users\test\Documents\Test Space\test.ps1'" -ExecutionPolicy Bypass

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

解决方案1显然更简单。

请注意,如果您未指定任何参数,则-Command也是使用的默认参数。

powershell.exe "& 'C:\Users\test\Documents\Test Space\test.ps1'" -ExecutionPolicy Bypass

这也行得通。

-EncodedCommand Parameter

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

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

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

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

powershell.exe -EncodedCommand JgAgACcAQwA6AFwAVQBzAGUAcgBzAFwAdABlAHMAdABcAEQAbwBjAHUAbQBlAG4AdABzAFwAVABlAHMAdAAgAFMAcABhAGMAZQBcAHQAZQBzAHQALgBwAHMAMQAnAA== -ExecutionPolicy Bypass

2
投票

试试这个:

PS C:\> & "C:\Users\test\Documents\test\line space\PS Script\test"
© www.soinside.com 2019 - 2024. All rights reserved.