connect-mstsc-ComputerName$server-Credential$Cred1-ErrorAction stop

connect-mstsc-ComputerName$server-Credential$Cred1-ErrorAction stop

$Cred1 = New-Object -TypeName pscredential -ArgumentList "domain\user",(ConvertTo-SecureString -String'密码'-AsPlainText -Force);

$服务器=获取内容“C:\Packages\Values.txt”

函数 Connect-Mstsc {

[cmdletbinding(SupportsShouldProcess,DefaultParametersetName='UserPassword')]
param (
    [Parameter(Mandatory=$true,
        ValueFromPipeline=$true,
        ValueFromPipelineByPropertyName=$true,
        Position=0)]
    [Alias('CN')]
        [string[]]     $ComputerName,
    [Parameter(ParameterSetName='UserPassword',Mandatory=$true,Position=1)]
    [Alias('U')] 
        [string]       $User,
    [Parameter(ParameterSetName='UserPassword',Mandatory=$true,Position=2)]
    [Alias('P')] 
        [string]       $Password,
    [Parameter(ParameterSetName='Credential',Mandatory=$true,Position=1)]
    [Alias('C')]
        [PSCredential] $Credential,
    [Alias('A')]
        [switch]       $Admin,
    [Alias('MM')]
        [switch]       $MultiMon,
    [Alias('F')]
        [switch]       $FullScreen,
    [Alias('Pu')]
        [switch]       $Public,
    [Alias('W')]
        [int]          $Width,
    [Alias('H')]
        [int]          $Height,
    [Alias('WT')]
        [switch]       $Wait
)

begin {
    [string]$MstscArguments = ''
    switch ($true) {
        {$Admin}      {$MstscArguments += '/admin '}
        {$MultiMon}   {$MstscArguments += '/multimon '}
        {$FullScreen} {$MstscArguments += '/f '}
        {$Public}     {$MstscArguments += '/public '}
        {$Width}      {$MstscArguments += "/w:$Width "}
        {$Height}     {$MstscArguments += "/h:$Height "}
    }

    if ($Credential) {
        $User     = $Credential.UserName
        $Password = $Credential.GetNetworkCredential().Password
    }
}
process {
    foreach ($Computer in $ComputerName) {
        $ProcessInfo = New-Object System.Diagnostics.ProcessStartInfo
        $Process = New-Object System.Diagnostics.Process

        # Remove the port number for CmdKey otherwise credentials are not entered correctly
        if ($Computer.Contains(':')) {
            $ComputerCmdkey = ($Computer -split ':')[0]
        } else {
            $ComputerCmdkey = $Computer
        }

        $ProcessInfo.FileName    = "$($env:SystemRoot)\system32\cmdkey.exe"
        $ProcessInfo.Arguments   = "/generic:TERMSRV/$ComputerCmdkey /user:$User /pass:$($Password)"
        $ProcessInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Hidden
        $Process.StartInfo = $ProcessInfo
        if ($PSCmdlet.ShouldProcess($ComputerCmdkey,'Adding credentials to store')) {
            [void]$Process.Start()
        }

        $ProcessInfo.FileName    = "$($env:SystemRoot)\system32\mstsc.exe"
        $ProcessInfo.Arguments   = "$MstscArguments /v $Computer"
        $ProcessInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Normal
        $Process.StartInfo       = $ProcessInfo
        if ($PSCmdlet.ShouldProcess($Computer,'Connecting mstsc')) {
            [void]$Process.Start()
            if ($Wait) {
                $null = $Process.WaitForExit()
            }       
        }
    }
}

}

RDP 连接 Powershell

foreach ($server 在 $servers 中) {

需要检查是否有防火墙阻止服务器之间的通信

重启计算机 $server -Credential $cred1 -Force -ErrorAction Stop Start-Sleep 20 write-host “服务器 $server 已通过重启启动” -BackgroundColor yellow

执行 { $LastSuccess = $true 尝试 { 如果 (New-Object System.Net.Sockets.TCPClient -ArgumentList $server,3389 )
{ 写入主机 $server '准备好进行 RDP 连接'-ForegroundColor 绿色

}

} 捕获 { 写警告 $error[0] 开始睡眠 30 $LastSuccess = $false } } 直到 ( $LastSuccess )

需要在源机器上启用以下功能才能进行通信

$服务器1=$服务器.tostring()

设置项目 WSMan:\localhost\Client\TrustedHosts -Value $server1 -Force

调用命令 -ComputerName $server -Credential $Cred1 -scriptblock{

启用-PSRemoting -Force}

连接-mstsc -计算机名称$服务器-凭据$Cred1

connect-mstsc-ComputerName$server-Credential$Cred1-ErrorAction stop

开始睡眠 10

注销我登录的会话

$scriptBlock = { $ErrorActionPreference = '停止'

 try {
     ## Find all sessions matching the specified username
     $sessions = quser | Where-Object {$_ -match 'Testing'}
     ## Parse the session IDs from the output
     $sessionIds = ($sessions -split ' +')[2]
     Write-Host "Found $(@($sessionIds).Count) user login(s) on computer."
     ## Loop through each session ID and pass each to the logoff command
     $sessionIds | ForEach-Object {
         Write-Host "Logging off session id [$($_)]..."
         logoff $_
     }
 } catch {
     if ($_.Exception.Message -match 'No user exists') {
         Write-Host "The user is not logged in."
     } else {
         throw $_.Exception.Message
     }
 }

}

调用命令-计算机名称$server-凭据$Cred1-ScriptBlock$scriptBlock

}

专家。我已经根据一些要求尝试了上述脚本,该脚本需要在输入列表上重新启动机器,并通过建立 RDP 连接登录和注销,它在某些机器上运行良好,但在某些情况下不起作用。登录和注销有时会因注销而失败,有时要等到 RDP 成功,我们需要根据策略单击确定,如何以其他方式缓解这种情况。无中断登录....任何帮助都很有帮助

错误:

WinRM 客户端无法处理该请求。在以下条件下,可以使用 IP 地址进行默认身份验证:传输为 HTTPS 或目标位于 TrustedHosts 列表中,并且提供了显式凭据。使用 winrm.cmd 配置 TrustedHosts。请注意,TrustedHosts 列表中的计算机可能未经过身份验证。有关如何设置 TrustedHosts 的更多信息,请运行以下命令:winrm help config

状况:

我只需要使用 RDP 会话来登录和注销

我使用单一帐户与所有服务器建立连接

相关内容