Open1

windows管理者権限でのバッチ実行

yunayuna

chatGPTのメモ

You

windowsで、一連の初期処理をバッチ化して実行したいと考えています。
その中には、管理者権限が必要な処理や、webサイトからファイルをダウンロードするものもあります。具体的に、どのような方法で実現可能でしょうか。

chatGPT

Windowsでは、バッチファイル(.batや.cmd)を使用することで、一連のコマンドを自動化できます。この方法では、一度に複数のコマンドを実行することができます。

  1. 管理者権限での実行: 管理者権限でバッチファイルを実行するには、以下のコードをバッチファイルの先頭に記述します。

    @echo off
    :: BatchGotAdmin
    :-------------------------------------
    REM --> Check for permissions
    >nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
    
    REM --> If error flag set, we do not have admin.
    if '%errorlevel%' NEQ '0' (
        echo Requesting administrative privileges...
        goto UACPrompt
    ) else ( goto gotAdmin )
    
    :UACPrompt
        echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
        echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"
    
        "%temp%\getadmin.vbs"
        exit /B
    
    :gotAdmin
        if exist "%temp%\getadmin.vbs" ( del "%temp%\getadmin.vbs" )
        pushd "%CD%"
        CD /D "%~dp0"
    :--------------------------------------
    
  2. Webサイトからのファイルダウンロード: Webサイトからファイルをダウンロードするには、bitsadminpowershellのコマンドを使用します。

    bitsadminを使用する例:

    bitsadmin /transfer "JobName" http://example.com/file C:\path\to\save\file
    

    powershellを使用する例:

    powershell.exe -Command "& { iwr http://example.com/file -OutFile C:\path\to\save\file }"
    

You

ありがとう。管理者権限での実行のサンプルコードは、ps1ですか?それとも.cmdファイルですか?

chatGPT

上記の管理者権限での実行のサンプルコードは、バッチファイル(.batまたは.cmd)用のものです。WindowsのPowerShellスクリプト(.ps1)でも同様のことは可能ですが、コードは少々異なります。

具体的には、PowerShellスクリプトで管理者権限を要求する場合、以下のようなコードを使用することが一般的です。

# Get the ID and security principal of the current user account
$myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
$myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)

# Get the security principal for the Administrator role
$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator

# Check to see if we are currently running "as Administrator"
if ($myWindowsPrincipal.IsInRole($adminRole))
{
   # We are running "as Administrator" - so change the title and background color to indicate this
   $Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)"
   $Host.UI.RawUI.BackgroundColor = "DarkBlue"
   clear-host
}
else
{
   # We are not running "as Administrator" - so relaunch as administrator
   
   # Create a new process object that starts PowerShell
   $newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";
   
   # Specify the current script path and name as a parameter
   $newProcess.Arguments = $myInvocation.MyCommand.Definition;
   
   # Indicate that the process should be elevated
   $newProcess.Verb = "runas";
   
   # Start the new process
   [System.Diagnostics.Process]::Start($newProcess);
   
   # Exit from the current, unelevated, process
   exit
}

# Run your code that needs to be elevated here

このスクリプトは、現在のスクリプトが管理者権限で実行されているか確認し、そうでない場合は管理者権限で再実行します。このコードをスクリプトの冒頭に追加すれば、そのスクリプトは管理者権限で実行されます。