Reputation:
When using Get-Process how can I use a string as -Name?
$program = "MyProgram"
Get-Process $program
Instead of
Get-Process -MyProgram
Upvotes: 6
Views: 30542
Reputation: 5140
Powershell will accept the name, no matter what.
Get-Process Firefox
Will return all running Firefox. Likewise, arrays will work too:
Get-Process Firefox, iexplore
Or
$Proc = @("Firefox","iexplore")
Get-Process $Proc
Declares an array explicitly, then checks for each running process.
Of course, as previously stated, you can and should use -Name for clarity. But nothing really changes. The script should still read something like:
$Proc = @("Firefox","iexplore")
Get-Process -Name $Proc
There is also the Where-Object approach:
Get-Process | Where-Object {$_.Name -eq "Firefox"}
To do "stuff" with it, just pipe the objects into a script block.
Where-Object:
PS C:\> Get-Process | Where-Object {$_.Name -eq "Firefox"} | fl $_.ID
Returns:
Id : 7516
Handles : 628
CPU : 1154.1421983
Name : firefox
get-process $Proc | FT ID, Name
Would return:
Id Name
-- ----
7516 firefox
12244 iexplore
12640 iexplore
Or, you could finally use the ForEach-Object as mentioned, and loop through them:
Get-Process $Proc | ForEach-Object {If($_.Path -contains "C:\Program Files*"){Write-host "Bad Directory"} else{ write-host "Safe"}}
If the running .exe above is running from C:\Program Files* then its writes out "Safe", otherwise it writes "Bad Directory".
Upvotes: 8
Reputation: 52689
Seems by popular agreement, the answer to your question is to provide a string array for the -Name
parameter of Get-Process
like so:
Get-Process -Name MyProgramA,MyProgramB
You can then loop through using the pipeline:
Get-Process -Name MyProgramA,MyProgramB | ForEach-Object {$_}
You can also use a variable:
Get-Process -Name $MyProgramStringArrray
Upvotes: 0