简体   繁体   中英

batch multiline powershell command

I am trying to parse appsettings.json file to extract the connection string using a batch script.

I am spreading the command on multiple lines as it is quite long and hard to maintain:

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 ~

When I run this, I get an error: 'ForEach-Object' is not recognized as an internal or external command .

How do we properly break this command into multiple lines, store in a variable in order to make the powershell -command call much shorter?

@LotPings hinted to the solution which was to escape everything that batch can trip on.

So I end up with the following:

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 ~

In some situations, I also had to escape the parenthesis (especially inside a block)

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 ~

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM