Dec 1, 2022

Simulate Linux's SUDO in PowerShell

To start a notepad.exe process as normal user:

c:\> notepad.exe

To start a notepad.exe process as normal user with PowerShell:

PS> Start-Process notepad


To open a file as Administrator with PowerShell:

Start-Process 'notepad' -Verb runAs -ArgumentList c:\windows\system32\drivers\etc\hosts


To simulate 'sudo' with PowerShell Cmdlet

-----------8<------------------

function sudo
{
  if ($args.Count -gt 0)
  {
    $lastIndex = $args.Count-1
    $programName = $args[0]
    if ($args.Count -gt 1)
    {
      $programArgs = $args[1 .. $lastIndex]
    }
    Start-Process $programName -Verb runAs -ArgumentList $programArgs
  }
  else
  {
    if ($env:WT_SESSION) {
      Start-Process "wt.exe" -Verb runAs
    }
    elseif ($PSVersionTable.PSEdition -eq 'Core')
    {
      Start-Process "$PSHOME\pwsh.exe" -Verb runAs
    }
    elseif ($PSVersionTable.PSEdition -eq 'Desktop')
    {
      Start-Process "$PSHOME\powershell.exe" -Verb runAs
    }
  }
}

Set-Alias -Name su -Value sudo

-----------8<------------------


To use the cmdlet:

PS> sudo notepad c:\windows\system32\drivers\etc\hosts


Links: