我编写了一个非常简单的Powershell脚本,用于批量重命名AD组,下面是代码
# This script will perform a bulk rename of AD groups.
# Takes input from a csv file called "ADGroups.csv" with two columns,
# first column labelled "ObjectGUID" and contains the GUID of the AD Group you wish to rename and
# the second column is labeled "NewName" and contains the name that you want the group to be renamed to.
# Outputs results to console and a file called ADGroupBulkRenameLog.txt
$Groups = Import-Csv ADgroups.csv
Foreach ($Group in $Groups)
{
$OldName = Get-ADGroup -Identity $Group.ObjectGUID | Select Name
Rename-ADObject -Identity $Group.ObjectGUID -NewName $Group.NewName
Set-ADGroup -Identity $Group.ObjectGUID -SamAccountName $Group.NewName
Write-Output ($OldName.Name + " has been renamed to " + $Group.NewName) | Tee-Object ADGroupBulkRenameLog.txt -Append
}
重命名部分工作正常,但我遇到问题的部分是输出。输出字符串将写入文件和控制台,但是如果发生错误(例如,新名称已存在),则错误不会写入文件,写入输出命令仍会运行。
我想知道是否有人知道更好的方法吗?最终目标是输出到控制台和文件,说明是否成功重命名了一个组,如果它确实出错则继续。
提前致谢!
答案 0 :(得分:0)
你可以这样重写你的foreach循环:
foreach ($Group in $Groups)
{
try
{
$OldName = Get-ADGroup -Identity $Group.ObjectGUID | Select Name
Rename-ADObject -Identity $Group.ObjectGUID -NewName $Group.NewName
Set-ADGroup -Identity $Group.ObjectGUID -SamAccountName $Group.NewName
Write-Output ($OldName.Name + " has been renamed to " + $Group.NewName) | Tee-Object ADGroupBulkRenameLog.txt -Append
}
catch
{
Write-Output "Error: $_" | Tee-Object ADGroupBulkRenameLog.txt -Append
}
}