Import-Module ActiveDirectory
$OutputEncoding = [Console]::OutputEncoding
#************************* Initiate Variable Empty ********************************
$var1="User,expiration date,departament,city,Manager `r`n"
#*********** Variable $Accounts will query SearchAccount with the Filters below *****************
$accounts = Search-ADAccount -SearchBase "OU=OUUsersguest,OU=OUMex23,DC=ferreronet,DC=com" -AccountExpiring -TimeSpan (New-TimeSpan -Days 15)
#*****Function Query will Initiate "Foreach" in every results and Filter as the Attributes below.****
$Tables = ForEach($account in $accounts) {
$mgr = (Get-ADUser $account -Properties * ) | Select-Object @{n =" ";e={get-aduser $_.manager | select -ExpandProperty name }}
$department = (Get-Aduser $account -Properties *).department
$city = (Get-Aduser $account -Properties *).city
$var1 = "{0}{1},{2},{3},{4},{5}`r`n" -f $var1, $account.name, $account.AccountExpirationDate,$department,$city,$mgr
}
Write-Output $var1
I am getting this as result: John smith,8/26/2020 12:00:00 AM,SALES,NEW YORK,@{ =Raymond gray} My doubts is why i am getting the @ {= managername} I just want the display name not the other characters
You shouldn't try to create a comma delimites result like this, but instead use Export-Csv
to create a usable file for you to open in Excel.
In order to do that, have your loop output objects with the desired properties instead of a string and capture these objects in a variable.
Also, since you only want a handfull of user attributes, it is wasteful to use -Properties *
, especially if you do that three times in the loop on the same account, every time just to get one property..
Try
Import-Module ActiveDirectory
$searchBase = "OU=OUUsersguest,OU=OUMex23,DC=ferreronet,DC=com"
$accounts = Search-ADAccount -UsersOnly -SearchBase $searchBase -AccountExpiring -TimeSpan (New-TimeSpan -Days 15)
$result = foreach($account in $accounts) {
# get the properties you need from the user account
$usr = $account | Get-ADUser -Properties Manager, Department, City, AccountExpirationDate
$mgr = if ($usr.Manager) { (Get-ADUser -Identity $usr.Manager).Name } else { $null }
# output an object with desired properties
[PsCustomObject]@{
User = $usr.Name
ExpirationDate = $usr.AccountExpirationDate
Department = $usr.Department
City = $usr.City
Manager = $mgr
}
}
# output on screen
$result | Format-Table -AutoSize
# output to CSV file
$result | Export-Csv -Path 'D:\Test\ExpiringUsers.csv' -UseCulture -Encoding UTF8 -NoTypeInformation
I added switch -UseCulture
to the Export-Csv
cmdlet so the file will use the delimiter character your Excel expects