【问题标题】:How do I access variables in execution script from executed script [duplicate]如何从执行脚本访问执行脚本中的变量[重复]
【发布时间】:2019-08-28 15:53:43
【问题描述】:

我有一个正在运行的 PS1 脚本 (start-webserver.ps1) 作为“web 服务器”运行,它正在侦听 http 调用,该调用执行在对“web 服务器的调用”中执行的脚本(例如:script2.ps1) ”。 我正在使用 Start-Job 执行脚本。如何在已执行的脚本(script2.ps1)中访问 start-webserver.ps1 中的变量?

Start-WebServer.ps1

$allObjects = @()
foreach ($item in $items) {
    $objectUID = $item.Attributes.Value                          
    $propertiesHash = [ordered]@{UID = $objectUID}                           
    $properties = $items.ChildNodes
    foreach ($property in $properties.ChildNodes) {
        $propertyName = $property.Attributes.Value                               
        $propertyValue = $property.innerText                                 
        $propertiesHash.Add($propertyName, $propertyValue)
    }
    $object = New-Object PSObject -Property $propertiesHash                          
    $allObjects += $object
}
$job = Start-Job -Name "$identifier" -FilePath "Path\To\ScriptToExecute.ps1" -InputObject $allObjects -ArgumentList $propertiesHash

ScriptToExecute.ps1

'Script executed!' | Out-File -Path ".\output.txt" -Encoding UTF8 -Append
$propertiesHash | Get-Member | Out-File -Path ".\output.txt" -Encoding UTF8 -Append
$allObjects | Get-Member | Out-File -Path ".\output.txt" -Encoding UTF8 -Append

我最终得到一个包含以下内容的“output.txt”:
脚本已执行!
空行

【问题讨论】:

    标签: powershell


    【解决方案1】:

    您需要在 ScriptToExecute 中定义您接收的参数

    默认设置在 $args 变量中。

    在您的情况下,只需使用 $args[0] 就足够了。

    即:

    'Script executed!' | Out-File -Path ".\output.txt" -Encoding UTF8 -Append
    $args[0] | Get-Member | Out-File -Path ".\output.txt" -Encoding UTF8 -Append
    

    如果你还想接收$allObjects,你需要将Start-WebServer修改成这样:

    $job = Start-Job -Name "$identifier" -FilePath "Path\To\ScriptToExecute.ps1" -InputObject $allObjects -ArgumentList @($propertiesHash,$allObjects)
    

    然后这样做:

    'Script executed!' | Out-File -Path ".\output.txt" -Encoding UTF8 -Append
    $args[0] | Get-Member | Out-File -Path ".\output.txt" -Encoding UTF8 -Append
    $args[1] | Get-Member | Out-File -Path ".\output.txt" -Encoding UTF8 -Append
    

    更好的方法是在 ScriptToExecute 中指定参数

    即:

    param($propertiesHash, $allObjects)
    'Script executed!' | Out-File -Path ".\output.txt" -Encoding UTF8 -Append
    $propertiesHash | Get-Member | Out-File -Path ".\output.txt" -Encoding UTF8 -Append
    $allObjects | Get-Member | Out-File -Path ".\output.txt" -Encoding UTF8 -Append
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多