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: Benchmark Disk Speed

Contrary to previous iteration, this version returns an object with multiple properties describing statistical analysis…

Basic CSS: Change the Font Size of an Element

<style>.red-text {color: red;}</style><h2 class="red-text">CatPhotoApp</h2><main><p class="red-text">Click here to view more <a href="#">cat photos</a>.</p><a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="A…

Optimizing Windows IIS Server

Most IIS instances are fine with default settings. However, it's often beneficial to configure some…