Creating sudo for PowerShell (Part 2)

by May 30, 2022

In our effort to create a sudo command for PowerShell – to elevate individual commands – in part 1 we created the sudo function body:

function sudo 
{
    param
    (
        [Parameter(Mandatory)]
        [string]
        $FilePath,

        [Parameter(ValueFromRemainingArguments)]
        [string[]]
        $ArgumentList

    )

    $PSBoundParameters
}

Now let’s replace $PSBoundParameters with the actual logic to run commands elevated. Start-Process can do the trick. This for example launches notepad elevated under the user “Tobias”:

 
PS> Start-Process -FilePath notepad -ArgumentList $env:windirsystem32driversetchosts -Verb runas  
 

Coincidentally, the parameter names of our sudo function body match the parameter names required by Start-Process, so implementation is simple: use splatting, and pass the user-supplied arguments found in the automatically defined hash table $PSBoundParameters to Start-Process – that’s all:

function sudo 
{
    param
    (
        [Parameter(Mandatory)]
        [string]
        $FilePath,

        [Parameter(ValueFromRemainingArguments)]
        [string[]]
        $ArgumentList

    )

    Start-Process @PSBoundParameters -Verb Runas
}

Run the code, and then test-drive your new sudo command. It turns out to work well, you can now run individual commands elevated from within a script. At the same time, you’ll experience the primary design difference in Windows: all commands launched with elevated privileges run in their own window, and there is no way to redirect results from elevated commands back to your PowerShell.

While our sudo command may be useful to invoke elevated actions, it is of limited use when you want to get back information from elevated commands. Windows architecture prohibits this.

You did learn though how to create function parameters like “ArgumentList” that accept a variable number of arguments.


Twitter This Tip! ReTweet this Tip!