Powershell script with task scheduler not working

I created a PowerShell script to email if it’s detected a new user account is added to the domain admin group within our AD. It works when I run through the PowerShell window but does throw an error. I am trying to automate and run it every 5 minutes until the user is removed from the domain admins group through task scheduler on our domain controller. Below is my code and beneath it is the error that it throws as well but as mentioned before it does run successfully when ran through a PowerShell window.

PowerShell Script


#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 = "[email protected]"
$EmailFrom = "[email protected]"
$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
}

Error that it throws


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_setupScriptsadmin-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_setupScriptsadmin-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_setupScriptsadmin-check2.ps1:63 char:18
+ Remove-PSSession $Session
+                  ~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Remove-PSSession], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.RemovePSSessionComman

The task scheduler history shows that it runs but then it just keeps hanging and nothing happens. It’s like it’s stuck. Below I have included images of the task scheduler settings.

I have already tried adjusting the task scheduler settings to force stop if it keeps running but it still keeps going. I have also used different accounts and the same issue occurs. Currently it is using my domain admin account for the task scheduler permissions. If anyone has any idea how to get this to run ever 5 minutes I’d appreciate it. Thanks!

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật