Basic Install-WindowsTaskTemplate

on Monday, July 8, 2019

I don’t install powershell scripts as Windows Tasks every day (any probably need to find a way for another system to manage that responsibility), so it’s easy to forget how to do them. Here’s a quick template to install a Windows Task on a remote machine:

$name = "Your-ScriptName"
$servers = @("XXX", "YYY", "ZZZ")
foreach($server in $servers) {
$filename = "$name.ps1"
$filepath = "\\$server\Scripts\$filename"
$install = $true
if((Test-Path $filepath) -eq $false) {
$srcPath = "\\your\root\powershellscript\location\$name\Current\$filename"
if(Test-Path $srcPath) {
. robocopy "$(Split-Path $srcPath -Parent)" "$(Split-Path $filepath -Parent)" $filename
} else {
Write-Warning "Powershell script $srcPath could not be found. Skipping install."
$install = $false
}
}
if($install) {
$args = @($name, $filename)
$scriptBlock = {
$name = $args[0]
$filename = $args[1]
$fp = "your-drive-letter:\Scripts\$filename"
$taskName = $name
$fp = "powershell $fp"
$found = . schtasks.exe /query /tn "$taskName" 2>null
if($found -ne $null) {
. schtasks.exe /delete /tn "$taskName" /f
$found = $null
}
if($found -eq $null) {
. schtasks.exe /create /ru "SYSTEM" /tn "$taskName" /sc daily /st "01:00" /tr "$fp"
. schtasks.exe /run /tn "$taskName"
}
}
Invoke-Command -ComputerName $server -ScriptBlock $scriptBlock -ArgumentList $args
}
}

0 comments:

Post a Comment


Creative Commons License
This site uses Alex Gorbatchev's SyntaxHighlighter, and hosted by herdingcode.com's Jon Galloway.