Home > OS >  How to insert new line char to powershell script variable called from batch script with single quote
How to insert new line char to powershell script variable called from batch script with single quote

Time:08-19

I have been wondering some time how to add property to end of the properties file from powershell script included to batch file. Example is in the else branch. It seems that single quotes are causing the problem but I am not aware how to get rid of them or how to add the new line right way. Don't mind the other parts of the script.

powershell -Command "&{"^
    "$file = 'conf\my.properties';"^
    "$regex = '(my.boolean.property=(?i)(true|false))';"^
    "$search = (Get-Content $file | Select-String -Pattern 
        'my.boolean.property').Matches.Success;"^
    "if($search){ (Get-Content $file) -replace $regex, 'my.boolean.property=false' | Set- 
        Content $file; }"^
    "else { Add-Content $file '`nmy.boolean.property=false' };"^
     "}"

CodePudding user response:

Two options come to mind that don't require double-quotes:

"else { Add-Content $file ([Environment]::NewLine   'my.boolean.property=false') };"^

This will grab the OS-default newline sequence from the [Environment] type and prefix the string with it.

Alternatively, let Add-Content add an empty newline by piping an extra empty string to it:

"else { '','my.boolean.property=false' | Add-Content $file };"^
  • Related