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

PowerShell: Get-NetTCPConnection for Windows 7 & 2008

On Windows 8 & 2012, there's this nifty function named Get-NetTCPConnection that is useful to…

CentOS System Setup

Notes from 2018...   # Upgrade system and clean disk yum upgrade yum clean all…

PowerShell: Legacy Methods to Save Credentials

PowerShell version 7 or later may already have facilities to store and retrieve credentials without…