PowerShell脚本问题远程重启会话

时间:2017-10-02 09:32:18

标签: powershell powershell-remoting

脚本问题是总是重新启动我自己的PC而不是提到的IP或会话。它应该逐行运行,但我没有看到问题。

感谢任何建议:

#Security Policy
Set-ExecutionPolicy -ExecutionPolicy Unrestricted

#Adding the range of IP address for Trading network
Set-Item -Path WSMan:\localhost\Client\TrustedHosts -value '10.22.*'

#IP address of the target PC, hostnames doesn't seems to be working
$targetpc = Read-Host "Please enter the IP Address of the target PC"

New-PSSession $targetpc -Credential(Get-Credential)

$sessionid = Read-Host "Please enter the session ID"

Enter-PSSession -Id $sessionid

Write-Host Test

[string]$forcereboot = Read-Host "Would you like to force reboot the PC ? [y][n]"

if ($forcereboot -eq "y") {
    #Restart-Computer -Force
    Stop-Process -Name "Notepad"
}

else { Exit-PSSession }

1 个答案:

答案 0 :(得分:2)

此处Restart-Computer在本地计算机本身中执行。

Enter-PSSession用于交互式远程处理,不能在脚本中使用。 要重新启动远程计算机,您不需要创建会话。您可以使用-ComputerName cmdlet的Restart-Computer参数重新启动远程主机。

#Example
Restart-Computer -ComputerName $Computer

如果您仍想使用WSMAN,则可以将会话与Invoke-Command

一起使用
 Invoke-Command -Session $SessionObject { Restart-Computer -Force }