如何使用 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
定义的对象是
[string]
类型的变量。

但是有没有办法使用

VariableDefinitions
定义其他类型的变量?

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

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

我不太喜欢这个解决方案,但它是可行的。

1.定义简单变量

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

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

2.在
FunctionDefinitions
...

中定义辅助函数
function New-HashVariable {
<#
.NOTES
  Looks for simple string variables already defined in pairs, like

  $VarNameX - $VarNameValX
  $VarNameY - $VarNameValY

  and creates a hashtable, $VarName, containing the labeled
  values provided in the simple string variables.
#>

  [CmdletBinding()]
  param (
    [string]$Name,
    [switch]$ValueOnly
  )

  Set-Variable $Name -Value @{} -Force
  $KeyIndex = 0

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

    Set-Variable $Name -Value (#add a value pair
      (Get-Variable $Name -ValueOnly) + @{
        (Get-Variable -Name "$($Name)$KeyIndex" -ValueOnly) =
        (Get-Variable -Name "$($Name)$($KeyIndex)Val" -ValueOnly)
      }
    )#end extend hash table

  }#end foreach value pair

  if ($ValueOnly) {
    return Get-Variable $Name -ValueOnly
  }

  return Get-Variable $Name

}

3.在需要的地方创建哈希变量...

Invoke-Command {
  $Cars = New-HashVariable 'Cars' -ValueOnly
}

在 Invoke-Command 末尾添加

$cars
将导致

> $cars

Name      Value
----      -----
YourCar   Tesla
MyCar     Volvo

您当然可以在

ScriptsToProcess
中定义的任何脚本中正常声明哈希变量,但这不会隐藏哈希值。

在脚本中使用

New-HashVariable
也是如此。在这种情况下,您需要在脚本中使用后将其删除,否则它将在 JEA 交互式控制台会话中可用。

© www.soinside.com 2019 - 2024. All rights reserved.