Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run multiple lines of PowerShell script in CMD

Tags:

powershell

cmd

I'm trying to the following powershell script in cmd. Here's a trivial example:

$path = "c:\"
cd $path
ls

Some PowerShell script of multiple lines and with quotation marks.

I read this post and @Alex's answer in this post, but putting multiple lines together with ; between them didn't work:

C:\Users\abcd>powershell "&c:\ ; ls"
& : The term 'c:\' is not recognized as the name of a cmdlet, function,
script file, or operable program. Check the spelling of the name, or if
a path was included, verify that the path is correct and try again.
At line:1 char:2
+ &c:\ ; ls
+  ~~~
    + CategoryInfo          : ObjectNotFound: (c:\:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

PS: My actual task is to run the following (I provided the trivial task above, since not everyone has the database).

$tabular_server = "abc_123\Tabular"

[Reflection.Assembly]::LoadWithPartialName("Microsoft.AnalysisServices")
$server = New-Object Microsoft.AnalysisServices.Server
$server.connect($tabular_server)
$db = $server.Databases.Item("db_name")

$db.Process("ProcessClear")
$db.Process("ProcessDefault")
$server.Disconnect()
like image 669
YJZ Avatar asked Jan 16 '18 22:01

YJZ


1 Answers

& is PowerShell's call operator. The operator is used for invoking commands/functions that come as strings (e.g. because someone wanted to represent them a variable, or their path contains spaces) as well as scriptblocks.

In your case it would suffice to just put your statements in a row, separated by semicolons:

powershell.exe -Command "$path = 'c:\'; cd $path; ls"

However, personally I prefer putting the statements in a scriptblock (which is where the call operator comes into play):

powershell.exe -Command "&{$path = 'c:\'; cd $path; ls}"

Either way should work, though. Beware that inside double-quoted command strings you need to either use single quotes or escape nested double quotes.

With all of that said, for longer, more complex PowerShell code inline execution via the -Command parameter is not recommended. Better write the code to a PowerShell script and run it like this:

powershell.exe -File "C:\path\to\your.ps1"
like image 149
Ansgar Wiechers Avatar answered Sep 20 '22 01:09

Ansgar Wiechers