正如Lee_Dailey 评论的那样,当你只想要一些属性时,要求所有属性是一种浪费。
此外,您应该始终测试是否可以找到在 Read-Host 中输入的用户,因为任何人都可以在那里输入任何内容。
尝试
$Username = Read-Host "Enter User ID"
# try and find the user in AD
$user = Get-ADUser -Filter "SamAccountName -eq '$Username'" -ErrorAction SilentlyContinue
if ($user) {
# Get-ADGroup already returns these properties by default:
# DistinguishedName, GroupCategory, GroupScope, Name, ObjectClass, ObjectGUID, SamAccountName, SID
# so only ask for the extra properties you need
$user | Get-ADPrincipalGroupMembership | Get-ADGroup -Properties Description, ManagedBy | ForEach-Object {
# try and get the group manager from the DistinguishedName in the ManagedBy property
$manager = if ($_.managedBy) { (Get-ADUser -Identity $_.managedBy).Name } else { 'Not set' }
[PsCustomObject]@{
Name = $_.Name
Description = $_.Description
ManagedBy = $manager
}
} | Export-Csv -Path (Join-Path -Path 'C:\Temp' -ChildPath ('{0:yyyy-MM-dd}-{1}.csv' -f (Get-Date), $user.Name )) -NoTypeInformation
}
else {
Write-Warning "User '$Username' not found.."
}