gpt4 book ai didi

powershell - enter-pssession invoke-command,什么时候使用?

转载 作者:行者123 更新时间:2023-12-04 17:33:22 25 4
gpt4 key购买 nike

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

在我的脚本中,我执行了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

这是正确的方法吗?

最佳答案

Enter-PSSession-由于这是一个交互式 session ,因此您可以在控制台上键入所需的内容,然后立即在控制台中查看结果(就像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

如果您只想停止\启动几个服务,则可以在不打开持久连接的情况下执行此操作。

例子:
Invoke-Command -ComputerName (Get-Content Machines.txt) -ScriptBlock {Stop-Service -Name Bits}

关于powershell - enter-pssession invoke-command,什么时候使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34619486/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com