Reputation: 5167
How can I write a quick 1-liner for write-host'ing an object property (let's say Name
)? Here is the object I want to print the Name
of ...
Get-WmiObject -Class win32_ComputerSystem -namespace "root\CIMV2"
I tried ...
write-host $_.name | Get-WmiObject -Class win32_ComputerSystem -namespace "root\CIMV2"
But this seems to still print all object properties. What can I do to fix this command?
Upvotes: 2
Views: 147
Reputation: 3153
In addition to the answer from BACON, another option is this (needs PowerShell v3 or higher):
Write-Host (Get-WmiObject -Class win32_ComputerSystem -namespace "root\CIMV2").Name
Upvotes: 3
Reputation: 16606
You can use the -ExpandProperty
parameter of the Select-Object
cmdlet to retrieve just the computer name, then pipe that to Write-Host
(formatted as multiple lines for readability):
Get-WmiObject -Class win32_ComputerSystem -namespace "root\CIMV2" `
| Select-Object -ExpandProperty 'Name' `
| Write-Host;
Alternatively, use the ForEach-Object
cmdlet to get the Name
property:
Get-WmiObject -Class win32_ComputerSystem -namespace "root\CIMV2" `
| ForEach-Object { $_.Name; } `
| Write-Host;
This is not a one-liner, but another approach similar to what you tried:
$computer = Get-WmiObject -Class win32_ComputerSystem -namespace "root\CIMV2";
Write-Host $computer.Name;
Note that since you only care about the Name
property of Win32_ComputerSystem
, it's a good idea to communicate that to Get-WmiObject
using the -Property
parameter so it doesn't bother returning information that will be discarded anyways:
Get-WmiObject -Class win32_ComputerSystem -namespace "root\CIMV2" -Property 'Name'
Upvotes: 4