gpt4 book ai didi

powershell - 错误处理并最小化脚本输出给最终用户

转载 作者:行者123 更新时间:2023-12-03 07:55:20 35 4
gpt4 key购买 nike

我有一个遍历用户列表(samaccountname)的脚本:

# Read usersfile to variable
$users = get-content ("users.txt")

# Get current time
$now = $(get-date -uformat "%H:%M %d/%m/%Y")

# Loop through list of users
foreach($user in $users) {

# Disable user
Disable-QADUser $user

# Set informative description
Set-QADuser $user -Description "Disabled $now"

# Delete all groupmemberships except "domain users"
Get-QADGroup -Containsmember $user | where-object { $_.name -ne 'domain users'} | Remove-QADGroupmember

# Move to "disabled users" group
move-QADObject $user -NewParentContainer 'contosoc.com/Disabled users'

# Hide from addresslist
Set-Mailbox -identity $user -HiddenFromAddressListsEnabled $true

# Moving mailbox to disabled users database
Move-Mailbox -Identity $user -TargetDatabase "myserver\mydb" -BadItemLimit 50 -Confirm:$False
}

我想要:
  • 禁止来自其他cmdlet的输出,仅显示“$ user is OK!”。如果一切正常,然后将成功日志记录到logfile.txt
  • 显示“错误!”以及失败的命令。并将完整的错误消息输出到单独的日志文件。

  • 我一直在考虑做一个 if(!cmdlettorun) { write-host "Error!" },但我想必须有一个更好的方法。

    我应该如何以适当的方式进行错误处理,以便最小化显示的输出,但是如果需要的话,仍然让我看到它?

    最佳答案

    为了抑制cmlet输出,您可以通过管道传递到out-null或在命令之前添加以下命令:

    [void](.. your cmdlets..)

    实现目标的一个好方法是使用托盘捕获最终代码,例如下面的最小化代码:
    $a = $ErrorActionPreference 
    $ErrorActionPreference = "SilentlyContinue"

    foreach($user in $users) {

    try
    {
    ... yours code ...
    $JobStatus = "OK"
    }
    catch [exception]
    {
    $("Error catched: " + $_.Exception.GetType().FullName) | out-file c:\file.log
    $("Error catched: " + $_.Exception.Message) | out-file c:\file.log -append

    $JobStatus = "not OK"
    continue;
    }
    finally
    {
    write-host "$user is $JobStatus!"
    }
    $ErrorActionPreference = $a
    }

    有关使用 try-catch-finally的一些提示,请阅读 here

    关于powershell - 错误处理并最小化脚本输出给最终用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9884890/

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