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.
ReTweet this Tip!
There are sudo modules that have been in the MS PowerShellGallery for a very long time.
Find-Module -Name '*sudo*'
Version Name Repository Description ------- ---- ---------- ----------- 2.1.0 Sudo PSGallery Use functionality similar to sudo in PowerShell. GitHub: https://github.com/pld...1.4.0 PSSudo PSGallery Function for executing programs with adminstrative privileges 1.0.2 PwrSudo PSGallery Implements Unix/sudo (Execute-Elevated) for powershell 2.0.1 PS-Sudoku PSGallery Recursive Sudoku solver written in PowerShell. This module can also generate so...0.0.2 PSudo PSGallery run PowerShell Scripts as sudo on Linux/MacOS