在执行更名主机或添加域操作后,为了使设置生效需要重启计算机。为此需要使用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/