【问题标题】:Powershell: Outputing Sucess and ErrorsPowershell:输出成功和错误
【发布时间】:2014-09-04 09:01:55
【问题描述】:

我写了一个非常简单的 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
}

重命名部分工作正常,但我遇到问题的部分是输出。输出字符串同时写入文件和控制台,但是如果发生错误(例如新名称已存在),则错误不会写入文件并且 write-output 命令仍然运行。

我想知道是否有人知道这样做的更好方法?最终目标是输出到控制台和文件,说明组是否成功重命名,如果出错则继续。

提前致谢!

【问题讨论】:

    标签: powershell logging output


    【解决方案1】:

    你可以这样重写你的 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
        }
    }
    

    【讨论】:

    • 哇。很简单!这正是我需要的。我修改了错误写入输出命令以添加旧的 AD 组名称。非常感谢您的帮助!我可以检查一下我对 try/catch 命令的理解是否正确吗?如果 try 块中遇到错误,它会立即跳出并执行 catch 块中的内容?
    猜你喜欢
    • 2015-09-13
    • 2022-11-29
    • 2020-12-20
    • 1970-01-01
    • 2020-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-02
    相关资源
    最近更新 更多