Creating sudo for PowerShell (Part 1)

by May 26, 2022

In Linux shells, there’s a command called “sudo” that lets you run a command with elevated privileges. In PowerShell, you’d have to open a completely new shell with elevated privileges.

Let’s try and add a sudo command to PowerShell. We want a new command called ‘sudo’, and it should require at least a command name, but then also a variable number of white-space separated arguments. Here is how you define such a function:

function sudo 



The param() block defines the input parameters. $FilePath is mandatory (required). $Arguments is optional but decorated with the attribute ValueFromRemainingArguments, so it is a so-called “parameter array” and takes any input parameter that is “left over” and not assigned to any other parameter.

Run the code, then try a few use cases. $PSBoundParameters shows how the function receives your input parameters:

Here’s what I tested, and it seems to work as expected:

PS> sudo notepad c:test 

Key          Value    
---          -----    
FilePath     notepad  
ArgumentList {c:test}

PS> sudo ping -n 1 

Key          Value             
---          -----             
FilePath     ping              
ArgumentList {, -n, 1}

Now that the sudo function body works, in part 2 we look at the actual implantation of running commands elevated.

Twitter This Tip! ReTweet this Tip!