Search code examples
windowspowershellsmtpscheduled-tasks

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_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

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.

12 34

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!


Solution

  • You need to call PowerShell as the Program/Script and place the script filespec in the Add arguments (optional): box.

    Here's the full text of the options in the picture below: -WindowStyle Hidden -Command "G:\BEKDocs\Scripts\production\CMsLocalPCInfo.ps1"

    enter image description here