# 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