首页 > 解决方案 > 从 Powershell 中的 write-host 输出中删除某些字符(Get-ADuser)

问题描述

我正在比较两个域之间的用户,以确保在一个域中被禁用的用户在另一个域中被禁用,使用以下两个步骤:

域 1:

Get-ADUser -SearchBase "OU=ou2,OU=ou1,DC=pre,DC=domain1,DC=com" -Filter * -Properties * | Select-Object Name | Export-Csv -encoding "utf8" Users.csv

领域 2:

$input = import-csv -path "Users.csv" 
ForEach ($User in $input) {
$result = get-aduser -SearchBase "OU=ou2,OU=ou1,DC=pre,DC=domain2,DC=com" -Filter "name -eq '$($User.Name)'" | Select-Object Enabled
If ($result -eq $null) { Write-host -ForegroundColor Yellow $User "Name not found. Please do a manual check" 
}
elseif ($result -like '*False*') 
{ 
Write-host -ForegroundColor Red "**" $User "** must be disabled!" 
}
else {get-aduser -SearchBase "ou=Users,ou=SCS,ou=All,dc=osit,dc=ad" -Filter "name -eq '$($User.Name)'" -Properties * | Select-Object Name, Enabled}
}

这有效,但给了我以下输出:

Name                          Enabled
----                          -------
Firstname1 Lastname1             True
@{Name=Firstname2 Lastname2} - Name not found. Please do a manual check

如何删除“@{Name=”和“}”?我已经尝试将 -ExtendProperity 添加到 $result,并替换没有运气。我可能做错了..

标签: powershellcompare

解决方案


$User是一个自定义对象(类型[pscustomobject],作为输出Import-Csv),并且@{Name=Firstname2 Lastname2}是它的字符串化表示[1],因为Write-Host字符串化了它的参数以供显示。

.Name而是访问该属性以仅获取名称:

Write-host -ForegroundColor Yellow $User.Name "- Name not found. Please do a manual check" 

更惯用的是,使用单个可扩展字符串(内部字符串插值"..."):

Write-host -ForegroundColor Yellow  "$($User.Name) - Name not found. Please do a manual check" 

如果要包含完整的对象表示,就像直接将其打印到控制台时那样,则需要Out-String,但请注意,您最终会得到多行输出:

Write-host -ForegroundColor Yellow  "$($User | Out-String) - Name not found. Please do a manual check" 

[1] 您可以通过以下方式验证这一点:$user = [pscustomobject] @{ Name = 'Firstname1 LastName1' }; "$user". 输出是字符串@{Name=Firstname1 LastName1}


推荐阅读