enter-pssession invoke-command,何时使用?

Nin*_*nja 5 powershell invoke-command

我正在编写一个脚本来停止和启动两个远程服务器中的服务.这是我的问题,

在我的脚本中,我做了new-pssession并使用invoke-command来停止和启动服务.

我需要使用enter-pssession吗?

更新: 这是我的脚本需要做的事情.

在server1上,我需要停止并启动两个服务.在server2上,我需要停止并启动一项服务.

# foreach for server 1 since I need to stop and start two services. created a session for server 1
foreach($service in $services){

    $session = New-PSSession -ComputerName $serverName -Credential $cred
    Invoke-Command -Session $session -ScriptBlock {param($service) Stop-Service -Name $service} -ArgumentList $service
    remove-pssession -session $session

}

# created a session for server 2. I need to stop and start just one service in server 2
$session = New-PSSession -ComputerName $serverName -Credential $cred
Invoke-Command -Session $session -ScriptBlock {param($service) Stop-Service -Name $service} -ArgumentList $service
remove-pssession -session $session
Run Code Online (Sandbox Code Playgroud)

这是正确的方法吗?

Kir*_*ran 9

Enter-PSSession - 由于这是一个交互式会话,您可以在控制台中键入所需内容,并立即在控制台中查看结果(就像CMD一样).如果它只有2个服务器,那么你可以使用enter-pssession但它总是串行意味着你在一台服务器上做某事然后你转移到另一台服务器上.

New-PSSession - 创建与远程服务器的持久连接,通常在有一系列命令在较大脚本\工作流的各个阶段在多个服务器上运行时使用.

例:

$s1, $s2 = New-PSSession -ComputerName Server1,Server2
Get-Service -Name Bits                #on localhost
Invoke-Command -session $s1 -scriptblock { # remote commands here }
Get-Process                           #on localhost
Invoke-Command -session $s1 -scriptblock { # remote commands here }
Remove-pSSession -session $s1 #on localhost
Run Code Online (Sandbox Code Playgroud)

如果您只是想停止\开始一些服务,那么您可以在不打开持久连接的情况下执行此操作.

例:

Invoke-Command -ComputerName (Get-Content Machines.txt) -ScriptBlock {Stop-Service -Name Bits}
Run Code Online (Sandbox Code Playgroud)