Posted On December 10, 2020

PowerShell: Remove a Scheduled Task By Name

kimconnect 0 comments
blog.KimConnect.com >> Codes >> PowerShell: Remove a Scheduled Task By Name
# removeScheduledTask.ps1

# Set CoomputerNames
$computerNames='sherver0001','sherver1000'
$scheduledTaskName='SomeTaskName'

# Obtain credentials
$username='Domain\Admin'
$password='PASSWORD'
$encryptedPassword=ConvertTo-SecureString $password -AsPlainText -Force
$adminCredential=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $userName,$encryptedPassword;

function removeScheduledTask{
    param(
        [string[]]$computerNames,
        [string]$taskName,
        [pscredential]$adminCredential
    )
    # Unregister the Scheduled task if it exists
    foreach ($computername in $computernames){
        if($session.state -eq 'Opened'){remove-pssession $session}
        $session=if($adminCredential){
                try{
                    New-PSSession -ComputerName $computername -Credential $adminCredential -ea stop
                }catch{
                    New-PSSession -ComputerName $computername -Credential $adminCredential -SessionOption $(new-pssessionoption -IncludePortInSPN)
                }
            }else{
                try{
                    New-PSSession -ComputerName $computername -ea stop
                }catch{
                    New-PSSession -ComputerName $computername -SessionOption $(new-pssessionoption -IncludePortInSPN)
                }
            }
        if($session){
            write-host "Connected to $computername."
            invoke-command -Session $session -scriptblock{
                param ($taskName)
                write-host "Removing scheduled task $taskname on $env:computername..."
                #$taskFound=Get-ScheduledTask $taskName -ea SilentlyContinue
                try{
                    Unregister-ScheduledTask -TaskName $taskName -Confirm:$false;
                }catch{
                    write-warning $_
                }
            } -args $taskName
        Remove-PSSession $session
        }else{
            write-warning "Cannot connect to $computername. $taskName NOT removed."
        }
    }
}

removeScheduledTask $computerNames $scheduledTaskName $adminCredential

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post

Indications that Chocolatey is locked down

# System's version is less than vendor's current (Chocolatey v0.10.15) 0+000+00[LAX-WEB005]: PS C:\Users\testadmin\Documents> choco source…

PowerShell: Perform Final Sync Between 2 Directories

Current Version # Final-Sync.ps1# This function performs CRC checks on each file at the source.#…

PowerShell: Download and Apply Windows Patch KB

The following snippet assumes that a Windows machine has access to download Microsoft patches directly…