【问题标题】:Command to run PowerShell command from Windows CMD从 Windows CMD 运行 PowerShell 命令的命令
【发布时间】:2018-03-14 06:29:28
【问题描述】:

考虑:

(Get-Content Rel_DDL.SQL) | ForEach-Object { 
  $_ -replace "SWIFT [\d\.]+", "SWIFT 2.4.0" 
} | Set-Content Rel_DDL.SQL

上面的 PowerShell 代码将 SQL 文件中的 SWIFT 2.3.0 替换为 SWIFT 2.4.0,当我通过 PowerShell 运行时,它可以正常工作。

我想通过 Windows CMD 运行 PowerShell 命令,但出现错误。

【问题讨论】:

标签: powershell cmd


【解决方案1】:

在该 .bat 脚本中使用 powershell 命令。我不会写入与输入相同的文件。是的,我知道这是可行的,因为 Get-Content 会读取整个文件,但这不是一个好习惯。

powershell -NoProfile -Command "(Get-Content Rel_DDL.SQL) |" ^
    "ForEach-Object { $_ -replace 'SWIFT [\d\.]+', 'SWIFT 2.4.0' } |" ^
    "Out-File -FilePath Rel_DDL2.SQL -Encoding Default"

【讨论】:

    【解决方案2】:

    您可以在 CMD Windows 中使用带有 -command 参数的 Powershell.exe 命令。你试过了吗?

    -命令

    Executes the specified commands (and any parameters) as though they were
    typed at the Windows PowerShell command prompt, and then exits, unless
    NoExit is specified. The value of Command can be "-", a string. or a
    script block.
    

    如果 Command 的值为“-”,则从标准输入中读取命令文本。 如果 Command 的值为脚本块,则脚本块必须用大括号 ({}) 括起来。

    您只能在 Windows PowerShell 中运行 PowerShell.exe 时指定脚本块。脚本块的结果作为反序列化的 XML 对象而不是活动对象返回到父 shell。

    如果 Command 的值是字符串,Command 必须是命令中的最后一个参数,因为在命令之后键入的任何字符都被解释为命令参数。

    要编写运行 Windows PowerShell 命令的字符串,请使用以下格式:“& {}”,其中引号表示字符串,调用运算符 (&) 导致命令被执行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-13
      • 2014-09-16
      • 2018-10-12
      • 2018-04-11
      • 1970-01-01
      • 2013-04-30
      • 1970-01-01
      相关资源
      最近更新 更多