PowerShell: How to retrieve a specific property _exclusively_
How can I retrieve a specific property exclusively?
I am aware of the select-object
cmdlet which seems to be dowdy in that respect:
PS C:\> Get-ADOrganizationalUnit -SearchBase 'OU=Houston,DC=contoso,DC=net' -Filter 'Name -like "SomeOU"' -Properties * | Select-Object Description,Streetaddress,State,postalcode | format-list
An optimized version would be:
PS C:\> Get-ADOrganizationalUnit -SearchBase 'OU=Houston,DC=contoso,DC=net' -Filter 'Name -like "SomeOU"' -Properties Description,Streetaddress,State,postalcode
Why is the -property
switch not solely returning the entered propteries?
Solution 1:
This is because the -properties
switch is not a formatting tool, it is intended as a way to receive more information than the default values already included.
From the Get-ADOrganizationalUnit article.
Specifies the properties of the output object to retrieve from the server. Use this parameter to retrieve properties that are not included in the default set.
If you want to format your output, you're better of sticking with the select-object
statement.
Solution 2:
You would need to use both, to specify which properties to retrieve from the DC, and which ones to select and ultimately display. -Properties *
is a potential performance basher since the DSA will need to return every attribute that has a value, including certificates and other binary values you might not have need for
In a script utilizing the AD cmdlets I would use the splatting operator (@
) and do the following:
$ADSplat = @{
"SearchBase" = 'OU=Houston,DC=contoso,DC=net'
"Filter" = 'Name -eq "SomeOU"'
"Properties" = "Description","Streetaddress","State","postalcode"
}
$ADOU = Get-ADOrganizationalUnit @ADSplat | Select-Object $ADSplat["Properties"]
If you do this consistently, your scripts become über-easy to update/edit, since every query is defined in the same readable hastable format
If I'm at the shell and mid-oneliner come to think about the properties I need, I'd do something like (using Get-ADUser
as an example):
Get-ADUser username -Properties ($p = "manager","memberOf","cn") |select $p