-1

I want to run .bat-script which calls some powershell function inside it. Function is not so small, so I want to split it. But I cannot do it, escape symbols doesn`t help ( ` ,^). Script example:

set file=%1

set function="$file=$Env:file; ^
              $hash = CertUtil -hashfile $file SHA256 | Select -Index 1"

powershell -command %function%
approximatenumber
  • 467
  • 1
  • 7
  • 22

2 Answers2

4

You can leave the quote at the end of each line like so:

set file=%1

set function="$file=$Env:file; "^
           "$hash = CertUtil -hashfile $file SHA256 | Select -Index 1; "^
           "example break line further...."

powershell -command %function%

The ^ works as multiline character but it also escapes the first character, so also a quote would be escaped.

AutoTester213
  • 2,714
  • 2
  • 24
  • 48
1

Do not mix batchfile syntax with PowerShell. As @Stephan mentioned $function= won't work in batch file. You need to use set function= instead. Let's say I want to execute the following:

Get-Process
Get-ChildItem

Then the code should look like this:

set function=Get-Process; ^
Get-ChildItem;

And you start PowerShell with:

powershell -noexit -command %function%

-noexit added so that you can verify that the code was successfully executed.

Also keep in mind that what you pass to PowerShell is batch multiline and in PowerShell it's visible as one line so you have to remember about semicolon (which you actually do but I'm leaving this comment here for future readers).


There's also another option how to pass variable from batch script to PowerShell. You can do it like this:

set name=explorer

set function=get-process $args[0]; ^
get-childitem

powershell -noexit  -command "& {%function% }" %name%

Explanation:

$args[0] represents first argument passed to the scriptblock. To pass that argument, add %name% after the scriptblock while starting powershell. Also, as pointed out in this answer (credits to @Aacini for pointing this out in comments), you have to add & operator and keep your scriptblock inside curly brackets { }.


Sidenote: to be honest, I'd avoid running scripts like this. Much simpler way would be to just save the file as .ps1 and run this in your batch file:

powershell -noexit -file .\script.ps1
Robert Dyjas
  • 4,979
  • 3
  • 19
  • 34