batchprog2020
batchprog2020

Reputation: 23

powershell command into batch - it doesn't work

I would like to run a powershell command with batch. My powershell command:

gc 'C:\Users\Test\Test-01\source.csv' | %{
    $cols = $_.split(";")
    1..$cols[-2]| %{
        "$($cols[0..9] -join ';');$($cols[(9+$_)] -join ';');$($cols[(24+$_)] -join ';');;;;;;;;;;;;;;;$($cols[-2]);"
    }
} | sc "C:\Users\Test\Test-01\target.csv"

My batch command:

powershell -Executionpolicy ByPass gc 'C:\Users\Test\Test-01\source.csv' | %{
        $cols = $_.split(";")
        1..$cols[-2]| %{
            "$($cols[0..9] -join ';');$($cols[(9+$_)] -join ';');$($cols[(24+$_)] -join ';');;;;;;;;;;;;;;;$($cols[-2]);"
        }
    } | sc "C:\Users\Test\Test-01\target.csv"

It doesn't work. But why? Can someone say why?

Upvotes: 0

Views: 214

Answers (1)

Aacini
Aacini

Reputation: 67216

To embedd PowerShell code into a .BATch file you just need to pay attention to a few details:

  • Eliminate all -ExecutionPolicy and -Command stuff. Just write pure powershell code after powershell command.
  • Terminate each line with caret: ^
  • Terminate each complete powershell command with semicolon: ;
  • Escape each quote with a backslash: \"like this\" or change they by apostrophe: 'like this'

And these modifications are required because Batch file special characters:

  • Duplicate percent signs: %%
  • Escape these characters: | > < & with caret, like this: ^| ^> ^< ^&

In your case this is the final, working code:

powershell  ^
gc 'C:\Users\Test\Test-01\source.csv' ^| %%{  ^
    $cols = $_.split(\";\");  ^
    1..$cols[-2]^| %%{  ^
        \"$($cols[0..9] -join ';');$($cols[(9+$_)] -join ';');$($cols[(24+$_)] -join ';');;;;;;;;;;;;;;;$($cols[-2]);\"  ^
    }  ^
} ^| sc \"C:\Users\Test\Test-01\target.csv\"

You may also review this question.

Upvotes: 1

Related Questions