No PowerShell Cmdlet to Start or Stop Something? Don’t Forget to Check for Methods on the Get Cmdlets
Many PowerShell commands return output in the form of objects (some return nothing at all). An example of this is shown in the following example where properties and their corresponding values are returned.
CommandType is a property and Cmdlet is the value for that particular property for each of the results:
1Get-Command -Noun Service -Module Microsoft.PowerShell.Management
Keep in mind that what is shown in the default output may not be the actual property names (compare
the default output from Get-Process
to the properties listed from Get-Process | Get-Member
for
an example of this).
In addition to properties, commands may also have methods which are actions that can be performed.
The Get-Member
cmdlet is used to determine what properties (and their actual names) and methods a
command has. Any command that produces output can be piped to Get-Member
.
1Get-Service -Name w32time | Get-Member
Notice as shown in the previous set of results that Get-Service
has a start and stop method. I
like to point this out because just because someone is only running commands that start with Get-*
doesn't mean that they can't perform a RGE (resume generating event).
There are cmdlets for starting and stopping services and I recommend using them instead of the methods any time a specific command exist for performing that task, but if those two commands didn't exist the methods could be used:
The windows time service is currently running:
1Get-Service -Name w32time
Stop the service using Get-Service
with the stop method:
1(Get-Service -Name w32time).Stop()
2Get-Service -Name w32time
Start the service using Get-Service
with the start method:
1(Get-Service -Name w32time).Start()
2Get-Service -Name w32time
You might ask, how is this beneficial in the real world for the everyday average IT Pro?
Sometimes with a fictitious example like with Get-Service
, it's hard to imagine Start-Service
and Stop-Service
not existing, but that's the exact scenario with the Get-SqlAgentJob
cmdlet
that's part of the SQLServer PowerShell module that installs as part of
SQL Server Management Studio 2016.
Notice that there's no Start-SqlAgentJob
cmdlet:
1Get-Command -Module SQLServer -Name *job*
Get-SqlAgentJob
returns a SMO object which has a start (and stop) method (thanks to
Rob Sewell for pointing this out):
1Get-SqlAgentJob -ServerInstance SQL011 -Name test | Get-Member -MemberType Method
That means it can be used to start a SQL agent job even though a specific cmdlet for performing that task doesn't exist:
1(Get-SqlAgentJob -ServerInstance SQL011 -Name test).Start()
2Get-SqlAgentJob -ServerInstance SQL011 -Name test
If I were asked in an interview what's the most important PowerShell command and I could only pick
one, it would be Get-Member
.
µ