Windowsのバッチで管理者権限を得て実行してみる

管理者が一般ユーザに配るバッチなどで、管理者権限で何かをさせたい時ってありますよね。

そんな時に使えるTipsです。

サンプルプログラムを載せておきますので、適当に変更してお使い下さい。

@echo off
TITLE 管理者権限を得て実行するのテスト
REM
REM  --> パーミッション確認
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"

REM  --> エラーだったら非管理者
if '%errorlevel%' NEQ '0' (
  echo 非管理者なので昇格してから再試行します
  goto UACPrompt
  ) else (
  echo 管理者なのでこのまま続行します
  goto gotAdmin )

:UACPrompt
  echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
  set params = %*:"="
  echo UAC.ShellExecute "cmd.exe", "/c %~s0 %params%", "", "runas", 0 >> "%temp%\getadmin.vbs"

  "%temp%\getadmin.vbs"
  del "%temp%\getadmin.vbs"
  exit /B

:gotAdmin
"%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system" >> "%temp%\getadminresult.txt"

以上です。

 

This website stores cookies on your computer. These cookies are used to provide a more personalized experience and to track your whereabouts around our website in compliance with the European General Data Protection Regulation. If you decide to to opt-out of any future tracking, a cookie will be setup in your browser to remember this choice for one year.

Accept or Deny