如何访问动态创建变量的方法?

时间:2017-10-16 10:53:08

标签: powershell scripting

我是PowerShell的新手,我尝试做这样的事情:

$sshictcred = New-Object 
System.Management.Automation.PSCredential("username",$password)

New-Variable -Name $Server"session" -Value (New-SSHSession -ComputerName 
$Server -Credential($credentials))

New-Variable -Name $Server"stream" -Value ("`$"(Get-Variable -Name 
$Server"session" | % Name).Session.CreateShellStream("PS-SSH", 0, 0, 0, 0, 1000))

我的问题:

在最后一个命令中我收到错误"你不能在空值表达式上调用方法"。我想这是因为它缺少$符号,因为它应该生成以前设置的变量的名称。

所以我创造了一个新的"我相信动态"来自先前生成的变量的变量。

创建新var -Value之后我想要的输出:

 $PREVVARNAME.Session.CreateShellStream(xxxxx)

Simplified I 想想我想要一个像这样生成的字符串:     " $"输出命令GET-VAR为字符串" session"

1 个答案:

答案 0 :(得分:0)

我无法访问这些cmdlet,但看起来您只是想在这里创建一些动态变量并使用一些相关的方法。

首先让我们捕获第一个动态变量的输出并保存。

$serversession = New-Variable -Name $Server"session" -Value (New-SSHSession -ComputerName $Server -Credential($credentials)) -Passthru

所以现在$serversession将是System.Management.Automation.PSVariable,它至少具有名称和值属性。

现在我们可以使用$serversession来执行下一步操作

$serversession.Value.Session.CreateShellStream("PS-SSH", 0, 0, 0, 0, 1000))

应该这样做。

我个人认为这里需要动态变量。如果您计划有多个并发会话,可能.....但有很多方法可以解决这个问题。

就像例如

的哈希表
$sessions = @{}
$sessions["$Server"] = New-SSHSession -ComputerName $Server -Credential($credentials)
$sessions["$Server"].Session.CreateShellStream("PS-SSH", 0, 0, 0, 0, 1000))