-2

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?

7
  • 2
    The above script/code, I assume, is in a .bat file? Could you not dump the PowerShell portion into a ps1 / script file and execute that way? What's the reasoning behind a separate .bat calling PowerShell script commands? Commented Aug 27, 2019 at 20:00
  • This might help Commented Aug 27, 2019 at 20:03
  • @gravity I have one .bat file with multiple calls to powershell -command in order to perform certain tasks that are not very easy to do with batch only. I am trying to avoid writing everything in powershell due to security restrictions Commented Aug 27, 2019 at 20:04
  • 1
    The way you want to build the ps-script in bat variables can't work. To have the ^ batch line continuation symbol work, it has to be outside of double quoted strings, which you OTOH *need to escape PowerShell pipe symbols and content not destined for batch => that exactly does the batch error message mean. Commented Aug 27, 2019 at 20:22
  • 1
    Why are people still trying to wrap PowerShell in batch files? Stop it. Commented Aug 28, 2019 at 7:48

1 Answer 1

1

@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 ~
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.