sudo for Windows

Discussion in 'Scripting' started by rpo, Jan 21, 2025.

  1. rpo

    rpo MDL Expert

    Jan 3, 2010
    1,484
    1,486
    60
    sudo is a Unix-like new feature in Windows 24H2 to get admin privileges. For more information go to Sudo for Windows | Microsoft Learn
    To execute a cmd script as admin, add the following statement at the top of your script :
    Code:
    @reg query HKU\S-1-5-19 >nul 2>nul||(sudo "%~f0"&exit)
    Example :
    Code:
    @reg query HKU\S-1-5-19 >nul 2>nul||(sudo "%~f0"&exit)
    @ECHO off
    echo Got Admin. Hit any key to execute powershell commands...&pause >nul
    set c=Set-Location '%~dp0';
    set c=%c%$host.ui.rawui.BackgroundColor = ""Blue"";
    set c=%c%$host.ui.rawui.ForegroundColor = 'White';
    set c=%c%Clear-Host;
    set c=%c%If(([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] ""Administrator""))
    set c=%c%{""`r`nWe are executing powershell with admin privileges`r`n""}
    pwsh -c "%c%;dir"
    echo Hit any key to exit&pause >nul&exit
    Following is an other way of doing hybrid batch + powershell scripts + elevation:
    Code:
    <# : standard way of doing hybrid batch + powershell scripts + elevation
    @set c=Set-Location '%~dp0';iex((Get-Content('%~nx0') -Raw))
    @reg query HKU\S-1-5-19 >nul 2>nul||(@sudo pwsh -c "%c%"&exit)
    #>
    # Powershell statements following
    #
    $host.ui.rawui.BackgroundColor = "Blue"
    $host.ui.rawui.ForegroundColor = "White"
    Clear-Host
    If(([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
    {"`r`nWe are executing powershell with admin privileges`r`n"}
    dir #$pwd
    Write-Host "Hit any key to exit" -NoNewLine
    [void][Console]::ReadKey("NoEcho,IncludeKeyDown")
    [Environment]::Exit(1)
    In a terminal session, if you need admin privilege to execute a statement, for example dism, enter :
    Code:
    sudo dism ...
    or :
    Code:
    sudo pwsh/powershell
    to execute powershell statements.

    If you want to switch to admin, enter :
    Code:
    sudo cmd
     
  2. Carlos Detweiller

    Carlos Detweiller Emperor of Ice-Cream

    Dec 21, 2012
    6,801
    7,771
    210
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...
  3. pm67310

    pm67310 MDL Guru

    Sep 6, 2011
    3,425
    2,607
    120
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...
  4. Carlos Detweiller

    Carlos Detweiller Emperor of Ice-Cream

    Dec 21, 2012
    6,801
    7,771
    210
    Interesting.
     
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...
  5. ohenry

    ohenry MDL Senior Member

    Aug 10, 2009
    439
    272
    10