2

在我们的脚本可以继续之前,我们有两个 PSSession 需要建立并导入到当前会话中。两个步骤都需要大约 10 - 15 秒,串联运行时总共需要 20 - 30 秒。

是否可以在单独的运行空间中运行 New-PSSession,然后以某种方式将该已建立的会话导入父进程?

例如从此改变:

New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri ("https://$($service)/PowerShell/") -Credential $Credential -Authentication Basic -AllowRedirection -ErrorAction Stop

New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "https://outlook.office365.com/powershell-liveid/" -Credential $Credential -Authentication Basic -AllowRedirection -ErrorAction Stop

可能是这样的(警告这不起作用):

$credential = Get-Credential

$scriptblock = 
{
       param ([string]$Credential)

       $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "https://outlook.office365.com/powershell-liveid/" -Credential $Credential -Authentication Basic -AllowRedirection -ErrorAction Stop
       return $session
}


$shell = [PowerShell]::Create().AddScript($scriptblock).AddParameter($credential)

$job = $shell.BeginInvoke()
$result = $shell.EndInvoke($job)

Import-PSSession $result

最终目标是让这花费更少的时间,如果我们并行使用 New-PSSession,它会在 10 - 15 秒内完成,而不是串联的 20 - 30 秒。我会对任何可以实现这一点的答案感到满意,它不需要使用运行空间。

编辑:添加目标

4

1 回答 1

3

感谢@ShankarShastri 为我们指明了正确的方向。New-PSSession commandlet 支持将一组 URI 或 ComputerNames 作为输入。我有要测试的服务器而不是 URI,但请看一下:

$cred = Get-Credential DOMAIN\user

$servers = 
"server1.domain.company.com",
"server2.domain.company.com",
"server3.domain.company.com",
"server4.domain.company.com",
"server5.domain.company.com",
"server6.domain.company.com",
"server7.domain.company.com"

(Measure-Command {
    foreach($s in $servers) { $temp = New-PSSession -ComputerName $s -Authentication Negotiate -Credential $cred }
}).TotalSeconds

# 2.987739

(Measure-Command {
    $s1, $s2, $s3, $s4, $s5, $s6, $s7 = New-PSSession -ComputerName $servers -Authentication Negotiate -Credential $cred
}).TotalSeconds

# 0.5793281

这表明 New-PSSession 运行 7 次与运行 New-PSSession 一次并提供 7 个计算机名称。差异大约快 6 倍,这意味着连接是异步进行的。

因此,在您的情况下,您可能可以通过运行以下命令来完成您想要的操作:

$sessions1, $sessions2 = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri ("https://$($service)/PowerShell/"),"https://outlook.office365.com/powershell-liveid/" -Credential $Credential -Authentication Basic -AllowRedirection -ErrorAction Stop
于 2016-09-15T21:29:26.900 回答