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

时间:2017-08-18 15:44:01

标签: powershell cmd scripting

所以我尝试了一些不同的方法从命令行运行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参数指定有效路径。

非常感谢任何帮助!

5 个答案:

答案 0 :(得分:12)

-File参数

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

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

-Command参数

如果您使用-Command参数而不是-File,则-Command内容由PowerShell处理,因此您可以 - 并且在这种情况下必须 - 使用{{1} } '

"

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

解决方案1显然更简单。

请注意,& 'C:\Users\test\Documents\Test Space\test.ps1'也是使用的默认参数,如果您未指定任何参数。

-Command

这也可行。

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

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

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

-EncodedCommand

然后您可以使用$Command = "& 'C:\Users\test\Documents\Test Space\test.ps1'" [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($Command)) 这样的参数

-EncodedCommand

答案 1 :(得分:3)

试试这个:

PS C:\> & "C:\Users\test\Documents\test\line space\PS Script\test"

答案 2 :(得分: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"
)

答案 3 :(得分:0)

如果您使用参数,则可以按照以下步骤操作

powershell.exe -command "& {&'C:\A B C\foo.ps1' param1 param2}"

在此感谢Hesham A. Amin:-)

答案 4 :(得分:0)

要添加到本主题:

我需要用空格传递参数

我正在将文件拖放到批处理文件上,并且该文件在服务器上已关闭,路径和/或文件名中带有空格。经过测试以上答案,我得到了这个工作。请注意,在启动powershell之前,我将切换到工作目录。

批处理文件:

pushd O:\Data\QuickList
start powershell -noexit -Command ".\QuickList.ps1 -datafile '%1'"
popd
相关问题