powershell - 从 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,并替换没有运气。我可能做错了..
解决方案
$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}
。
推荐阅读
- azure-devops - VSTS 和 InstallShield 项目
- apache-flink - Flink 1.3 在 YARN 上运行单个作业如何设置每个 TaskManager 的 Task Slot 数量
- css - CSS:为什么 Safari 中有灰色的奇怪东西?
- android - 如何在通过 Jenkins 构建 apk 时动态设置 buildConfigField 参数
- btrieve - Btrieve 记录锁定问题
- c# - 如何有效地进行多次随机试验?
- rabbitmq - 自动化 RabbitMQ 消费者测试
- sql - BigQuery UPDATE 嵌套数组字段
- tfs - TFS 2017 API;使用变量排队构建
- java - @PreAuthorize 的方法安全性 - RequestHeader 在 403 之后不刷新