powershell - 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
解决方案
您可以执行以下操作以输出仅显示具有值的属性的 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
}
推荐阅读
- java - 类在使用扩展方法时返回扩展类的参数而不是它自己的参数
- javascript - 这两个闭包有什么区别?
- flutter - 如何在颤振流中正确调用 S3 文件?
- geometry - 如何在 Yelp 或 Uber 服务中使用 S2?
- javascript - 在 Bootstrap 5 中实现暗/亮/...模式的最合适方法是什么?
- python - GridSearchCV 没有为 xgboost 选择最佳超参数
- swift - 用新数据重新加载 PageViewController
- uwp - ObservableCollection 在 UWP 和 WASM 上的行为不同
- nginx - 在 nignx 中动态重写路径
- module - 如何使用 Xquery 为 MarkLogic 实现自动递增数字主键