Outdated script. Use something else by searching this blog further.

# scheduledTasksRemote_V0.0.2.ps1
# Purpose: to add a schedule onto remote system(s)
# Requires: PowerShell 3.0 or higher

# Scheduled task variables
$servers='server1','server2'
$scriptFile="\\snapshots\FileServerClusters\Daily-VSS-Snapshot.ps1"
$description="Daily snapshots of mounted volumes."
$taskName="Daily_Snapshots"

# Obtain Domain Admin Credentials
function obtainDomainAdminCredentials{
# Legacy domain binding function
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}
}
function isDomainAdmin($username){
if (!(get-module activedirectory)){Install-WindowsFeature RSAT-AD-PowerShell -Confirm:$false}
if((Get-ADUser $username -Properties MemberOf).MemberOf -match 'Domain Admins'){return $True;}else{return $false;}
}

# Create a domain context
function dotNetDomainBind{
Add-Type -AssemblyName System.DirectoryServices.AccountManagement;
Try {
$type = [System.DirectoryServices.AccountManagement.ContextType]::Domain;
$context = New-Object System.DirectoryServices.AccountManagement.PrincipalContext $type,$env:USERDOMAIN;
return $context;
} Catch {
If ($_.Exception.InnerException -like "*The server could not be contacted*") {
write-host "Could not contact a server for the specified domain $env:USERDOMAIN via DotNet Method.";
} Else {
write-host "Unknown errors occured while attempting to contact $env:USERDOMAIN via DotNet Method.";
}
return $false;
}
}

$attempt=0;
$maxAttempts=3;
$plainTextPassword='';
Do{
$attempt++;
$failureMessage = $null;

[string][ValidateNotNullOrEmpty()]$userName=Read-Host -Prompt "Please input a User ID";
if($userName -match '\\'){$username=$env:USERDOMAIN+'\'+$userName}
$password = Read-Host -Prompt "Please type in the password for user $userName" -AsSecureString;
$plainTextPassword=[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))

# Test bind to this credential
try {
# Test bind
$context=dotNetDomainBind
if($context){
$validatedAccount = $context.ValidateCredentials($userName,$plainTextPassword)
}else{
$validatedAccount=isValidCred -u $userName -p $plainTextPassword
}

If ($validatedAccount) {
$isDomainAdmin=isDomainAdmin -username $userName;
if($isDomainAdmin){
$credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $userName,$password;
$validAccount=$true;
}else{
$failureMessage += "$attempt out of $maxAttempts`: $userName account is valid, but it is not a Domain Admin";
}
}else{
$failureMessage += "$attempt out of $maxAttempts`: username and/or password error";
}
}catch{
$failureMessage += "Unable to bind to $env:USERDOMAIN.";
}

# Depending on whether there are failures, proceed accordingly
if($failureMessage){
If ($attempt -lt $maxAttempts-1) {
$message = "$failureMessage`: Authentication error. Please Try again.";
Write-Warning $message;
} elseif ($attempt -eq $maxAttempts-1){
$message = "$failureMessage`: Last attempt.";
Write-Warning $message;
$credentials= $false;
}
}

} Until (($ValidAccount) -or ($Attempt -eq $MaxAttempts))
if($credentials){return $credentials;}else{return $false}
}
$adminCredential=obtainDomainAdminCredentials;

function isUnc($path){
$uncServer=$scriptFile | select-string -pattern "(?<=\\\\)(.*?)(?=\\)" | Select -ExpandProperty Matches | Select -ExpandProperty Value
$isValidPath=test-path $scriptfile -ErrorAction SilentlyContinue
if ($uncServer -and $isValidPath){
return $uncServer;
}else{
return $False;
}
}

function setScheduledTasks{
param(
[string[]]$servers,
[string]$scriptFile,
[string]$description,
[string]$taskName,
$credential
)

$username=$credential.Username;
$plaintextPassword=$credential.GetNetworkCredential().password;
$uncServer=isUnc $scriptFile

if ($credential){
if ($uncServer){

foreach ($computer in $servers){
Invoke-Command -ComputerName $computer -Credential $credential -ScriptBlock{
param($scriptFile,$taskName,$description,$user,$password,$uncServer)

$settingsCommand = New-ScheduledTaskSettingsSet -MultipleInstances IgnoreNew -ExecutionTimeLimit 0
$callPowerShell = New-ScheduledTaskAction -Execute "Powershell.exe" -Argument "-ExecutionPolicy Bypass $scriptFile"
$dailyTrigger = New-ScheduledTaskTrigger -Daily -At 5pm
$username="$env:USERDOMAIN`\$user"

# 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:credential -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;

} -ArgumentList $scriptFile,$taskName,$description,$username,$plainTextPassword,$uncServer
# pause;
}
}
}else{
"Need to run this program with a valid Domain Administrator account."
}
}

setScheduledTasks -servers $servers -scriptFile $scriptFile -description $description -taskName $taskName -credential $adminCredential
# 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;