2014-09-04 123 views
0

我已经写了批量重命名AD组一个非常简单的PowerShell脚本,下面是代码PowerShell的:Outputing Sucess和错误

# 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

你或许可以改写你的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 
    } 
} 
+0

哇。很简单!这正是我所需要的。我修改了错误写入输出命令以添加旧的AD组名称。非常感谢您的帮助! 我可以检查我对try/catch命令的理解是否正确?如果在try块中遇到错误,它会立即跳出并执行catch块中的内容? – PhilB 2014-09-04 09:42:20