PowerShell2.0之桌面计算机维护(八)关闭或重启远程计算机
在執行更名主機或添加域操作后,為了使設置生效需要重啟計算機。為此需要使用Win32_OperatingSystem WMI類的shutdown()和reboot()方法,要執行的操作由向腳本傳遞的參數-a確定,值為s則關機;為r則重啟。為了順利地關機或重啟所用賬戶必須具有相應的權限,將EnablePrivileges的屬性設置為$true。
需要注意的是如果執行關機和重啟操作的主機是本機,則需要兩次定義Get-WmiObject,分別為出示憑據和不需要使用憑據的情況。如果操作的主機不是本機,則需要使用備用憑據,此腳本的代碼如下:
param(
$computer="localhost",
$user = "administrator",
$password,
$a,
$help
)
function funHelp()
{
$helpText=@"
DESCRIPTION:
NAME: ShutdownRebootComputer.ps1
Shutdown or reboot a local or remote machine.
ARAMETERS:
-computer Specifies the name of the computer upon which to run the script
-user user credentials
-password password of the user
-a(ction) action to perform < s(hutdown), r(eboot) >
-help prints help file
SYNTAX:
ShutdownRebootComputer.ps1 -computer WebServer -a s
Shutdown a remote computer named WebServer
ShutdownRebootComputer.ps1 -computer WebServer -a r
-user WebServer\admin -password MyPassword
Reboots a computer named WebServer. Uses the credentials
of the WebServer admin, with password of MyPassword
ShutdownRebootComputer.ps1
Displays message pointing to help
ShutdownRebootComputer.ps1 -help ?
Displays the help topic for the script
"@
$helpText
exit
}
if($help){ "Obtaining help ..." ; funhelp }
switch($a)
{
"s" {
if($computer -ne "localhost")
{
$objWMI = Get-WmiObject -Class Win32_operatingsystem `
-computername $computer -credential $user
$objWMI.psbase.Scope.Options.EnablePrivileges = $true
$objWMI.shutdown()
}
ELSE
{
$objWMI = Get-WmiObject -Class Win32_operatingsystem `
-computername $computer
$objWMI.psbase.Scope.Options.EnablePrivileges = $true
$objWMI.shutdown()
}
}
"r" {
if($computer -ne "localhost")
{
$objWMI = Get-WmiObject -Class Win32_operatingsystem `
-computername $computer -credential $user
$objWMI.psbase.Scope.Options.EnablePrivileges = $true
$objWMI.reboot()
}
ELSE
{
$objWMI = Get-WmiObject -Class Win32_operatingsystem `
-computername $computer
$objWMI.psbase.Scope.Options.EnablePrivileges = $true
$objWMI.reboot()
}
}
DEFAULT { "You must supply an action. Try this"
"ShutdownRebootComputer.ps1 -help ?" }
}
執行此腳本調用命令.\ShutdownRebootComputer.ps1 –a s和.\ShutdownRebootComputer.ps1 –a r,分別對應當前系統的關閉和重啟。關機和重啟操作在本地計算機上可以直接執行,而遠程計算機需要指定相應的參數,其中-computer指定主機名;-user指定用戶;-password指定用戶密碼。
為了避免誤運行該腳本關閉或重啟計算機,將默認操作設置為顯示幫助字符串,并要求用戶在提供-help參數的情況下才能運行該腳本的幫助信息。
?
作者: 付海軍
出處:http://fuhj02.cnblogs.com
版權:本文版權歸作者和博客園共有
轉載:歡迎轉載,為了保存作者的創作熱情,請按要求【轉載】,謝謝
要求:未經作者同意,必須保留此段聲明;必須在文章中給出原文連接;否則必究法律責任
個人網站: http://txj.lzuer.com/
轉載于:https://www.cnblogs.com/fuhj02/archive/2011/01/14/1935971.html
總結
以上是生活随笔為你收集整理的PowerShell2.0之桌面计算机维护(八)关闭或重启远程计算机的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux下常用软件下载
- 下一篇: C语言面试算法题(一)