0

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?

  • it does not work since that is not how one calls a PoSh script from a BAT file. [*grin*] please, read the docs on how to use `powershell.exe` when called from BAT or CMD files [or other programs]. – Lee_Dailey Jul 31 '20 at 10:34
  • You can begin by getting rid of the unneeded `-Executionpolicy ByPass` part. – Compo Jul 31 '20 at 11:06
  • If I remove it, it won't work ... is something missing? – batchprog2020 Jul 31 '20 at 11:44
  • Yes, you cannot expect a multiline powershell command to work like that. `-Executionpolicy` is for use when running powershell scripts, _(generally `*.ps1`)_. You're not running a powershell script, you're running a powershell command. – Compo Jul 31 '20 at 11:54
  • Why don't you use import-csv and export-csv? – js2010 Jul 31 '20 at 17:10

1 Answers1

1

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.

Aacini
  • 65,180
  • 12
  • 72
  • 108