【问题标题】:batch multiline powershell command批处理多行 powershell 命令
【发布时间】:2019-08-27 19:57:40
【问题描述】:

我正在尝试解析 appsettings.json 文件以使用批处理脚本提取连接字符串。

我将命令分布在多行上,因为它很长且难以维护:

set ps_GetConnectionString=(Get-Content 'appsettings.json' -Raw)^
 | ForEach-Object { $_ -replace '(?ms)/\*.*?\*/' -replace '[\s\t]+//.*' }^
 | ConvertFrom-Json^ 
 | Select -expand ConnectionStrings | Select default^ 
 | ConvertTo-Csv -Delimiter ~

当我运行这个时,我得到一个错误:'ForEach-Object' is not recognized as an internal or external command

我们如何正确地将这个命令分成多行,存储在一个变量中以使powershell -command 调用更短?

【问题讨论】:

  • 我假设上面的脚本/代码在.bat 文件中?你不能将 PowerShell 部分转储到 ps1 / 脚本文件中并以这种方式执行吗?单独的.bat 调用 PowerShell 脚本命令背后的原因是什么?
  • @gravity 我有一个.bat 文件,其中多次调用powershell -command 以执行某些仅通过批处理不太容易完成的任务。由于安全限制,我试图避免在 powershell 中编写所有内容
  • 你想在 bat 变量中构建 ps-script 的方式行不通。要使 ^ 批处理行继续符号起作用,它必须在双引号字符串之外,您 OTOH *need 转义 PowerShell 管道符号和不用于批处理 => 的内容确实如此批处理错误消息的意思。
  • 为什么人们仍在尝试将 PowerShell 包装在批处理文件中?别了。

标签: powershell batch-file multiline


【解决方案1】:

@LotPings 暗示了一个解决方案,即逃避批次可能绊倒的所有事情。

所以我最终得到以下结果:

set ps_GetConnectionString=(Get-Content 'appsettings.json' -Raw)^
 ^| ForEach-Object { $_ -replace '(?ms)/\*.*?\*/' -replace '[\s\t]+//.*' }^
 ^| ConvertFrom-Json^ 
 ^| Select -expand ConnectionStrings ^| Select default^ 
 ^| ConvertTo-Csv -Delimiter ~

在某些情况下,我还必须转义括号(尤其是在块内)

set ps_GetConnectionString=^(Get-Content 'appsettings.json' -Raw^)^
 ^| ForEach-Object { $_ -replace '(?ms)/\*.*?\*/' -replace '[\s\t]+//.*' }^
 ^| ConvertFrom-Json^ 
 ^| Select -expand ConnectionStrings ^| Select default^ 
 ^| ConvertTo-Csv -Delimiter ~

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-15
    • 1970-01-01
    • 2020-09-10
    • 1970-01-01
    • 2011-08-27
    • 1970-01-01
    • 2018-02-14
    • 1970-01-01
    相关资源
    最近更新 更多