Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble with powershell commas

Im trying to write a very brief powershell script that runs a few commands, pipes their output to a text file, and then does a search against a keyword.

I cant figure out what to change however for this line:

wmic service get name, startname | out-File "$pwd\admin\wmic.txt"

WMIC.exe : Invalid GET Expression.
At \\test.ps1:7 char:5
+ wmic <<<<  service get name startname | out-File "$pwd\admin\wmic.txt"
+ CategoryInfo          : NotSpecified: (Invalid GET Expression.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError

I believe the error is generated from the ',' as powershell uses the comma to create an array. Any thoughts or suggestions?

Thanks

like image 368
Jingles177 Avatar asked Jun 22 '12 17:06

Jingles177


People also ask

How do you use commas in PowerShell?

Commas are array separators in PowerShell. You should either escape them or encase the parameter in double quotes and then write some logic to split your string that contains commas. E.g. Your cmdlet call should be: Get-Weather "Shrewsbury,MA?

What does $() mean in PowerShell?

Subexpression operator $( ) For a single result, returns a scalar. For multiple results, returns an array. Use this when you want to use an expression within another expression. For example, to embed the results of command in a string expression. PowerShell Copy.

What does $_ in PowerShell mean?

The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.


2 Answers

wmic service get name"," startname| out-File "$pwd\admin\wmic.txt"

This is easy to resolve comma, no change at all.

like image 141
Raymond Cheng Avatar answered Oct 01 '22 09:10

Raymond Cheng


Beginning with PowerShell 3.0 there is the new escaping operator --% available (see magic parameter in the release notes):

wmic --% service get name, startname | out-File "$pwd\admin\wmic.txt"

This operator is known as the stop-parsing operator, and it instructs PowerShell to stop interpreting input from that point forward as PowerShell commands or expressions (see docs here).

like image 44
sevenforce Avatar answered Oct 01 '22 10:10

sevenforce