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 { param ( [Parameter(Mandatory)] [string] $FilePath, [Parameter(ValueFromRemainingArguments)] [string[]] $ArgumentList ) $PSBoundParameters }
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 127.0.0.1 -n 1 Key Value --- ----- FilePath ping ArgumentList {127.0.0.1, -n, 1}
Now that the sudo function body works, in part 2 we look at the actual implantation of running commands elevated.