function ServiceRestart
{
Param
(
$ErrorLog,
$Services,
$MaxSize
)
$Time = Get-Date -Format 'yyyy:MM:dd HH:mm:ss'
$Result = (Get-Item $ErrorLog).length
if($Result -gt $MaxSize)
{
Clear-Content $ErrorLog
}
Try
{
Foreach($Service in $Services)
{
Restart-Service -DisplayName $Service -ErrorAction Stop
}
} Catch
{
"ERROR: $Service could not be restarted $Time" | Add-Content $ErrorLog
}
}
ServiceRestart -ErrorLog -Services -MaxSize
我需要从任务计划程序传递以下参数
- 错误日志
- 服务
- MaxSize
我目前的任务调度程序设置如下
程序/脚本:C:\ Windows \ System32 \ WindowsPowerShell \ v1.0 \ powershell.exe
添加参数(可选):
-Command“&\ ServerName \ C $ \ Users ***** \ Documents \ Scripts \ Scheduled-ServiceRestart.ps1
-ErrorLog 'ServerName\C$\Users*****\Documents\log\ScriptErrors.txt'
-Services 'foo1','foo2'
-MaxSize '5MB'“
当我运行计划任务时没有任何事情发生,可能会出错 .
4 回答
我建议安排任务使用
-File
参数而不是-Command
. 例:程式/脚本:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
添加参数(可选):
-NoProfile -ExecutionPolicy Unrestricted -File 'Scheduled-ServiceRestart.ps1' -ErrorLog 'ScriptErrors.txt' -Services 'foo1','foo2' -MaxSize 5MB
从(可选)开始:
C:\Users\<username>\Documents\Scripts
您可以在任务的“开始”属性中指定脚本的起始目录,并避免脚本和日志文件的冗长路径名 . (请注意,我假设您在本地计算机上运行脚本的副本,而不是通过网络运行,这增加了潜在的复杂性和失败的可能性 . )
该函数需要先导入 . 我建议将该功能保存为模块并将其放在system32或程序文件的modules文件夹中 . 这样,当PowerShell启动时,它将自动导入您的功能 .
执行此操作后,任务计划程序非常简单 .
程序/脚本
添加参数(可选):
至于问题的字面答案:可能你需要添加单引号来包围你的脚本位置,否则它会尝试将特殊字符/反斜杠解释为转义 .
例如:
您还可以在powershell脚本中添加一些基本日志记录,以确保它实际上正在启动 .
我在 生产环境 Powershell计划任务中使用“-Command&”样式,如果字符串格式正确,它们可以正常工作 .
显然,在使用计划任务时,引号的选择会产生巨大的差异 . 试试这个你的论点: