首页 > 解决方案 > 如何从 powershell 启动一个进程而不把它带到前面?

问题描述

我正在为工作编写一个简单的清理脚本,其中应该包括 gpupdate。我想要做的是运行 gpupdate 并捕获输出或在另一个窗口中运行它并将当前窗口保持在顶部。我尝试了多种不同的方式来运行 gpupdate.exe(包括使用具有不同焦点选项的 WSH),但它总是在当前 PowerShell 窗口的前面弹出。PS commandlet Invoke-GPUpdate 显示错误“访问被拒绝”,因此这似乎不是一个可用的解决方案。我目前正在尝试调用 ProcessGPUpdate API,但我的代码一定有问题。无论如何,我真的不喜欢这个解决方案,因为它看起来不会提供反馈/进展。

参考 API:https ://docs.microsoft.com/en-us/previous-versions/windows/desktop/wmi_v2/class-library/remotegpupdate-processgpupdate-method-string-boolean-boolean-boolean-boolean-uint32-string -microsoft-grouppolicy

我当前的非工作代码

Add-Type '@
using Microsoft.GroupPolicy;
public static void ProcessGPUpdate(
string Computer,
bool force,
bool boot,
bool logoff,
bool sync,
uint delayInMinutes,
string target
)
'@

我愿意接受有关如何完成此任务的建议。目前,我正在考虑最小化运行 gpupdate。

编辑:根据要求添加命令输出



PS H:\> $gpupdate = Start-Job -ScriptBlock { gpupdate.exe 2>$1 }
PS H:\> get-job

Id     Name            PSJobTypeName   State         HasMoreData
Location             Command
--     ----            -------------   -----         -----------
--------             -------
1      Job1            BackgroundJob   Failed        False
localhost             gpupdate.exe 2>$1


PS H:\> Receive-Job -Name Job1
[localhost] The background process reported an error with the following
message: .
    + CategoryInfo          : OpenError: (localhost:String) [],
PSRemotingTransportException
    + FullyQualifiedErrorId : 2100,PSSessionStateBroken
PS H:\> $gpupdate = Start-Job -ScriptBlock { gpupdate.exe 2>$1 } -Name
gpupdate
PS H:\> Receive-Job -Name gpupdate
[localhost] The background process reported an error with the following
message: .
    + CategoryInfo          : OpenError: (localhost:String) [],
PSRemotingTransportException
    + FullyQualifiedErrorId : 2100,PSSessionStateBroken
PS H:\> $gpupdate = Start-Job -ScriptBlock { & "gpupdate.exe 2>$1" } -Name
gpupdate
PS H:\> Receive-Job -Name gpupdate
[localhost] The background process reported an error with the following
message: .
    + CategoryInfo          : OpenError: (localhost:String) [],
PSRemotingTransportException
    + FullyQualifiedErrorId : 2100,PSSessionStateBroken
[localhost] The background process reported an error with the following
message: .
    + CategoryInfo          : OpenError: (localhost:String) [],
PSRemotingTransportException
    + FullyQualifiedErrorId : 2100,PSSessionStateBroken
PS H:\> get-job

Id     Name            PSJobTypeName   State         HasMoreData
Location             Command
--     ----            -------------   -----         -----------
--------             -------
1      Job1            BackgroundJob   Failed        False
localhost             gpupdate.exe 2>$1
3      gpupdate        BackgroundJob   Failed        False
localhost             gpupdate.exe 2>$1
5      gpupdate        BackgroundJob   Failed        False
localhost             & "gpupdate.exe 2>$1"

标签: powershell

解决方案


推荐阅读