-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCreateTask.ps1
More file actions
78 lines (59 loc) · 2.13 KB
/
CreateTask.ps1
File metadata and controls
78 lines (59 loc) · 2.13 KB
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
72
73
74
75
76
77
78
# $scriptToExecutePath = "C:\\backup-mongo.ps1";
# $taskName = "MongoDB Backup - <databaseName>"
# $taskDescription = "Make a dump of <databaseName> database"
$ErrorActionPreference = 'Stop'
$pathScriptToExecute = ""
$taskName = ""
$taskDescription = ""
function Show-ErrorMessage([string] $message) {
Write-Host -Message $message `
-ForegroundColor Red `
-BackgroundColor White
}
function Get-TaskInfo {
$script:pathScriptToExecute = Read-Host "Please enter the path to the PowerShell script"
$script:taskName = Read-Host "Please enter the name of the task"
$script:taskDescription = Read-Host "Please enter the description of the task (optional)"
Get-Param
}
function Get-Param {
if ([String]::IsNullOrEmpty($pathScriptToExecute) -or -not ($pathScriptToExecute | Test-Path) ) {
Show-ErrorMessage "The script path doesn't exists"
$script:pathScriptToExecute = Read-Host "Please enter the path to the PowerShell script"
Get-Param
return
}
if ([String]::IsNullOrEmpty($taskName)) {
Show-ErrorMessage "The name of the task can not be empty"
$script:taskName = Read-Host "Please enter the username"
Get-Param
return;
}
}
Get-TaskInfo
$taskExists = Get-ScheduledTask | Where-Object { $_.TaskName -like $taskName }
if ($taskExists) {
Show-ErrorMessage "An taks with the name $taskName already exists!"
exit
}
if ([String]::IsNullOrEmpty($taskDescription)) {
$taskDescription = "MongoDB Backup"
}
$action = New-ScheduledTaskAction `
-Execute 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe' `
-Argument "-NoProfile -NoLogo -NonInteractive -ExecutionPolicy Bypass -File $pathScriptToExecute"
$trigger = New-ScheduledTaskTrigger -Daily -At 1am
$taskSettings = New-ScheduledTaskSettingsSet -Compatibility Win8
Register-ScheduledTask `
-TaskName $taskName `
-Action $action `
-Trigger $trigger `
-Settings $taskSettings `
-Description $taskDescription
$runTask = Read-Host "Run task immediatly? [y/n] (y) "
$noOptions = @('n', 'no')
if ($runTask -in $noOptions) {
return
}
# OBS: If you need to run the task manually for testing use:
Start-ScheduledTask -TaskName $taskName