首页 > 解决方案 > Powershell - 仅获取具有值的属性

问题描述

我想获取所有属性,例如只有具有值的属性(例如 ADUC)。只是我能够获得属性名称。另外,我想将所有属性与下面的值一起获取。

脚本 :

$ADUser = Get-ADUser -Identity 'user' -Properties *
$CusUser = New-Object -TypeName PSObject
$ADUser.PropertyNames | ?{$ADUser.$_ -ne $null} | %{ $CusUser | Add-Member -MemberType NoteProperty -Name $_ -Value $ADUser.$_ }

输出:

AccountExpirationDate
accountExpires
AccountLockoutTime
AccountNotDelegated
AllowReversiblePasswordEncryption
AuthenticationPolicy
AuthenticationPolicySilo
BadLogonCount
CannotChangePassword
CanonicalName
Certificates
City
CN
..
..
blah 
blah

我想要的输出:

AccountExpirationDate blank
accountExpires ; never
AccountLockoutTime ; blank
AccountNotDelegated ; blank
AllowReversiblePasswordEncryption ; blank
AuthenticationPolicy ; blank
AuthenticationPolicySilo ; blank
BadLogonCount ; blank
CannotChangePassword ; blank
Certificates ; blank
City ; blank
CN ; john T
..
..
blah 
blah

标签: powershell

解决方案


您可以执行以下操作以输出仅显示具有值的属性的 ADUser 对象:

$ADUser = Get-ADUser -Identity 'user' -Properties *
# $props contains property names (an array) with non-empty values
$props = $ADUser.PSObject.Properties | 
    Where {[string]$_.BaseObject -eq $ADUser.DistinguishedName -and ![string]::IsNullOrEmpty($_.Value)} |
        Select-Object -Expand Name
# Outputs user object with only properties that contain non-empty values.
$ADUser | Select-Object $Props

如果要格式化属性/值对输出,可以执行以下操作:

$ADUser = Get-ADUser -Identity 'user' -Properties *
# List all properties in format property ; value. Empty values show as string blank.
$ADUser.PSObject.Properties | 
    Where {[string]$_.BaseObject -eq $ADUser.DistinguishedName} | Foreach-Object {
        if ([string]::IsNullOrEmpty($_.Value)) {
            $value = 'blank'
        } else {
            $value = $_.Value
        }
        "{0} ; {1}" -f $_.Name,$value
    }

推荐阅读