我正在尝试在 Powershell 中异步运行某些自定义代码。以下尝试在后台线程中检查更新:
Function CheckUpdates($manager)
{
. "$PSScriptRoot\..\commands\upgradecmd.ps1";
$upgradeCmd = New-Object UpgradeCmd -ArgumentList $manager;
[bool]$upgradesAvailable = $false;
try
{
$Global:silentmode = $true;
$upgradeCmd.preview = $true;
Start-Job -ArgumentList $upgradeCmd -ScriptBlock { param($upgradeCmd) $upgradeCmd.Run(); };
Get-Job | Receive-Job;
$upgradesAvailable = $upgradeCmd.upgradesAvailable;
}
finally
{
$Global:silentmode = $false;
}
if ($upgradesAvailable)
{
WriteWarning "Upgrades detected.";
WriteWarning "Please, run the upgrade command to update your Everbot installation.";
}
}
问题在于,在作业内部(在 ScriptBlock 中),PS无法识别有关我的自定义“ Run()”方法的任何信息,因此它不知道如何调用它。我尝试使用-InitializationScript
参数在作业中“包含”该类,但收效甚微。
在网络上搜索后,看来方法是使用 PS Jobs ,PS中没有线程处理或类似“异步”之类的东西。关键是我只想异步运行PS代码中某些类的方法。
答案 0 :(得分:1)
为什么不在脚本块中加点源?
Function CheckUpdates($manager)
{
try
{
$Global:silentmode = $true
$Scriptblock = {
param($manager)
. "<absolutepath>\upgradecmd.ps1"; #better to replace this with absolute path
$upgradeCmd = New-Object UpgradeCmd -ArgumentList $manager;
[bool]$upgradesAvailable = $false
$upgradeCmd.preview = $true
$upgradeCmd.Run()
$upgradesAvailable = $upgradeCmd.upgradesAvailable;
Return $upgradesAvailable
}
Start-Job -ArgumentList $manager -ScriptBlock $Scriptblock
$upgradesAvailable = @(Get-Job | Wait-Job | Receive-Job) #This will probably not be so cut and dry but you can modify your code based on the return value
}
finally
{
$Global:silentmode = $false;
}
if ($upgradesAvailable)
{
WriteWarning "Upgrades detected.";
WriteWarning "Please, run the upgrade command to update your Everbot installation.";
}
}
我还添加了一个Wait-Job
,以便您的脚本等待作业完成。