OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Powershell script with task scheduler not working

  • Thread starter Thread starter crizpyy
  • Start date Start date
C

crizpyy

Guest
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

Code:
#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

Code:
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!
<p>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.</p>
<p><strong>PowerShell Script</strong></p>
<pre><code>
#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
}

</code></pre>
<p><strong>Error that it throws</strong></p>
<pre><code>
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

</code></pre>
<p>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.</p>
<p><a href="https://i.sstatic.net/oTG6WbkA.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/oTG6WbkA.jpg" alt="1" /></a><a href="https://i.sstatic.net/XIHFrdOc.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/XIHFrdOc.jpg" alt="2" /></a>
<a href="https://i.sstatic.net/82YQ7yYT.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/82YQ7yYT.jpg" alt="3" /></a><a href="https://i.sstatic.net/G4Ma9NQE.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/G4Ma9NQE.jpg" alt="4" /></a></p>
<p>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!</p>
Continue reading...
 

Latest posts

B
Replies
0
Views
1
Blundering Ecologist
B
Top