我有一组要关闭电源然后再打开电源的计算机,是否有Powershell命令可以执行此操作?我有“关机”命令将其关闭,我不能使用重新启动命令。
谢谢!
答案 0 :(得分:2)
如果使用powershell 5.0 +,则可以使用 Restart-Computer cmdlet。
$computers = @('name1','name2')
foreach ($computer in $computers)
{
Restart-Computer -ComputerName $computer -Force
}
另一种替代方法是将关机与 CMD 一起使用。
shutdown -i
答案 1 :(得分:0)
如果您愿意在PowerShell脚本中使用WMI,则Win32_OperatingSystem
WMI类对象具有称为Win32Shutdown
和Win32ShutdownTracker
的方法,这两种方法都将允许您关闭或重新启动计算机,或强行注销远程用户。我创建了一个scriptlet / script cmdlet /高级函数,该函数使用后者来完全执行您要执行的操作;它可与以下版本的任何Windows PowerShell版本2.0配合使用:
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
}
}