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