Store the value of the cmdlet result in a Powershell variable

I would like to run the cmdlet and store the result value in a variable.

for example

C:\PS>Get-WSManInstance -enumerate wmicimv2/win32_process | select Priority 

It lists priorities with a headline. First example:

 Priority -------- 8 

How can I store them in a variable? I tried:

 $var=Get-WSManInstance -enumerate wmicimv2/win32_process | select Priority 

Now the variable: @{Priority=8} , and I wanted it to be 8 .

Question 2:

Is it possible to save two variables with one cmdlet? I mean save it after the pipeline.

 C:\PS>Get-WSManInstance -enumerate wmicimv2/win32_process | select Priority, ProcessID 

I would like to avoid this:

 $prio=Get-WSManInstance -enumerate wmicimv2/win32_process | select Priority $pid=Get-WSManInstance -enumerate wmicimv2/win32_process | select ProcessID 
+8
powershell
source share
2 answers

Use the -ExpandProperty Select-Object flag

 $var=Get-WSManInstance -enumerate wmicimv2/win32_process | select -expand Priority 

Refresh to answer another question:

Note that you can simply access the property:

 $var=(Get-WSManInstance -enumerate wmicimv2/win32_process).Priority 

So, to get a few of them in variables:

 $var=Get-WSManInstance -enumerate wmicimv2/win32_process $prio = $var.Priority $pid = $var.ProcessID 
+19
source share

Just enter the Priority property of the object returned from the pipeline:

 $var = (Get-WSManInstance -enumerate wmicimv2/win32_process).Priority 

(This will not work if Get-WSManInstance returns multiple objects. 2 )

For the second question: to get two properties, there are several options, perhaps the simplest is the presence of one variable * containing an object with two separate properties:

 $var = (Get-WSManInstance -enumerate wmicimv2/win32_process | select -first 1 Priority, ProcessID) 

and then use, assuming only one process:

 $var.Priority 

and

 $var.ProcessID 

If there are multiple processes, $var will be an array that you can index to get the properties of the first process (using the array literal @(...) syntax, so it is always set 1 ):

 $var = @(Get-WSManInstance -enumerate wmicimv2/win32_process | select -first 1 Priority, ProcessID) 

and then use:

 $var[0].Priority $var[0].ProcessID 

1 PowerShell is useful for the command line, but not so useful in scripts it has some additional logic when assigning the result of the pipeline to a variable: if objects are not returned, set $null , if one is returned, this object is assigned, otherwise an array is assigned. Forcing an array returns an array with zero, one or more (respectively) elements.

2 This change in PowerShell V3 (at the time of writing in Release Candidate), the use of the member property in an array of objects returns an array of values ​​for these properties.

+2
source share

All Articles