gpt4 book ai didi

powershell - 修复try/catch,并输出

转载 作者:行者123 更新时间:2023-12-03 00:59:12 25 4
gpt4 key购买 nike

我要将一个用户单位OU添加到组中,并希望捕获:

  • 用户添加了
  • 列表中已有用户
  • 将以上内容输出到文件

  • 下面的当前代码可以工作并输出:
    UserName              GroupName                          TimeStamp--------              ---------                          ---------%Username%            %groupname%                        14/10/2019 15:50:49

    But, the catch doesn't catch users already in the group and report on output on console. The export to CSV just contains all users in the OU and shows what time it added.

    I would like the catch output to trigger on screen, and have some way in the exported CSV file to show if a user was already added or was added on this run.

    The code that I'm using:

    $groupName = 'SOMEGROUP'
    $ou = 'OU=Users,DC=DC,DC=LOCAL'
    $cred = Get-Credential -Credential bsg\myusername$

    $results = Get-ADUser -Filter * -SearchBase $ou -Credential $cred | ForEach-Object {
    #Add the user to the group here
    $userName = $_.Name
    try {
    Add-ADGroupMember -Identity $groupName -Members $_.DistinguishedName -Credential $cred -ErrorAction Stop
    } catch {
    Write-Warning "User $userName is already a member of group $groupName"
    }

    # output a PsCustomObject that gets collected in the $results variable
    [PsCustomObject]@{
    'UserName' = $userName
    'GroupName' = $groupName
    'TimeStamp' = Get-Date
    }
    }

    # output on console
    $results | Format-Table -AutoSize

    # Export to CSV file
    $results | Export-Csv C:\PS\AddADGroupToUsers.csv -NoTypeInformation

    Read-Host -Prompt "Press Enter to exit"

    我不确定 Add-ADGroupMember。那里的DistingushedName而不是 $userName无关紧要吗?

    我希望输出显示无法正常工作的 catch

    我在两个语句上都使用了 -Credential $cred,是否有一种更简单的方法来使所有内容作为 session 的 -Credential运行,而不是为了整洁而使用命令?

    答复已阅读并理解。
    我运行了脚本。用户已经在组中,因此我希望他们全部回来,因为“用户已经是组…的成员。”但是相反,这似乎是错误的。

    最新更新后的错误消息(该组已经有很多成员了):
    Add-ADGroupMember : Cannot validate argument on parameter 'Members'. The argument is null, empty, or an element of the
    argument collection contains a null value. Supply a collection that does not contain any null values and then try the
    command again.
    At C:\PS\add to usersNEW2.ps1:28 char:57
    + ... oupMember -Identity $groupName -Members $_.DistinghuishedName -ErrorA ...
    + ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidData: (:) [Add-ADGroupMember], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.AddADGrou
    pMember

    输出CSV错误,因为没有添加用户,因为他们已经在其中。所以结果是错误的:
    UserName    GroupName   TimeStamp           Status
    TheUser GROUPSActual 16/10/2019 15:23 User added successfully

    因此,远离Theo的代码,我尝试了Ivan的建议,但这花了很长时间:
    # I'll use the DistinghuishedName because this is always unique in the forest
    $currentMembers = Get-ADGroupMember -Identity $groupName | Select-Object -ExpandProperty DistinghuishedName

    $results = Get-ADUser -Filter * -SearchBase $ou -credential $cred | ForEach-Object {

    # test if the user is already a member by checking the array

    If ((Get-ADGroupMember -Identity $groupname).distinguishedName -contains $_.distinguishedName) {
    Write-Warning "User $userName is already a member of group $groupName"
    }
    else {
    Add-ADGroupMember -Identity $groupName -Members $_.DistinguishedName -Credential $cred -ErrorAction Stop
    }
    # output a PsCustomObject that gets collected in the $results variable
    [PsCustomObject]@{
    'UserName' = $_.Name
    'GroupName' = $groupName
    'TimeStamp' = Get-Date
    'Status' = $status
    }
    }

    我认为它正在运行,但是花了几分钟才从7中得到3个结果,而原始代码却在几秒钟内就起作用了。
    编辑:代码已完成,并且已编写托管警告。我知道我可以调整状态部分以将错误添加到状态。只是不应该花那么长时间!

    时间戳相隔几秒钟,但现在:
    TimeStamp
    16/10/2019 16:12
    16/10/2019 16:14
    16/10/2019 16:15
    16/10/2019 16:16
    16/10/2019 16:17
    16/10/2019 16:18
    16/10/2019 16:19

    最佳答案

    仅当catch设置为ErrorAction时发生错误时,才会执行Stop块。当用户已经是组的成员时,Add-ADGroupMember不会返回错误。

    我建议在try块的脚本中使用某种逻辑。就像是:

    If ((Get-ADGroupMember -Identity $groupname).distinguishedName -contains $_.distinguishedName) {
    Write-Warning "User $userName is already a member of group $groupName"
    }
    else {
    Add-ADGroupMember -Identity $groupName -Members $_.DistinguishedName -Credential $cred -ErrorAction Stop
    }

    您仍然可以使用 catch块来处理可能发生的任何错误。

    关于powershell - 修复try/catch,并输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58379402/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com