PowerShell: Setup Windows Scheduled Tasks

# Scheduled-tasks-remote.ps1
# Purpose: to add a schedule task onto remote Windows system(s)
# Requires: PowerShell 3.0 or higher at the Jump box. Powershell 1.0 or higher at the targets.

# Scheduled task variables
$servers="SHERVER01","SHERVER02","SHERVER03"
$scriptFile="\\snapshots\FileServerClusters\File_Copy_Script_V0.17.ps1"
$description="Daily filecopying operations."
$taskName="Daily_Files_Copy"
[DateTime]$timeToStartTasks = '5:00pm'

# Credentials
$user=Read-Host -Prompt "Input $env:USERDOMAIN administrator's username"
$plainTextPassword=Read-Host -Prompt 'Input the password'
$password=ConvertTo-SecureString -String $plainTextPassword -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $user,$password

function isUnc($path){
$GLOBAL:uncServer=$scriptFile | select-string -pattern "(?<=\\\\)(.*?)(?=\\)" | Select -ExpandProperty Matches | Select -ExpandProperty Value
if ($uncServer){return $True}else{return $False}
}

function isDomainAdmin($account){
if (!(get-module activedirectory)){Install-WindowsFeature RSAT-AD-PowerShell -Confirm:$false}
if((Get-ADUser $user -Properties MemberOf).MemberOf -match 'Domain Admins'){return $True;}else{return $false;}
}

function isValidCred($u,$p){
# Get current domain using logged-on user's credentials
$domain = "LDAP://" + ([ADSI]"").distinguishedName
$domainCred = New-Object System.DirectoryServices.DirectoryEntry($domain,$u,$p)
if ($domainCred){return $True}else{return $False}
}

