PowerShell 生成一个后台进程以保持事件状态

标签 powershell background spawn

我有一个简单的保持事件功能,每 60 秒按一次 ScrollLock 来阻止我的工作笔记本电脑进入休眠状态(这里不能选择更改电源管理设置,因为这些设置仅限于我在这个工作系统上使用) ,但此脚本依赖于启动该功能的控制台始终处于打开状态。有人可以建议如何将此功能实现:

• 生成一个完全独立的进程(即不是子进程),即使运行该函数的控制台关闭后该进程仍将继续存在?

• 使新进程完全静默,即作为后台进程隐形启动,我只能通过运行 Get-Process 才能看到该进程?

能够以这种方式创建独立(非子)进程对于我认为的许多其他情况都有好处 - 创建不随调用控制台关闭的独立进程的能力将非常有用。

function KeepAlive {
    $wsh = New-Object -ComObject WScript.Shell
    while($true) {
        $wsh.SendKeys('{SCROLLLOCK}')
        Start-Sleep 60
    }
}

最佳答案

最简单的方法 - 使用后台作业:

Start-Job {
    $wsh = New-Object -ComObject WScript.Shell
    while($true) {
        $wsh.SendKeys('{SCROLLLOCK}')
        Start-Sleep 60
    }
}

后台作业将(对您来说透明)导致代码在单独的子进程中运行。

如果您想在同一进程的后台运行代码,您需要将代码分配在单独的运行空间中运行 - 运行空间在某种程度上类似于“线程”在低级编程语言中:

# Create (and open) a new runspace
$rs = [runspacefactory]::CreateRunspace([initialsessionstate]::CreateDefault2())
$rs.Open()

# Create a [powershell] object to bind our script to the above runspaces
$ps = [powershell]::Create().AddScript({
    $wsh = New-Object -ComObject WScript.Shell
    while($true) {
        $wsh.SendKeys('{SCROLLLOCK}')
        Start-Sleep 60
    }
})

# Tell powershell to run the code in the runspace we created
$ps.Runspace = $rs

# Invoke the code asynchronously
$handle = $ps.BeginInvoke()

BeginInvoke() 函数将立即返回,并且代码将开始在我们的后台运行空间中执行 - 这意味着它不会阻塞默认运行空间,因此您可以继续使用 shell时间。

再次结束/停止执行:

$ps.Stop()

关于PowerShell 生成一个后台进程以保持事件状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60571667/

相关文章:

Python:生成 sudo 进程(在新终端中),等待完成

windows - 如何在具有管理员权限的 Windows 任务计划程序中设置 Powershell 脚本?

powershell - 使用 PowerShell 将前导零添加到文件名

PowerShell,下载 StackOverflow 答案或评论的内容

shell 脚本 : run a block of code in the background without defining a new function?

ios - 我如何知道我的应用程序是由于后台刷新而启动的?

c# - 将另一种语言转换为 powershell 或在 powershell 中使用该语言

php - 在 AJAX 中执行带有变量参数的 php 脚本?

Node.js:杀死 ChildProcess#spawn 的子进程

python - pexpect,期望'$'时脚本超时