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
我需要从Task Scheduler中传递以下参数
-错误日志
- 服务
-最大大小
我目前有这样的任务计划程序设置
程序/脚本: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'-服务'foo1','foo2'-MaxSize'5MB'“
当我运行计划的任务时,什么都没有发生,这可能是错误的。
最佳答案
我建议安排任务使用-File
参数而不是-Command
。例:
程序/脚本:C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
添加参数(可选):-NoProfile -ExecutionPolicy Bypass -File "Scheduled-ServiceRestart.ps1" -ErrorLog "ScriptErrors.txt" -Services "foo1","foo2" -MaxSize 5MB
开始于(可选):C:\Users\<username>\Documents\Scripts
您可以在任务的“开始于”属性中为脚本指定开始目录,并避免使用冗长的脚本和日志文件路径名。 (请注意,我假设您正在本地计算机上而不是通过网络运行脚本的副本,这会增加潜在的复杂性和失败的可能性。)
关于powershell - 在任务计划程序中传递Powershell参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44594179/