PowerShell写守护进程

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_36485376/article/details/83210591

工作中,需要守护一个装在Windows上的进程,下面代码中以守护notepad++的进程为例
写到此处,是因为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

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

猜你喜欢

转载自blog.csdn.net/weixin_36485376/article/details/83210591
今日推荐