powershell - 在任务计划程序中传递Powershell参数

标签 powershell scheduled-tasks

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/

相关文章:

azure - 如何在 Azure PowerShell 中获取所有资源参数详细信息

windows - powershell 传递命令行参数

windows - 用于删除早于 X 天的文件的批处理脚本(基于创建日期,而不是修改日期)

R taskscheduleR不执行脚本

azure - 对于 Microsoft Graph 中缺少 UsersPermissionToUserConsentToAppEnabled 是否有任何解决方法?

postgresql - 在 PowerShell 中更改第三方应用程序输出的编码

windows - 写入主机和写入输出之间的 PowerShell 区别?

php - "php script"/"mysql update"动态调度

windows - 在 windows 的 schtasks 命令中指定 "start-in"目录

c++ - 多线程作业队列管理器