还原Enable-PSRemoting所做的更改

时间:2014-09-03 17:19:37

标签: powershell localhost

我创建了一个脚本,用于根据http://blogs.technet.com/b/bshukla/archive/2011/04/28/how-revert-changes-made-by-enable-psremoting.aspx还原Enable-PSRemoting所做的更改

当我在Powershell控制台中输入以下命令时,它按预期工作,即禁用PSRemoting

c:\> winrm delete winrm/config/listener?address=*+transport=HTTP

c:\> Stop-Service winrm

c:\> Set-Service -Name winrm -StartupType Disabled

c:\> Set-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -Name LocalAccountTokenFilterPolicy -Type dword -Value 0

执行脚本时

$scriptblock = {winrm delete winrm/config/listener?address=*+transport=HTTP}

$host_name =  (hostname.exe)

Invoke-Command -ScriptBlock $scriptblock -ComputerName $host_name

Stop-Service winrm

Set-Service -Name winrm -StartupType Disabled

Set-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -Name LocalAccountTokenFilterPolicy -Type dword -Value 0

我得到了不需要的输出

WARNING: The network connection to local_computer has been interrupted. Attempting to reconnect for up to 4 minutes...
WARNING: Attempting to reconnect to local_computer ...
WARNING: Attempting to reconnect to local_computer ...
WARNING: Attempting to reconnect to local_computer ...
WARNING: Attempting to reconnect to local_computer ...
WARNING: Attempting to reconnect to local_computer ...
WARNING: Attempting to reconnect to local_computer ...
WARNING: Attempting to reconnect to local_computer ...
WARNING: The reconnection attempt to local_computer failed. Attempting to disconnect the session...
WARNING: Computer local_computer has been successfully disconnected.
Invoke-Command : Network connectivity to local_computer has been lost and the reconnection attempt failed. Please repair the network connection and reconnect using Connect-PSSession or Receive-PSSession.
At C:\share\ps_disable.ps1:6 char:1
+ Invoke-Command -ScriptBlock $scriptblock -ComputerName $host_name
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationTimeout: ([PSSession]Session5:PSSession) [Invoke-Command], RuntimeException
    + FullyQualifiedErrorId : PowerShellNetworkFailedStartDisconnect,Microsoft.PowerShell.Commands.InvokeCommandCommand

WARNING: Session Session5 with instance ID c7243bdf-bb9f-49c1-a1b0-9798969b0f99 on computer local_computer has been successfully disconnected.
WARNING: Session Session5 with instance ID c7243bdf-bb9f-49c1-a1b0-9798969b0f99 has been created for reconnection.
  1. 如何消除“警告.....”
  2. 如何提高执行速度,而不是花费4分钟,即Attempting to reconnect for up to 4 minutes
  3. 如何解决Invoke-Command:与local_computer的网络连接已丢失,重新连接尝试失败。

1 个答案:

答案 0 :(得分:1)

将其移至答案,以便解决问题。

使用-InDisconnectedSession开关会立即断开运行该命令的会话,因此连接丢失不会使脚本停止运行或导致警告。它将返回一个PSSession对象,您可以在以后使用它来获取命令的结果。