Reputation: 11
I am trying to use the Get-Service
command or Get-Process
command
but I wanna try use a parameter with the "get" command.
I am getting and error with this:
$a = Service
$b = Running
Get-$a | where {$_.Status -eq $b}
this part is not working, either when I use this:
powershell -Command Get-$a
this one works, how can I complete with both of the parameters.
Upvotes: 1
Views: 157
Reputation: 174690
When you issue the command Service
, and powershell is unable to find a command by that name, it'll automatically try to resolve the command name with Get-
prepended - so $a
already contains the results from executing Get-Service
.
Now, if you want to execute a command based on its name stored in a variable, you can use the call operator (&
):
$a = "Service" # notice that we're defining a string
$b = "Running" # otherwise powershell would think it should execute a command right away
& "Get-$a" |Where-Object { $_.State -eq $b }
As Mike Shepard points out, you can also execute a command by getting the corresponding CommandInfo object from Get-Command
:
$cmd = Get-Command "Get-$a"
& $cmd |Where-Object { $_.State -eq $b }
Upvotes: 1