Powershell 脚本使用参数创建计划任务

Powershell 脚本使用参数创建计划任务

我有这个脚本,用于检查命名服务是否正在运行。实际情况下,它正在检查“RSCDsvc”服务。

if(!(Get-ScheduledTask | Where-Object {$_.TaskName -like "restart_RSCDsvc" })){
New-Item -Path C:\Admin\scripts -Name check-service.cmd -Force -ItemType "file" -Value '
@ECHO OFF
SET SvcName=%~1

SC QUERYEX "%SvcName%" | FIND "STATE" | FIND /v "RUNNING" > NUL && (
ECHO %SvcName% is not running
ECHO START %SvcName%

NET START "%SvcName%" > NUL || (
ECHO "%SvcName%" wont start
EXIT /B 1
)
ECHO "%SvcName%" is started
EXIT /B 0
) || (
ECHO "%SvcName%" is running
EXIT /B 0
)
'
$dt= ([DateTime]::Now)
$timespan = $dt.AddYears(33) -$dt;
$principal = New-ScheduledTaskPrincipal -UserID "NT AUTHORITY\SYSTEM" -LogonType ServiceAccount -RunLevel Highest
$Action = New-ScheduledTaskAction -Execute C:\Admin\scripts\check-service.cmd -Argument "RSCDsvc"
$Trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).Date -RandomDelay (New-TimeSpan -Minutes 5) -RepetitionDuration $timespan -RepetitionInterval (New-TimeSpan -Minutes 10)
$Task = New-ScheduledTask -Action $Action -Trigger $Trigger -Settings ($Stset = New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Minutes 3)) -Principal $principal
$Task | Register-ScheduledTask -TaskName ‘restart_RSCDsvc’
}

现在我的问题是,我是否可以使用更多参数,这样我就不必在脚本中频繁输入特定的服务名称。现在我必须在 3 个不同的点进行设置

if(!(Get-ScheduledTask | Where-Object {$_.TaskName -like "restart_RSCDsvc" }))

$Action = New-ScheduledTaskAction -Execute C:\Admin\scripts\check-service.cmd -Argument "RSCDsvc"

$Task | Register-ScheduledTask -TaskName ‘restart_RSCDsvc’

就像我说的,我的目标是得到类似“$Servicename = RSCDSVC”的东西,然后将其设置为这三行。我已经尝试过了,但我已经为完成这个脚本而感到自豪了,因为我不太擅长编写脚本 :(

答案1

您可以用变量名称替换 RSCDSVC 的所有实例,就像您理论的那样

$Servicename = "RSCDSVC"
if(!(Get-ScheduledTask | Where-Object {$_.TaskName -like "restart_$Servicename" })){
New-Item -Path C:\Admin\scripts -Name check-service.cmd -Force -ItemType "file" -Value '
@ECHO OFF
SET SvcName=%~1

SC QUERYEX "%SvcName%" | FIND "STATE" | FIND /v "RUNNING" > NUL && (
ECHO %SvcName% is not running
ECHO START %SvcName%

NET START "%SvcName%" > NUL || (
ECHO "%SvcName%" wont start
EXIT /B 1
)
ECHO "%SvcName%" is started
EXIT /B 0
) || (
ECHO "%SvcName%" is running
EXIT /B 0
)
'
$dt= ([DateTime]::Now)
$timespan = $dt.AddYears(33) -$dt;
$principal = New-ScheduledTaskPrincipal -UserID "NT AUTHORITY\SYSTEM" -LogonType ServiceAccount -RunLevel Highest
$Action = New-ScheduledTaskAction -Execute C:\Admin\scripts\check-service.cmd -Argument "$Servicename"
$Trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).Date -RandomDelay (New-TimeSpan -Minutes 5) -RepetitionDuration $timespan -RepetitionInterval (New-TimeSpan -Minutes 10)
$Task = New-ScheduledTask -Action $Action -Trigger $Trigger -Settings ($Stset = New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Minutes 3)) -Principal $principal
$Task | Register-ScheduledTask -TaskName "restart_$Servicename"
}

相关内容