if ((isDomainAdmin $user)-AND (isValidCred $user $password)){
if (isUnc $scriptFile){
foreach ($computer in $servers){
"Processing $computer...";
Invoke-Command -ComputerName $computer -Credential $cred -ScriptBlock{
param($scriptFile,$taskName,$description,$user,$password,$uncServer,$timeToStart)
<# Debug
"Running with these variables:`n"
"`nUserID: $user"
"`nPassword: $password"
"`nScript: $scriptFile"
"`nTask name: $taskName"
"`nDescription: $description"
"`nUNC server: $uncServer"
#>
$username="$env:USERDOMAIN`\$user"

# Execute this sequence if the detected PowerShell version is 3.0 or greater
$powershellVersion=$PSVersionTable.PSVersion.Major
if($powershellVersion -ge 3){
"Powershell version $powershellVersion is detected. Now running commands basing on features available in this release...";
$settingsCommand = New-ScheduledTaskSettingsSet -MultipleInstances IgnoreNew -ExecutionTimeLimit 0
$callPowerShell = New-ScheduledTaskAction -Execute "Powershell.exe" -Argument "-ExecutionPolicy Bypass $scriptFile"
$dailyTrigger = New-ScheduledTaskTrigger -Daily -At $timeToStart

# Unrestrict this Domain Administrator from security prompts
Set-Executionpolicy -Scope CurrentUser -ExecutionPolicy UnRestricted -Force

# Unblock file & Ensure that script exists
<# Overcome error caused by double hop issue:
Cannot find path '\\snapshots\FileServerClusters\Daily-VSS-Snapshot.ps1' because it does not exist.
+ CategoryInfo : ObjectNotFound: (\\snapshots\Fil...SS-Snapshot.ps1:String) [Unblock-File], ItemNotFoundException
+ FullyQualifiedErrorId : FileNotFound,Microsoft.PowerShell.Commands.UnblockFileCommand
+ PSComputerName : SHERVER007

1. Run scheduled task as: New-ScheduledTaskAction -Execute "Powershell.exe" -Argument "-ExecutionPolicy Bypass $scriptFile"
2. Unblock-File -Path $scriptFile
#>
if ((Invoke-Command -computername $uncServer -Credential $Using:cred -ScriptBlock{Unblock-File -Path $Args[0];Test-Path $Args[0] -ErrorAction SilentlyContinue}-Args $scriptFile) -eq $False) {"Errors locating $scriptFile... Skipping";break;}

# Unregister the Scheduled task if it already exists
Get-ScheduledTask $taskName -ErrorAction SilentlyContinue | Unregister-ScheduledTask -Confirm:$false;

# Create new scheduled task
Register-ScheduledTask -Action $callPowerShell -Trigger $dailyTrigger -TaskName $taskName -Description $description -User $username -Password $password -Settings $settingsCommand -RunLevel Highest;
}else{
"Powershell version $powershellVersion is detected. Setting scheduled task as $username with that release...";
$TaskDescription = $description
$TaskCommand = "powershell.exe"
$TaskScript = $scriptFile
$TaskArg = "-WindowStyle Hidden -NonInteractive -Executionpolicy unrestricted -file $TaskScript"
#$TaskStartTime = [datetime]::Now.AddMinutes(60)
$TaskStartTime = $timeToStart
$service = new-object -ComObject("Schedule.Service")
$service.Connect()
$rootFolder = $service.GetFolder("\")
$TaskDefinition = $service.NewTask(0)
$TaskDefinition.RegistrationInfo.Description = $TaskDescription
$TaskDefinition.RegistrationInfo.Author = $taskRunAsuser
$TaskDefinition.Settings.Enabled = $true
$TaskDefinition.Settings.AllowDemandStart = $true
$TaskDefinition.Settings.ExecutionTimeLimit = "PT0S"
$TaskDefinition.Principal.RunLevel = 1
$triggers = $TaskDefinition.Triggers
$trigger = $triggers.Create(2)
$trigger.StartBoundary = $TaskStartTime.ToString("yyyy-MM-dd'T'HH:mm:ss")
$trigger.Enabled = $true
$Action = $TaskDefinition.Actions.Create(0)
$action.Path = $TaskCommand
$action.Arguments = $TaskArg
$rootFolder.RegisterTaskDefinition($TaskName,$TaskDefinition,6,$username,$password,1)
}
} -ArgumentList $scriptFile,$taskName,$description,$user,$plainTextPassword,$uncServer,$timeToStartTasks

"$computer scheduled task is now set."
#pause;
$timeToStartTasks = $timeToStartTasks.AddMinutes(5)
}
}
}else{
"Need to run this program with a valid Domain Administrator account."
}
# scheduled-task.ps1
# Purpose: to add a schedule onto a local system
# Requires: PowerShell 3.0 or higher

$scriptFile='C:\scripts\filecopy.ps1'
$sourceScriptFile="\\SHERVER007\c$\Software\File_Copy_Script_V0.16.ps1"
$callPowerShell = New-ScheduledTaskAction -Execute "Powershell.exe" -Argument "-ExecutionPolicy Bypass $scriptFile"
$dailyTrigger = New-ScheduledTaskTrigger -Daily -At 5pm
$user= "$env:USERDOMAIN\$username"
$password= 'PASSWORT'
$description="file copying operations"
$taskName="Files_Copy"
$settingsCommand = New-ScheduledTaskSettingsSet -MultipleInstances IgnoreNew -ExecutionTimeLimit 0

################################## Excuting Program as an Administrator ####################################
# Get the ID and security principal of the current user account
$myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
$myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)

# Get the security principal for the Administrator role
$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator

# Check to see if we are currently running "as Administrator"
if ($myWindowsPrincipal.IsInRole($adminRole))
{
# We are running "as Administrator" - so change the title and background color to indicate this
$Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)"
$Host.UI.RawUI.BackgroundColor = "Black"
clear-host
}
else
{
# We are not running "as Administrator" - so relaunch as administrator

# Create a new process object that starts PowerShell
$newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";

# Specify the current script path and name as a parameter
$newProcess.Arguments = $myInvocation.MyCommand.Definition;

# Indicate that the process should be elevated
$newProcess.Verb = "runas";

# Start the new process
[System.Diagnostics.Process]::Start($newProcess);

# Exit from the current, unelevated, process
exit
}

Write-Host -NoNewLine "Running as Administrator..."
################################## Excuting Program as an Administrator ####################################

# Ensure that script exists at destination
New-Item -ItemType Directory -Force -Path "C:\scripts";
if (-NOT (Test-Path $scriptFile)) {Copy-Item $sourceScriptFile -Destination $scriptFile -Force}

# Unregister the Scheduled task if it already exists
Get-ScheduledTask $taskName -ErrorAction SilentlyContinue | Unregister-ScheduledTask -Confirm:$false ;

# Create new scheduled task
Register-ScheduledTask -Action $callPowerShell -Trigger $dailyTrigger -TaskName $taskName -Description $description -User $user -Password $password -Settings $settingsCommand -RunLevel Highest

# Call the GUI version for double checking purposes
#taskschd.msc
#pause;

Leave a Reply

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