VBScriptを使ってPowerShellスクリプトを管理者権限で実行する

VBScriptで管理者権限に昇格させ、実行ポリシー(ExecutionPolicy) を Bypass に設定し、PowerShellスクリプトを実行させる。

そうすると、確認メッセージ無しでPowerShellスクリプトを実行させることができる。
例)ExecutionPolicyの変更も、確認メッセージなしで実行できちゃう

で、VBSとPS1のファイル名のドットの前を同一にしておけば、VBSをいちいち修正しないで実行できるようにしてみた。
例)test1.ps1を実行させたいときは、test1.vbsの名前で下記のVBSを保存して、test1.vbsを実行するだけでOK

[test1.vbs]

'管理者権限に設定
Dim WMI, OS, Value, Shell
do while WScript.Arguments.Count = 0 and WScript.Version >= 5.7
    Set WMI = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\.\root\cimv2")
    Set OS = WMI.ExecQuery("SELECT *FROM Win32_OperatingSystem")
    For Each Value in OS
     if left(Value.Version, 3) < 6.0 then exit do
    Next
    Set Shell = CreateObject("Shell.Application")
    Shell.ShellExecute "wscript.exe", """" & WScript.ScriptFullName & """ uac", "", "runas"
    WScript.Quit
loop

Dim wsh
Dim strPath, strName, strFile, strCmd
Set wsh = WScript.CreateObject("WScript.Shell")

'PowerShell ファイル名の作成
strPath = Replace(WScript.ScriptFullName,WScript.ScriptName,"")
strName = WScript.ScriptName
strName=Mid(strName, 1, InStr(strName, ".")) & "ps1"
strFile = strPath & + strName

'ExecutionPolicyの変更
strCmd = "PowerShell -Command ""Set-ExecutionPolicy Bypass"""
wsh.Run strCmd,0,True

'PowerShell スクリプトの実行
strCmd = "cmd /c powershell -file " + strFile
wsh.Run strCmd,0,True

[test1.ps1] 例としてExecutionPolicyの変更を実行させる

Get-ExecutionPolicy
Set-ExecutionPolicy RemoteSigned

 

実行ポリシーの戻し有りバージョン

実行ポリシーを Bypass にしたままというのは気が引けるので、実行ポリシーを変更前の状態に戻す処理を追加した物も記載しておきます。
こちらのほうが、実用的かも…

On Error Resume Next
'管理者権限に設定
Dim WMI, OS, Value, Shell
do while WScript.Arguments.Count = 0 and WScript.Version >= 5.7
    Set WMI = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\.\root\cimv2")
    Set OS = WMI.ExecQuery("SELECT *FROM Win32_OperatingSystem")
    For Each Value in OS
     if left(Value.Version, 3) < 6.0 then exit do
    Next
    Set Shell = CreateObject("Shell.Application")
    Shell.ShellExecute "wscript.exe", """" & WScript.ScriptFullName & """ uac", "", "runas"
    WScript.Quit
loop

Dim wsh, objFSO, objFile
Dim strPath, strName, strFile, strCmd
Set wsh = WScript.CreateObject("WScript.Shell")

'PowerShell ファイル名の作成
strPath = Replace(WScript.ScriptFullName,WScript.ScriptName,"")
strName = WScript.ScriptName
strName=Mid(strName, 1, InStr(strName, ".")) & "ps1"
strFile = strPath & + strName

'実行ポリシーの退避
strCmd = "PowerShell -Command ""Get-ExecutionPolicy | Out-File -encoding default -filepath temp.txt"""
wsh.Run strCmd,0,True

'実行ポリシーの変更
strCmd = "PowerShell -Command ""Set-ExecutionPolicy Bypass"""
wsh.Run strCmd,0,True

'スクリプト実行
strCmd = "powershell -file " + strFile
wsh.Run strCmd,0,True

'実行ポリシーの戻し
Set objFSO = WScript.CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("temp.txt")
strCmd = "PowerShell -Command ""Set-ExecutionPolicy " + objFile.ReadLine + """"
wsh.Run strCmd,0,True

'一時ファイル削除
objFSO.DeleteFile "temp.txt", True

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です