0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Windowsでカバーを閉じた際の電源設定を変えるvbs

0
Posted at

現在の設定が「スリープ」であれば「何もしない」に、「何もしない」
であれば「スリープ」にするvbsです。内部ではpowercfgコマンドを使用しています。

Option Explicit

' 管理者昇格
If WScript.Arguments.Named.Exists("admin") = False Then
    CreateObject("Shell.Application").ShellExecute "wscript.exe", """" & WScript.ScriptFullName & """ /admin", "", "runas", 1
    WScript.Quit
End If

Dim shell, exec, output, targetVal, statusMsg, isSleep
Set shell = CreateObject("WScript.Shell")

' 1. 現在の電源設定を取得
Set exec = shell.Exec("powercfg /q SCHEME_CURRENT SUB_BUTTONS LIDACTION")
output = exec.StdOut.ReadAll

' 2. 「現在の DC 電源設定のインデックス」の行を特定して判定
' "インデックス: 0x00000001" という文字列が現在の値として含まれているかチェック
If InStr(output, "現在の DC 電源設定のインデックス: 0x00000001") > 0 Then
    targetVal = 0 ' スリープ(1) なので 何もしない(0) へ
    statusMsg = "「何もしない」に変更しました。"
Else
    targetVal = 1 ' それ以外(0など) なので スリープ(1) へ
    statusMsg = "「スリープ」に変更しました。"
End If

' 3. 設定の反映 (ここで実行するコマンドを変更することで、シャットダウンなど別のアクションにも変更できます。)
shell.Run "powercfg /setdcvalueindex SCHEME_CURRENT SUB_BUTTONS LIDACTION " & targetVal, 0, True
shell.Run "powercfg /setacvalueindex SCHEME_CURRENT SUB_BUTTONS LIDACTION " & targetVal, 0, True
shell.Run "powercfg /setactive SCHEME_CURRENT", 0, True

MsgBox statusMsg, vbInformation, "電源設定の切り替え"

もし動作しない場合は、powercfg /q SCHEME_CURRENT SUB_BUTTONS LIDACTIONコマンドを実行し、使用されている文字列でのInStr (文字列検索) に置き換えてください。
以下の例では検索単語は現在の DC 電源設定のインデックス: 0x00000000になります。

C:\Users\xxxxxxxxxx>powercfg /q SCHEME_CURRENT SUB_BUTTONS LIDACTION
      ~省略~
      利用可能な設定のインデックス: 000
      利用可能な設定のフレンドリ名: 何もしない
      利用可能な設定のインデックス: 001
      利用可能な設定のフレンドリ名: スリープ
      利用可能な設定のインデックス: 002
      利用可能な設定のフレンドリ名: 休止状態
      利用可能な設定のインデックス: 003
      利用可能な設定のフレンドリ名: シャットダウン
    現在の AC 電源設定のインデックス: 0x00000001
    現在の DC 電源設定のインデックス: 0x00000001

image.png
ちゃんと変わっていることが確認できます。

なお、vbsは2027年に無効化~廃止が決定しています。PowerShellやbatファイルにして実行することをおすすめします。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?