Skip to content

Commit ab5bda1

Browse files
committed
Fix removing all lines from crontab
1 parent 0be252e commit ab5bda1

2 files changed

Lines changed: 26 additions & 6 deletions

File tree

demos/crontab.ps1

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,26 @@
1-
# Use the crontab module available at ./modules/CronTab
1+
2+
if (!($env:PSMODULEPATH -split ';' | Where-Object { $_.StartsWith($PSScriptRoot) }))
3+
{
4+
$env:PSMODULEPATH += ";$PSScriptRoot/modules"
5+
}
6+
7+
Import-Module CronTab
28

39
# Get the existing cron jobs
10+
Get-CronJob
411

5-
# Sort them by data
12+
# New cron job to clean out tmp every day at 1am
13+
New-CronJob -Command 'rm -rf /tmp/*' -Hour 1
614

7-
# Create a new one using a DateTime object
15+
# New cron job to start a build
16+
New-CronJob -Command 'powershell -c "cd ~/src/PowerShell; ipmo ./build.psm1; Start-PSBuild"' -Hour 2 -DayOfWeek 1-5
17+
18+
# Sort them by data
19+
Get-CronJob | Sort-Object Command
820

921
# Show in bash that the new cron job exists
22+
crontab -l
23+
24+
# Remove a cron job
25+
Get-CronJob | Where-Object { $_.Command -match '^powershell.*' } | Remove-CronJob
26+

demos/modules/CronTab/CronTab.psm1

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
2+
using namespace System.Collections.Generic
3+
14
$crontabcmd = "/usr/bin/crontab"
25

36
class CronJob {
@@ -15,7 +18,7 @@ function Get-CronTab ([String] $user) {
1518
$crontab = Invoke-CronTab -user $user -arguments "-l" -noThrow
1619
if ($crontab -is [System.Management.Automation.ErrorRecord]) {
1720
if ($crontab.Exception.Message.StartsWith("no crontab for ")) {
18-
$crontab = $null
21+
$crontab = @()
1922
}
2023
else {
2124
throw $crontab.Exception
@@ -85,15 +88,15 @@ function Remove-CronJob {
8588
process {
8689

8790
[string[]] $crontab = Get-CronTab -user $UserName
88-
[string[]] $newcrontab = $null
91+
$newcrontab = [List[string]]::new()
8992
$found = $false
9093

9194
foreach ($line in $crontab) {
9295
$cronjob = ConvertTo-CronJob -crontab $line
9396
if ((Compare-object $cronjob.psobject.properties $Job.psobject.properties) -eq $null) {
9497
$found = $true
9598
} else {
96-
$newcrontab += $line
99+
$newcrontab.Add($line)
97100
}
98101
}
99102

0 commit comments

Comments
 (0)