我要从一长串要填充到CSV中的用户中提取数据的子集。我可以执行以下操作以打印出要筛选的列表,然后如何将每个迭代作为一行写在CSV中?
foreach ($User in $UserList)
{
Write-Host $User.Enabled #Enabled
if ($User.Country -eq "CA" -OR $User.DistinguishedName -like "CANADA")
{
Write-Host "Canada"
}
elseif ($User.Country -eq "LUX" -OR $User.DistinguishedName -like "LUXEMBOURG")
{
Write-Host "Luxembourg"
}
elseif ($User.Country -eq "BRL" -OR $User.DistinguishedName -like "BRAZIL")
{
Write-Host "Brazil"
}
elseif ($User.Country -eq "USA" -OR $User.DistinguishedName -like "US")
{
Write-Host "America"
}
elseif ($User.Country -eq "UNITED KINGDOM" -OR $User.DistinguishedName -like "GB")
{
Write-Host "United Kingdom"
}
elseif ($User.Country -eq "HONG KONG" -OR $User.DistinguishedName -like "HK")
{
Write-Host "Hong Kong"
}
elseif ($User.Country -eq "INDIA" -OR $User.DistinguishedName -like "IN")
{
Write-Host "India"
}
elseif ($User.Country -eq "AUSTRALIA" -OR $User.DistinguishedName -like "AU")
{
Write-Host "Australia"
}
Write-Host $User.SamAccountName #Login ID
Write-Host $User.GivenName #First Name
Write-Host $User.Surname #Last Name
Write-Host $User.Title #Title
Write-Host $User.mail #E-Mail
Write-Host $User.LastLogonDate #Last Login Date
if ($User.accountExpires -eq 1)
{
Write-Host $User.AccountExpirationDate
}
else
{
Write-Host "N/A"
} #Expiration Date
# Write-Host $User. #Password Expiration
Write-Host $User.Department #Department
Write-Host $User.Office #Floor
Write-Host $User.OfficePhone #Office Number
Write-Host $User.MobilePhone #Mobile Number
Write-Host $User.whenCreated #Created Date
Write-Host $User.whenChanged #Changed Date
}
答案 0 :(得分:2)
我建议使用switch
,Export-Csv
和计算的属性与Select-Object
:
$UserList | Select-Object -Property @(
'SamAccountName', 'Enabled', 'GivenName', 'Surname'
'Title'
'Mail'
'LastLogonDate'
'Department', 'Office'
'OfficePhone', 'MobilePhone'
'WhenCreated', 'WhenChanged'
@{
Label = 'AccountExpires'
Expression = {
if ($PSItem.accountExpires -eq 1) {
$PSItem.AccountExpirationDate
} else {
'N/A'
}
}
}
@{
Label = 'Country'
Expression = {
switch ($PSItem) {
{$PSItem.Country -eq 'CA' -or $PSItem.DistinguishedName -eq 'CANADA'} {
'Canada'
}
{$PSItem.Country -eq 'LUX' -or $PSItem.DistinguishedName -eq 'LUXEMBOURG'} {
'Luxembourg'
}
{$PSItem.Country -eq 'BRL' -or $PSItem.DistinguishedName -eq 'BRAZIL'} {
'Brazil'
}
{$PSItem.Country -eq 'USA' -or $PSItem.DistinguishedName -eq 'US'} {
'America'
}
{$PSItem.Country -eq 'UNITED KINGDOM' -or $PSItem.DistinguishedName -eq 'GB'} {
'United Kingdom'
}
{$PSItem.Country -eq 'HONG KONG' -or $PSItem.DistinguishedName -eq 'HK'} {
'Hong Kong'
}
{$PSItem.Country -eq 'INDIA' -or $PSItem.DistinguishedName -eq 'IN'} {
'India'
}
{$PSItem.Country -eq 'AUSTRALIA' -or $PSItem.DistinguishedName -eq 'AU'} {
'Australia'
}
}
}
}
) | Export-Csv -Path C:\Temp\UserList.csv -NoTypeInformation -Force -Encoding UTF8