
close
close
Chance to win $250 in Petri 2023 Audience Survey
Without a doubt, one of the features in PowerShell that makes it so compelling is the pipeline. You run a cmdlet or script, and PowerShell spits out objects that are formatted on the screen for your viewing pleasure. With that said, sometimes the output is less than friendly. One quirk that always frustrates me is the Get-Service command. The command will display service information for remote computers, but the associated property name is MachineName rather than the traditional Computername parameter. In this article, I’ll show you a workaround for working with PowerShell’s Get-Service cmdlet.
Get-Service bits -computername chi-core01,chi-fp02,chi-hvr2,chi-dc04 | Select Status,Name,Machinename
Displaying the MachineName property (Image Credit: Jeff Hicks)
Get-Service bits -computername chi-core01,chi-fp02,chi-hvr2,chi-dc04 | Select Status,Name,@{Name="Computername";Expression={$_.Machinename}}
Using Select-Object to rename a property (Image Credit: Jeff Hicks)
Getting type information for service objects (Image Credit: Jeff Hicks)
Update-TypeData -TypeName System.ServiceProcess.ServiceController -MemberType AliasProperty -MemberName Computername -Value Machinename –Force
I typically also use the –Force parameter to overwrite any existing values. In this situation, I’m not changing anything that Microsoft defines, so I should be good. Let’s look at Get-Member again.
The revised object properties (Image Credit: Jeff Hicks)
Get-Service bits -computername chi-core01,chi-fp02,chi-hvr2,chi-dc04 | Format-Table Status,Name,Computername -AutoSize
Using the alias property (Image Credit: Jeff Hicks)
The ComputerName parameter for Get-CimInstance (Image Credit: Jeff Hicks)
The AD Computer object (Image Credit: Jeff Hicks)
Update-TypeData -TypeName Microsoft.ActiveDirectory.Management.ADComputer -MemberType AliasProperty -MemberName Computername -Value Name -Force
Now I can get a bunch of computers.
$c = Get-ADComputer -Filter * -SearchBase "OU=Servers,DC=Globomantics,DC=Local"
And they now have a Computername property.
Using the new Computername property (Image Credit: Jeff Hicks)
$c | Get-CimInstance Win32_logicaldisk -filter "DeviceID='c:'" -ErrorAction SilentlyContinue
But because of some weird quirk of the AD Computer object with Get-Cimstance, this will fail. So in this particular case, I need to tweak the command a bit:
$c | Select * | Get-CimInstance Win32_logicaldisk -filter "DeviceID='c:'" -ErrorAction SilentlyContinue
Although since I’m select properties, I could just select Computername only.
$c | Select computername | Get-CimInstance Win32_logicaldisk -filter "DeviceID='c:'" -ErrorAction SilentlyContinue
Either way, I get results.
Pipelined results (Image Credit: Jeff Hicks)
$c | Get-Service bits -ErrorAction SilentlyContinue | Select Computername,Name,Status
Getting remote services in the pipeline (Image Credit: Jeff Hicks)
More in PowerShell
Most popular on petri