摘要:在 PowerShell 中,你可以使用 `Shutdown-Computer` cmdlet 来实现自动关机。你可以通过指定不同的参数来控制关机的行为,比如延迟关机的时间、强制关闭应用程序、关闭原因等。 下面是一个简单的 Pow...
在 PowerShell 中,你可以使用 `Shutdown-Computer` cmdlet 来实现自动关机。你可以通过指定不同的参数来控制关机的行为,比如延迟关机的时间、强制关闭应用程序、关闭原因等。
下面是一个简单的 PowerShell 脚本示例,演示如何立即关机:
```powershell
Shutdown the computer immediately
Shutdown-Computer
```
如果你希望在一定时间后关机,比如 60 秒后,你可以使用 `-Time` 参数:
```powershell
Shutdown the computer after 60 seconds
Shutdown-Computer -Time (Get-Date).AddSeconds(60)
```
你也可以添加其他参数来控制关机行为。例如,`-Force` 参数可以强制关闭正在运行的应用程序,`-Confirm` 参数可以控制是否需要用户确认。
以下是一个更复杂的示例,展示了如何在关机前提示用户,并强制关闭所有应用程序:
```powershell
Prompt the user before shutdown
$response = Read-Host "Are you sure you want to shutdown the computer? (y/n)
if ($response -eq 'y' -or $response -eq 'Y') {
Shutdown the computer immediately, forcing all running applications to close
Shutdown-Computer -Force
} else {
Write-Host "Shutdown cancelled.

```
关机原因和注释
你还可以指定关机的原因和注释,这些信息会记录在事件日志中。例如:
```powershell
Shutdown the computer with a reason and comment
Shutdown-Computer -Reason MajorOther -Comment "Scheduled maintenance
```
远程关机
如果你需要远程关闭计算机,可以结合使用 `-ComputerName` 参数。确保你有相应的权限来远程关闭目标计算机。
```powershell
Shutdown a remote computer
Shutdown-Computer -ComputerName "RemoteComputerName" -Force
```
完整示例
以下是一个包含多种选项的完整示例脚本:
```powershell
param (
[switch]$Force,
[int]$Delay = 0,
[string]$ComputerName = $env:COMPUTERNAME,
[string]$Reason = "Other",
[string]$Comment = "No comment
if ($Delay -gt 0) {
$shutdownTime = (Get-Date).AddSeconds($Delay)
} else {
$shutdownTime = $null
if ($Force) {
$confirm = "-Force
} else {
$confirm = $null
Write-Host "Shutting down computer '$ComputerName' in $Delay seconds with reason '$Reason' and comment '$Comment'...
Shutdown-Computer -ComputerName $ComputerName -Time $shutdownTime -Force:$Force -Reason $Reason -Comment $Comment -Confirm:$confirm
```
运行这个脚本时,你可以通过参数来控制是否强制关机、延迟时间、目标计算机名称、关机原因和注释。例如:
```powershell
ShutdownScript.ps1 -Force -Delay 120 -ComputerName "TargetComputer" -Reason "MajorOther" -Comment "Scheduled maintenance
```
这个脚本会在 120 秒后强制关闭名为 "TargetComputer" 的计算机,并记录关机原因为 "MajorOther",注释为 "Scheduled maintenance"。