PowerShell JEA 会话配置文件中的 VariableDefinitions 部分支持哪些对象类型?

问题描述 投票:0回答:1

当使用

New-PSSessionConfigurationFile
定义要与 JEA 会话中的函数和脚本一起使用的“私有全局”变量时,我注意到我只能创建字符串变量。

有没有办法在

VariableDefinitions
部分定义其他类型的对象?

以下定义

VariableDefinitions @(
  @{ Name = 'Test'   ; Value = 'blah' }
  @{ Name = 'Integer'; Value = 13 }
  @{ Name = 'Array'  ; Value = @(1,2,3,4,'b') }

  @{
    Name = 'Hash'
    Value = @{
      Hash1 = '1'
      Hash2 = '2'
    }
  }

}

将导致(当然,如果允许可见 Cmdlet 中的 Invoke-Command)

> Invoke-Command {$Test}
blah

> Invoke-Command {$Integer}
13

> Invoke-Command {$Array}
System.Object[]

> Invoke-Command {$Hash}
System.Collections.Hashtable

起初,我很困惑,因为结果表明返回了某种对象。但仔细检查后发现,它是以字符串形式返回的原始对象类型名称。

> Invoke-Command {$Array -is [string]}
True

> Invoke-Command {$Hash -is [string]}
True

> Invoke-Command {$Integer -is [string]}
True

因此,似乎唯一可以使用

VariableDefinitions
定义的对象是字符串类型的变量。

powershell powershell-remoting remoting jea
1个回答
0
投票

使用哈希变量的解决方法可能是将所有关键部分定义为单独的变量,然后在要使用它的每个函数/脚本中构造它......

我真的不喜欢这个解决方案。

VariableDefinitions @(
  @{ Name = 'Var1'   ; Value = 'Cars' }
  @{ Name = 'Var1Type; Value = 'Hash' }

    @{ Name = 'Cars1'   ; Value = 'MyCar'   }
    @{ Name = 'Cars1Val'; Value = 'Volvo'   }

    @{ Name = 'Cars2'   ; Value = 'YourCar' }
    @{ Name = 'Cars2Val'; Value = 'Tesla'   }
}

(这可能会影响代码的可读性,抱歉)
(因为我不关心不同类型的变量,所以我不关心寻找 变量类型变量。现在不需要另一个级别的复杂性;)

Invoke-Command {
  $VarIndex = 0

  Get-Variable -Name "var?" -ValueOnly | foreach {#hash variable found
    $VarName = $_; $VarIndex++; $KeyIndex = 0
    Set-Variable -Name "$VarName" -Value @{} -Force

    Get-Variable -Name "$($VarName)?" -ValueOnly | foreach {#hash value pair found
      $KeyName = $_; $KeyIndex++

      Set-Variable -Name $VarName -Value (#add new hash value pair
        (Get-Variable -Name $VarName -ValueOnly) + @{
          (Get-Variable -Name "$($VarName)$KeyIndex" -ValueOnly) = 
          (Get-Variable -Name "$($VarName)$($KeyIndex)Val" -ValueOnly)
        }
      )# end redefine variable

    }#end foreach hash value pair

  }#end foreach hash variable

}
> $cars

Name      Value
----      -----
YourCar   Tesla
MyCar     Volvo
© www.soinside.com 2019 - 2024. All rights reserved.