我有一组计算机要关机然后重新开机,是否有 Powershell 命令可以执行此操作?我有'shutdown'命令来关闭它们,我不能使用reboot 命令。
提前致谢!
我有一组计算机要关机然后重新开机,是否有 Powershell 命令可以执行此操作?我有'shutdown'命令来关闭它们,我不能使用reboot 命令。
提前致谢!
如果您愿意在 PowerShell 脚本中使用 WMI,则Win32_OperatingSystem
WMI 类对象具有称为Win32Shutdown
and的方法Win32ShutdownTracker
,其中任何一个都允许您关闭或重新启动计算机,或强制注销远程用户。我创建了一个 scriptlet/script cmdlet/advanced 函数,它使用后者来完成您想要做的事情;它适用于从 2.0 开始的任何版本的 Windows PowerShell:
function Close-UserSession {
<#
.SYNOPSIS
Logs off a remote user, or reboots a remote computer.
.DESCRIPTION
Logs off a remote user, or reboots a remote computer.
Optionally, forces the logoff or reboot without waiting for running programs to terminate.
.INPUTS
This cmdlet can accept a computer object from the pipeline.
Default is to act on the local computer.
.OUTPUTS
Returns the success or failure of the attempt to logoff/reboot the remote computer.
.PARAMETER ComputerName
The name of the computer to log off or reboot.
.PARAMETER Reboot
If present, causes the computer to reboot instead of logging off the current user.
.PARAMETER Force
If present, forces the logoff/reboot without waiting for running programs to shut down.
.Parameter Delay
Defaults to 0. Specifies the number of seconds to wait before logging off or rebooting
.EXAMPLE
PS C:\> Close-UserSession -ComputerName WPBBX-LW57359
(Would cause the current user on the indicated computer to be logged off immediately)
.EXAMPLE
PS C:\> Close-UserSession -Reboot -ComputerName WPBBX-LW57359 -Delay 30
(Would cause the indicated computer to reboot after 30 seconds)
.EXAMPLE
PS C:\> Close-UserSession -ComputerName WPBBX-LW57359 -Reboot -Force
(Forces an immediate reboot of the indicated computer without waiting for programs to shut down.)
#>
[CmdletBinding(SupportsShouldProcess=$true)]
param(
[Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[String]$ComputerName = $env:COMPUTERNAME,
[Switch]$Force,
[Alias("Boot","Restart")]
[Switch]$Reboot,
[int]$Delay = 0
)
$logoff = 0
$shutdown = 1
$rebootit = 2
$forceit = 4
$poweroff = 8
$func = 0 #default is to just log the user off
$message = "Logging you off for ITSD troubleshooting "
if ($Reboot) {
$func = $func -bor $rebootit #reboot the indicated computer
$message = "Rebooting the computer for ITSD troubleshooting "
}
if ($Force) { $func = $func -bor $forceit } #Force the logoff or reboot without worrying about closing files
if ($Delay -eq 0) {
$message = $message + "now!"
} else {
$message = $message + "in $Delay seconds."
}
$RemoteOS = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $ComputerName
if ($psCmdlet.ShouldProcess($ComputerName)) {
($RemoteOS.Win32ShutdownTracker($Delay,$message,0,$func)).ReturnValue
}
}