I am trying to create a simple scheduled task that Removes a spesific group from a spesific user. The task is created but it doesen't actully do anything based on the Action defined. If I run it with the same user manually in powershell it works fine. Any ideas to what I am missing here?
The problematic line here is the New-ScheduledTaskAction action I try to set.
Here is the code block im using.
$Action = New-ScheduledTaskAction -Execute "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -Argument "Import-Module ActiveDirectory; Remove-ADGroupMember -Identity $SecurityGroup -Members $User -Confirm:$false"
$Trigger = New-ScheduledTaskTrigger -Once -At "$ARDate 00:00:00 AM"
$Settings = New-ScheduledTaskSettingsSet
$Task = New-ScheduledTask -Action $Action -Trigger $Trigger -Settings $Settings
Register-ScheduledTask -TaskName "SAAR - Remove $User From $SecurityGroup" -InputObject $Task -User ($env:USERDOMAIN '\' $env:USERNAME)
CodePudding user response:
Your Powershell arguments look wrong. It should probably be something like this:
$Action = New-ScheduledTaskAction -Execute "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -Argument "-ExecutionPolicy Bypass -Command `"& { Import-Module ActiveDirectory; Remove-ADGroupMember -Identity `$SecurityGroup -Members `$User -Confirm:`$false }`""
$Trigger = New-ScheduledTaskTrigger -Once -At "$ARDate 00:00:00 AM"
$Settings = New-ScheduledTaskSettingsSet
$Task = New-ScheduledTask -Action $Action -Trigger $Trigger -Settings $Settings
Register-ScheduledTask -TaskName "SAAR - Remove $User From $SecurityGroup" -InputObject $Task -User ($env:USERDOMAIN '\' $env:USERNAME)
Note the backticks (`) to escape certain characters like quotes and dollars. Having said this, I'm not sure where your values such as $SecurityGroup will come from...?
CodePudding user response:
Thank you! With some guidance and more tweaking on your version I got it working by using this line:
$Action = New-ScheduledTaskAction -Execute "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -Argument "-ExecutionPolicy Bypass -Command `"& { Import-Module ActiveDirectory; Remove-ADGroupMember -Identity `"$SecurityGroup`" -Members `"$User`" -Confirm:`$false }`""