Adding Script automatically on Task Scheduler

Welcome Forums General PowerShell Q&A Adding Script automatically on Task Scheduler

This topic contains 1 reply, has 2 voices, and was last updated by

 
Participant
3 months ago.

  • Author
    Posts
  • #146475

    Participant
    Topics: 1
    Replies: 0
    Points: -3
    Rank: Member

    Hi

    I m new to scripting. I working on script to to add domain member to local Admin account and remove it automatically after a certain period of time. After referring posts online i could able to add or remove accounts from a machine. I don't have programming skill and i stuck up with the step 3

    Step are like

    1. Get Input

    $DomainName = "xxxxx" #Read-Host -Prompt "Domain name:"
    $ComputerName = Read-Host -Prompt "Computer name:"
    $UserName = Read-Host -Prompt "User name:"

    while(1){
    Try{
    $d = [datetime](read-host 'Enter any valid valid date/time')
    break
    }
    Catch{
    Write-Host 'Not a valid date' -fore red
    }
    }

    $AdminGroup = [ADSI]"WinNT://$ComputerName/Administrators,group"
    $User = [ADSI]"WinNT://$DomainName/$UserName,user"

    2. Add the user account to local admin group

    $AdminGroup.add($User.Path)

    3. Create a PS file on the local machine and update it with command to remove the account

    Connect-PSSession -ComputerName $ComputerName
    New-Item -ItemType "directory" -Path "\\$ComputerName\c$\temp"
    New-Item -ItemType "file" -Path "\\$ComputerName\c$\temp\test.ps1"
    Add-Content \\$ComputerName\c$\temp\test.ps1 "$AdminGroup.remove($User.Path)"

    4. Add the created Script file on the Task Scheduler to run it automatically

    $Trigger= New-ScheduledTaskTrigger -At $d.ToString('yyyy-MM-dd HH:mm:ss')
    $PSUser= "NT AUTHORITY\SYSTEM" # Specify the account to run the script
    $Action= New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "C:\Temp\test.ps1"
    Register-ScheduledTask -TaskName "Local Account removal" -Trigger $Trigger -User $PSUser -Action $Action -RunLevel Highest –Force

    Exit-PSSession

    The output at the step 3 was not as expect . the file it getting updated as

    " System.DirectoryServices.DirectoryEntry.remove(System.DirectoryServices.DirectoryEntry.Path) "

    Instead of Local admin group and the user account.

    Could anyone please suggest me a solution to automated it with proper output. Or a different way to derive it ?

    I m not sure how the step 4 will work

  • #146625

    Participant
    Topics: 2
    Replies: 968
    Points: 1,784
    Helping Hand
    Rank: Community Hero

    What do you mean by this?

    3. Create a PS file on the local machine and update it with command to remove the account

    Just create the script with the commands you need and copy it to the target to use it on and call it.

The topic ‘Adding Script automatically on Task Scheduler’ is closed to new replies.