【问题标题】:Calling Powershell script from CMD with paths as parameters使用路径作为参数从 CMD 调用 Powershell 脚本
【发布时间】:2020-10-08 15:38:20
【问题描述】:

我无法通过传递两个参数(路径)使这个 cmd 命令运行 powershell 脚本。

C:\WINDOWS\System32>powershell -command \"C:\Apps\Scripts\Test\testing.ps1" \"\\Data1\dataholder$\office\J Smith\backup\" \"\\Data1\dataholder$\office\J Smith\backup2\"

我收到以下错误:

At line:1 char:36
+ ... ps\Scripts\Test\testing.ps1 "\\Data1\dataholder$\office\ ...
+                                  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unexpected token '\\Data1\dataholder$\office' in expression or statement.
At line:1 char:146
+ ... Smith\backup" "\\Data1\dataholder$\office\J Smith\backup2"
+                                                                         ~
The string is missing the terminator: ".
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnexpectedToken

知道为什么会失败吗?

我不得不修改通向脚本的路径。现在命令看起来像这样:

C:\WINDOWS\System32>powershell -command \"C:\Apps\Scripts\Power test\testing.ps1" \"\\Data1\dataholder$\office\J Smith\backup\" \"\\Data1\dataholder$\office\J Smith\backup2\"

由于脚本路径中的空间而导致失败,知道如何处理吗?

【问题讨论】:

  • 你的第一个引号转义是不必要的\"C:\Apps\Scripts\Test\testing.ps1" --> "C:\Apps\Scripts\Test\testing.ps1"

标签: powershell cmd path parameter-passing


【解决方案1】:

您需要反斜杠转义引号,以便从 cmd shell 发送到 PowerShell:

powershell -command "& \"C:\Apps\Scripts\Power test\testing.ps1\" \"\\Data1\dataholder$\office\J Smith\backup\" \"\\Data1\dataholder$\office\J Smith\backup2\""

如果您的程序或脚本文件有空格,您需要使用调用运算符 (&) 调用它,并将其包含在发送到-Command 的字符串中。注意映射到-Command 的整个值/字符串周围的双引号。

注意:内部双引号在这里起作用,因为$\ 取代。如果以 dataholder$folder 为例,则需要单引号或转义 $,因为 PowerShell 会尝试将 $folder 解释为变量。

【讨论】:

  • 谢谢,脚本路径中的空格怎么处理? C:\Apps\Scripts\Power test\testing.ps1
  • 我对其进行了编辑以展示如何做到这一点。您需要使用调用运算符&,将整个命令用引号括起来,然后转义内部双引号。
【解决方案2】:

这是一种反引用空格的方法。

type "my script.ps1"

echo $args[0]


powershell .\my` script.ps1 hi` there

hi there

或策略性地放置单引号。如果第一个字符不是引号,则可以执行某些操作。反斜杠之前的引号不起作用。

powershell .\'my script.ps1' 'hi there'

hi there

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-06
    • 2019-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多