You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell域管理员检测脚本任务计划执行异常求助

域管理员组变更告警脚本定时执行异常排查请求

问题描述

我编写了一款PowerShell脚本,用于检测AD(Active Directory)中域管理员组新增用户账户时发送告警邮件。该脚本在PowerShell窗口手动运行可正常工作(虽存在报错),但尝试通过域控制器的任务计划每5分钟自动执行(直至违规账户被移除)时出现异常:任务计划显示已运行但进程挂起无响应,同时抛出WinRM连接错误(HTTP 500),后续Import-PSSession、Remove-PSSession因Session为空报错。我已调整任务计划停止设置、更换执行账户(当前使用域管理员账户),但问题仍未解决。恳请协助解决该定时执行问题。

PowerShell脚本

#Enter the list of approved admin accounts. 

#Domain admin accounts
$domainAdminsList = "Administrator", "Admin2", "admin3"


  #Get the members of the "Domain Admins" group
    $actualAdmins = Get-ADGroupMember -Identity "Domain Admins" | Select-Object -ExpandProperty SamAccountName
    $adminsList = $domainAdminsList
    $accountType = "Domain"



#Compare the admin accounts vs the adminsList, and if an account exists then add it to $rogueAdmins
$actualAdmins | ForEach-Object {
    $adminName = $_
    $matchFound = $false
    foreach ($account in $adminsList) {
        if ($adminName -like $account) {
            $matchFound = $true
            break
        }
    }
    if (-not $matchFound) {
        $rogueAdmins += $adminName
    }
    else {
        $goodAdmins += $adminName
    }
}



if ($rogueAdmins.count -gt 0) {


# Import the required module for this script
#Import-Module MSOnline

# Your credentials
$User = "email account"
$Credential = Get-StoredCredential -Target "stored email"
$UserCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $Credential.Password

# Create a session
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection

# Import the session
Import-PSSession $Session -DisableNameChecking

# Email details
$EmailTo = "to@email.com"
$EmailFrom = "from@email.com"
$Subject = "ALERT: The Domain Admins group has been modified"
$Body = "A new user has been added or removed from the Domain Admin user's group. Please confirm this is a legitimate change and not malicious by checking the Domain Admin group for the user: $rogueAdmins. This message will repeat every 5 minutes until this has been resolved."
$SMTPServer = "smtp.office365.com"
$SMTPPort = "587"

# Send the email
Send-MailMessage -To $EmailTo -From $EmailFrom -Subject $Subject -Body $Body -SmtpServer $SMTPServer -port $SMTPPort -UseSsl -Credential $UserCredential

# Remove the session
Remove-PSSession $Session


    exit 1
}
else {
    Write-Output "Good news!  The $accountType Admins group only contains these approved users:"
    $goodAdmins
    exit
}

报错信息

New-PSSession : [outlook.office365.com] Connecting to remote server outlook.office365.com failed with the following error message : The WinRM client received an HTTP server error status (500), but the 
remote service did not include any other information about the cause of the failure. For more information, see the about_Remote_Troubleshooting Help topic.
At C:\1st_setup\Scripts\admin-check2.ps1:46 char:12
+ $Session = New-PSSession -ConfigurationName Microsoft.Exchange -Conne ...
+            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotingTransportException
    + FullyQualifiedErrorId : WinRMHttpError,PSSessionOpenFailed
Import-PSSession : Cannot validate argument on parameter 'Session'. The argument is null. Provide a valid value for the argument, and then try running the command again.
At C:\1st_setup\Scripts\admin-check2.ps1:49 char:18
+ Import-PSSession $Session -DisableNameChecking
+                  ~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Import-PSSession], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.ImportPSSessionCommand
 
Remove-PSSession : Cannot validate argument on parameter 'Id'. The argument is null. Provide a valid value for the argument, and then try running the command again.
At C:\1st_setup\Scripts\admin-check2.ps1:63 char:18
+ Remove-PSSession $Session
+                  ~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Remove-PSSession], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.RemovePSSessionComman

任务计划设置截图

  • 常规设置:
    任务计划常规设置
  • 触发器设置:
    任务计划触发器设置
  • 操作设置:
    任务计划操作设置
  • 其他设置详情:
    任务计划其他设置详情

内容的提问来源于stack exchange,提问作者crizpyy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 00:12:31