在任务计划程序中执行的 Powershell 问题

Powershell issue with executing in Task Scheduler

我有以下脚本,可以在用户开始工作时将用户添加到 o365 组,如下所示:

$DateMaxTime = (Get-date).AddDays(0)
$DateMaxTimeNew = (Get-date).AddDays(-30)

$usersRO = Get-ADUser -Filter * -Properties * -SearchBase "OU=Users,OU=Resources,OU=Romania,OU=DataManagement,DC=USA"|where {$_.Description -like "*TEMP*" -or $_.Description -like "*PERM*" } |select samaccountname,description,name
$groupsRO = '#O365-EXTERNALACCESS'


$FinalResultRO = New-object System.Collections.ArrayList

ForEach($groupRO in $groupsRO){
$membersRO = Get-ADGroupMember -Identity $groupRO -Recursive | Select -ExpandProperty samaccountname
Foreach ($userRO in $usersRO){
$AcountNameRO = $userRO.samaccountname
$DatePartRONew = get-aduser -identity $AcountNameRO -Properties * | Select-Object whenCreated
$DatePartSubsRONew = $DatePartRONew.whenCreated
$DataPartROdesc=$userRO.description
$expressionRO = ([regex]'(\d{2}/\d{2}/\d{4})').Match($DataPartROdesc).Groups[0].Value
$DatePartRO= $expressionRO
$FinalDateRO = [datetime]::ParseExact($DatePartRO,'dd/MM/yyyy',$null)
    If ($DatePartSubsRONew -lt $DateMaxTimeNew){
    Write-Host "$AcountNameRO ouf of date scope"}
    else {Write-Host "$AcountNameRO in scope"
        If ((get-date $FinalDateRO.Date) -eq (get-date $DateMaxTime.Date)){
            Write-Host "$AcountNameRO is a today Starter"
            If ($membersRO -notcontains $AcountNameRO ) {
            Write-Host "Adding external group $groupRO for: $AcountNameRO"
            Add-ADGroupMember -Identity "#O365-EXTERNALACCESS" -Members $AcountNameRO 
            $FinalResultRO.Add((New-Object psobject -Property @{User=$AcountNameRO}))
             } 
            Else {Write-Host "$AcountNameRO  exists in  group $groupRO"}
        }Else {Write-Host "$AcountNameRO is not a Starter"}
        }
    }
}

$listRO = [array]$FinalResultRO |Select User |Out-String
$listRO.gettype()

if [string]::IsNullOrEmpty($listRO){
Write-Host "nothing to send"
}
Else {
Write-Host "Mail sent"
Send-MailMessage -From "mail1@donut.com" -To "mail2@donut.com" -Subject "Following users have been granted external access rights" -smtpServer "donut" -body "$($listRO)"
}

我 运行 这个脚本每天在任务调度程序中以最高权限运行。

由于某些原因,有时在执行脚本时,告诉我用户已添加到组中,但在 Active DIrectory 中没有更改。只有当我 运行 脚本第二次工作时(手动在 powershell 上,不使用任务调度程序)。

这可能是什么原因?

我会检查这一行

 Add-ADGroupMember -Identity "#O365-EXTERNALACCESS" -Members $AcountNameRO 

即使出于某种原因遇到错误,您的代码也会运行。我会添加一个 try catch 语句来找出问题所在(可能是 DNS、网络、$AcountNameRO 变量的一些问题...)。

try {Add-ADGroupMember -Identity "#O365-EXTERNALACCESS" -Members $AcountNameRO}
catch{

write-host "something went wrong in Add-ADGroupMember"
Send-MailMessage -From "mail1@donut.com" -To "mail2@donut.com" - 
Subject "please check Add-ADGroupMember"
write-host $_
}

当然,当 运行 计划任务时写主机不是一个好主意,因为您看不到输出。所以我会将输出转储到文件或事件日志中或写一封电子邮件。 Bill 写了一个很好的总结,说明了您可以对日志记录做什么。 https://adamtheautomator.com/powershell-logging/