【问题标题】:powershell watcher to run all the time without exitpowershell watcher 在不退出的情况下一直运行
【发布时间】:2020-03-08 01:56:48
【问题描述】:

我正在基于此链接测试文件/文件夹事件观察器

https://www.mobzystems.com/code/using-a-filesystemwatcher-from-powershell/

一切正常,但是当powershell关闭时,watcher也会被销毁,这是个问题,因为我想一直有一个watcher watch文件夹。

有什么方法可以实现吗?

非常感谢

【问题讨论】:

    标签: powershell powershell-2.0 powershell-3.0


    【解决方案1】:

    我必须使用 nssm 将我的 powershell 作为服务运行。在我的 powershell 中,我使用 Start-Process 启动我感兴趣的进程(php.exe),然后我的 powershell 将监视该进程的 PID 并执行我需要的任何操作(如果进程失败则发出警报,在脚本终止时关闭进程,等等)。

    Nssm 非常酷,它只是一个您运行(无需安装)来创建服务的 .exe。

    例如:

    创建一个脚本来运行观察者

    # Set up your logging; the stdout and stderr log files have to exist, Start-Process won't create them.
    
    $global:JobID = Start-Process `
        -FilePath 'C:\Windows\System32\WindowsPowerShell\v1.0\Powershell.exe  `
        -ArgumentList -File Start-FileSystemWatcher.ps1 -Path <path to watch> `
        -PassThru `
        -RedirectStandardOutput <your stdout log>
        -RedirectStandardError <your stderr log>
    
    # Optional loop to watch the JobID to see if it dies and then alert
    # Optional loop to stop the job and rotate the log files; then restart the job
    

    您可能对参数列表有一些问题。我还没有尝试传递命名参数。您可能希望将参数放入哈希表并将其放入 Start-Process。

    Nssm 很简单,这是命令行版本,因为我不得不这样做,十几次并编写了一个脚本来生成详细信息,而不是填写 24 种不同的表格:

    D:\nssm-2.24\win64\nssm.exe install "Watch <folder name> "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"
    
    D:\nssm-2.24\win64\nssm.exe set "Watch <folder name>" AppParameters  -nologo -noexit -noninteractive -noprofile -file <the script created above>
    
    D:\nssm-2.24\win64\nssm.exe set "Watch <folder name>" AppDirectory <the directory you want it to run in (optional)>
    

    但是您可以只运行 nssm.exe install "Watch 'folder name'" ,它会显示一些表格供您填写,因为您只执行一次。

    【讨论】:

    • 有非第三方方法吗?
    • 如果使用nssm,你能举个例子来添加观察者作为服务吗?我试过但不适合我
    • 我之前也写过一个 C++ 应用程序作为服务运行,然后运行 ​​Powershell。 NSSM 要容易得多。
    猜你喜欢
    • 1970-01-01
    • 2010-10-03
    • 2012-07-17
    • 1970-01-01
    • 2016-10-06
    • 1970-01-01
    • 2011-03-19
    • 2017-11-23
    • 1970-01-01
    相关资源
    最近更新 更多