Set-Item wsman:\localhost\Client\TrustedHosts -Value "xxx.xxx.xxx.xxx" -Force
$username = "xdfsdff"
$password = ConvertTo-SecureString "xxxxxxxxxx" -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($username, $password)
$ipAddress = "xxxxxxxxxxxx" # Enclose IP address in quotes
# Attempt to create a new PSSession
$session = New-PSSession -ComputerName $ipAddress -Credential $credential
# Check if $session is null
if ($session -ne $null) {
# If session is successfully created, execute script block
Invoke-Command -Session $session -ScriptBlock {
# Your script goes here
Get-Date
}
# Close the session
Remove-PSSession $session
} else {
Write-Host "Failed to establish a remote session."
}
我已使用 Powershell 使用上述脚本连接 Azure VM 机器,但面临以下问题
New-PSSession:[172.174.154.189] 连接到远程服务器 172.174.154.189 失败,并显示以下错误消息:WinRM 无法完成 手术。验证指定的计算机名称是否有效、该计算机是否可通过网络访问以及该计算机是否存在防火墙例外 WinRM 服务已启用并允许从此计算机进行访问。默认情况下,公共配置文件的 WinRM 防火墙例外限制对远程的访问 同一本地子网内的计算机。有关更多信息,请参阅 about_Remote_Troubleshooting 帮助主题。
WinRM 无法完成操作。验证指定的计算机名称是否有效、该计算机是否可通过网络访问、WinRM 服务的防火墙例外是否已启用并允许从此计算机进行访问。
上述错误表明远程服务器上未启用WinRM进行远程管理,您可以使用适当的cmdlet来启用它。
WinRM quickconfig
注意:如果在启用远程管理时遇到任何错误,只需将网络从公共网络更改为私有网络,然后尝试再次执行相同的命令即可。
使用cmd在防火墙上打开端口5986。
netsh firewall add portopening TCP 5986 "WinRM over HTTP"
使用 cmd 允许远程计算机作为客户端的受信任主机。
winrm set winrm/config/client '@{TrustedHosts="Remote_IP"}'
这是完整的脚本。
winrm quickconfig -transport:http or winrm quickconfig
netsh firewall add portopening TCP 5986 "WinRM over HTTP"
winrm set winrm/config/client '@{TrustedHosts="Remote_IP"}'
$password = ConvertTo-SecureString "Welcome@123$" -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential("Venkat", $password)
$ipAddress = "Remote-Server_IP"
# Attempt to create a new PSSession
$session = New-PSSession -ComputerName $ipAddress -Credential $credential
# Check if $session is null
if ($session -ne $null) {
# If session is successfully created, execute script block
Invoke-Command -Session $session -ScriptBlock {
# Your script goes here
Hostname
}
# Close the session
Remove-PSSession $session
} else {
Write-Host "Failed to establish a remote session."
}
输出: