使用PowerShell写守护进程

$current_dir = Split-Path -Parent $MyInvocation.MyCommand.Definition;
$log_file = "${current_dir}\monitor.log"
# 脚本日志最大为10M
$log_max_size = 10*1024*1024

# 需要检测的进程名和启动文件路径
$process_name = "notepad++"
$start_up_file = "C:\Program Files (x86)\Notepad++\notepad++.exe"

function log($content)
{
    $date = Get-Date -UFormat "%Y-%m-%d %H:%M:%S"
    Add-Content -Path $log_file -Value "$date : $content"

    $log_file_size = (Get-ChildItem $current_dir\monitor.log).Length
    if ( $log_file_size -gt $log_max_size)
    {
        if ( Test-Path $current_dir\monitor.log.bak )
        {
            Remove-Item $current_dir\monitor.log.bak
        }
        Copy-Item $log_file $current_dir\monitor.log.bak
        Clear-Content $log_file
    }
}

Get-Process | findstr $process_name > $null
if ( $? -eq "True" )
{
    log "process ${process_name} is running!"
}
else
{
    log "process ${process_name} is not exist, now to start it."
    Start-Process -FilePath $start_up_file
    if ( $? -eq "True" )
    {
        log "start ${process_name} succefully!"
    }
    else
    {
        log "start ${process_name} failed!"
    }
}

在win10上默认执行策略为Restricted,不让执行powershell脚本

PS C:\WINDOWS\system32> get-executionpolicy
Restricted

自测试时可以改变执行策略为RemoteSigned,测试完后,再改为

PS C:\WINDOWS\system32> set-ExecutionPolicy RemoteSigned

测试完后,再改为Restricted

PS C:\WINDOWS\system32> set-ExecutionPolicy Restricted

对于实际的服务器环境,最好为脚本签名,让脚本以受信方式执行

Power如何执行参见:
https://www.pstips.net/powershell-create-and-start-scripts.html

猜你喜欢

转载自blog.csdn.net/u010178308/article/details/88633182
今日推荐