批处理多行 powershell 命令

batch multiline powershell command

我正在尝试解析 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 调用更短?

@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 ~