簡體   English   中英

Powershell:Runspace / Pool我如何傳遞函數和共享變量?

[英]Powershell: Runspace/Pool how do i pass a function and shared variable?

我正在嘗試創建一個線程,該線程將使用共享變量(在主會話和線程之間),並賦予線程使用主代碼中外部函數的能力

我設法通過函數供線程使用,我設法通過只讀變量。 我的問題是,如果我在線程內更改變量的值,然后嘗試從主會話讀取它-我看不到值的更改,因此無法共享。

我怎么做? 我的目標是最終擁有一個線程。

這是我的代碼:

$x = [Hashtable]::Synchronized(@{})

$global:yo = "START"

Function ConvertTo-Hex {
    #Write-Output "Function Ran"
    write-host "hi"
    $x.host.ui.WriteVerboseLine("===========")
    write-host $yo
    $yo="TEST"
    write-host $yo
}
#endregion

        $rs = [RunspaceFactory]::CreateRunspace()
        $rs.ApartmentState,$rs.ThreadOptions = "STA","ReUseThread"
        $rs.Open()
        $rs.SessionStateProxy.SetVariable("x",$x)

ls
# create an array and add it to session state
$arrayList = New-Object System.Collections.ArrayList
$arrayList.AddRange(('a','b','c','d','e'))
 $x.host = $host
$sessionstate = [system.management.automation.runspaces.initialsessionstate]::CreateDefault()
$sessionstate.Variables.Add((New-Object System.Management.Automation.Runspaces.SessionStateVariableEntry('arrayList', $arrayList, $null)))
$sessionstate.Variables.Add((New-Object System.Management.Automation.Runspaces.SessionStateVariableEntry('x', $x, $null)))
#$sessionstate.Variables.Add((New-Object System.Management.Automation.Runspaces.SessionStateVariableEntry('yo', $yo, $true)))
$sessionstate.Commands.Add((New-Object System.Management.Automation.Runspaces.SessionStateFunctionEntry -ArgumentList 'ConvertTo-Hex', (Get-Content Function:\ConvertTo-Hex -ErrorAction Stop)))

$runspacepool = [runspacefactory]::CreateRunspacePool(1, 2, $sessionstate, $Host)
$runspacepool.Open()

$ps1 = [powershell]::Create()
$ps1.RunspacePool = $runspacepool

$ps1.AddScript({
    for ($i = 1; $i -le 15; $i++)
    {
        $letter = Get-Random -InputObject (97..122) | % {[char]$_} # a random lowercase letter
        $null = $arrayList.Add($letter)
        start-sleep -s 1
    }
})
$ps1.AddParameter(@($yo))

# on the first thread start a process that adds values to $arrayList every second
$handle1 = $ps1.BeginInvoke()

# now on the second thread, output the value of $arrayList every 1.5 seconds
$ps2 = [powershell]::Create()
$ps2.RunspacePool = $runspacepool

$ps2.AddScript({
     Write-Host "ArrayList contents is "
     foreach ($i in $arrayList)
     {
        Write-Host $i  -NoNewline
        Write-Host " " -NoNewline
     }
     Write-Host ""
     $yo = "BAH"
     ConvertTo-Hex
})
$ps2.AddParameter(@($yo))


1..10 | % {
    $handle2 = $ps2.BeginInvoke()
    if ($handle2.AsyncWaitHandle.WaitOne())
    {
        $ps2.EndInvoke($handle2)
    }
    start-sleep -s 1.5
    write-host "====================" + $yo
}
$global:yo = "test"

您需要在函數內部寫入$global

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM