变量中的 POWERSHELL GET-ADUSER 显示错误?

POWERSHELL GET-ADUSER in variables displays an error?

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 

我得到的结果是: John smith,8/26/2020 12:00:00 上午,销售,纽约,@{ =Raymond gray} 我的疑问是为什么我得到 @ {= managername} 我只想要显示名称而不是其他字符

您不应尝试创建这样的逗号分隔结果,而应使用 Export-Csv 创建一个可用文件供您在 Excel.
中打开 为了做到这一点,让你的循环输出 objects 具有所需的属性而不是字符串,并将这些对象捕获在变量中。

此外,由于您只需要少量用户属性,因此使用 -Properties * 是一种浪费,尤其是如果您在同一个帐户上循环执行三次,每次都只是为了获得一个 属性..

尝试

 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

我将开关 -UseCulture 添加到 Export-Csv cmdlet,因此文件将使用您的 Excel 期望的分隔符