繁体   English   中英

PowerShell关闭打开的会话

[英]PowerShell Closing open sessions

我正在编写一个大型脚本,我在其中运行Foreach循环,在该循环中定义变量,然后检查$Server变量是否可ping,以及是否可远程访问。

为此,我使用PowerShell帮助中的以下函数:

# Function to check if $Server is online
Function CanPing ($Server) {
   $error.clear()
   $tmp = Test-Connection $Server -ErrorAction SilentlyContinue

   if ($?) {
       Write-Host "Ping succeeded: $Server"; Return $true
   }
   else {
        Write-Host "Ping failed: $Server."; Return $false
   }
}

# Function to check if $Server is remotely accessible
Function CanRemote ($Server) {
    $s = New-PSSession $Server -Authentication Credssp -Credential $Credentials -Name "Test" -ErrorAction SilentlyContinue

    if ($s -is [System.Management.Automation.Runspaces.PSSession]) {
        Enter-PSSession -Session $s
        Exit-PSSession
        Write-Host "Remote test succeeded: $Server."; Return $true
    }
    else {
        Write-Host "Remote test failed: $Server."; Return $false
    }
}

# Execute functions to check $Server
if ($Server -ne "UNC") {

    if (CanPing $Server) {
        if (-Not (CanRemote $Server)) {
        Write-Host "Exit loop REMOTE" -ForegroundColor Yellow
        continue
        }
    }
    else {
         Write-Host "Exit loop PING" -ForegroundColor Yellow
         continue # 'continue' to the next object and don't execute the rest of the code, 'break' exits the foreach loop completely
    }
} 

每次运行此代码时,都会在远程服务器上创建一个名为wsmprovhost.exe 如果我在网络上找到的信息正确,则此过程代表PowerShell会话。 但是,在执行Get-PSSession $Server时,PowerShell ISE中没有显示打开的会话,即使这些进程在远程服务器上可见,并且只能使用任务管理器终止。

当我经常运行此代码时,会达到打开会话的限制,因为每次将新进程wsmprovhost.exe添加到$Server并且命令出错时。 我试图通过在代码中添加Exit-PSSession来解决这个问题,但它并没有关闭会话。

任何帮助或想法都非常受欢迎。

问题是Enter-PSSession。 Enter-PSSession只能以交互方式使用,不能在脚本中使用它。 我建议更像这样的东西:

# Function to check if $Server is remotely accessible
Function CanRemote ($Server) {

  Try {
   $s = New-PSSession $Server -Authentication Credssp -Credential $Credentials -Name "Test" -ErrorAction Stop
   Write-Host "Remote test succeeded: $Server."
   $true
   Remove-PSSession $s
   }

  Catch {
          "Remote test failed: $Server."
          $false
        }
 }

如果我已正确理解,您的远程ps-session不会被关闭。

对于我的理解, Get-PSSession将显示会话,直到您的本地会话处于活动状态(我的意思是您创建远程ps-session )但是一旦您的本地会话结束, Get-PSSession将不会显示它们因为它们不再存在您的计算机而不是远程系统(或)它们不再是本地会话范围。

您可以使用该命令获取会话

Get-PSSession -ComputerName server_name

如果你想删除它们,你可以这样做

Get-PSSession -ComputerName server_name | Remove-PSSession

即使执行以下命令也是如此,如果您无法创建会话

Get-PSSession -ComputerName server_name | Remove-PSSession

请在目标计算机中重新启动服务Windows远程管理(WS-Management)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM