-
Notifications
You must be signed in to change notification settings - Fork 0
/
Execute-ScheduledTask-Remote.ms1
71 lines (57 loc) · 2.48 KB
/
Execute-ScheduledTask-Remote.ms1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<#
.SYNOPSIS
Registers and executes (after 1
minute) a scheduled task on a remote computer.
.PARAMETER RemoteComputerName
The name of the remote computer.
.PARAMETER TaskName
The name of the scheduled task.
.PARAMETER ExecutablePath
The path to the executable file.
.PARAMETER Arguments
The arguments to pass to the executable file.
.PARAMETER UserName
The user name under which to run the task.
.EXAMPLE
Execute-ScheduledTask-Remote -RemoteComputerName "RemoteComputerName" -TaskName "Updates-NEW" -ExecutablePath '"c:\Windows\temp\PSADT_MSUpdates\Deploy-Application.exe"' -Arguments '-DeployMode "Silent"' -UserName "SYSTEM"
.NOTES
Author: Thorsten E.
#>
function Execute-ScheduledTask-Remote {
param (
[string]$RemoteComputerName,
[string]$TaskName,
[string]$ExecutablePath,
[string]$Arguments,
[string]$UserName = "SYSTEM"
)
$logPath = "C:\Windows\Temp\TaskExecutionLog.txt" # Passe den Pfad nach Bedarf an
# Parameter Validierung
if (-not (Test-Path -PathType Leaf $ExecutablePath)) {
Write-Host "ExecutablePath '$ExecutablePath' does not exist."
Add-Content -Path $logPath -Value "$(Get-Date) - ExecutablePath '$ExecutablePath' does not exist."
return
}
$taskAction = New-ScheduledTaskAction -Execute $using:ExecutablePath -Argument $Arguments
$taskTrigger = New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes(1)
$taskSettings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -RunOnlyIfNetworkAvailable
try {
Register-ScheduledTask -TaskName $TaskName -Action $taskAction -Trigger $taskTrigger -Settings $taskSettings -User $UserName -CimSession $RemoteComputerName -Force
Write-Host "Scheduled task '$TaskName' registered on $RemoteComputerName."
Add-Content -Path $logPath -Value "$(Get-Date) - Scheduled task '$TaskName' registered on $RemoteComputerName."
} catch {
Write-Host "Error registering scheduled task: $_"
Add-Content -Path $logPath -Value "$(Get-Date) - Error registering scheduled task: $_"
}
}
$remoteComputerName = "RemoteComputerName"
$taskName = "Updates-NEW"
$executablePath = 'c:\Windows\temp\PSADT_MSUpdates\Deploy-Application.exe'
$arguments = '-DeployMode "Silent"'
$params = @{
RemoteComputerName = $remoteComputerName
TaskName = $taskName
ExecutablePath = $executablePath
Arguments = $arguments
}
Execute-ScheduledTask-Remote @params