Scripting “sudo” with PowerShell

Now that I finally have some time on my hands to get a little into Microsoft PowerShell again I decided to work on small things to remember what I learned once (aeons ago 😉 ).

And guess what, there was a practical command I always lack on Windows, it’s the great sudo command from the Unix/Linux world. It basically starts a program with elevated rights (just the rough idea).

Because doing it yourself is fine but looking how other people do it is just as nice I decided to consult Google and found Peter Provost’s great post for a PowerShell script that does exactly what I wanted.

The script launches a new process with elevated rights, only one thing was bugging me a little (yeah, I’m nitpicking now!): I had to provide the full path to the executable. Gee-wiz, how dare you!

Easy to fix with the addition of a few lines of code:

if([System.IO.File]::Exists("$(get-location)\$file"))
{
$file = "$(Get-Location)\$file";
}

Now I can just type i.e. “sudo MyApp.exe” or “sudo MyDir\MyApp.exe” when the application is in that very directory and it launches.

I really enjoy myself working with PowerShell again. Personally I think it’s a shame this great piece of software isn’t a default part of Windows Server 2008 just because it’s .net based (yes, that’s the reason, you can’t install .net on Server Core setups without kinks)…

Published by

tsukasa

The fool's herald.

3 thoughts on “Scripting “sudo” with PowerShell”

  1. Unfortunately this does not help with starting and stopping services, which is really what I want administrative rights to do. But thanks for the tips.

  2. Heya David,

    you can easily achieve that by simply starting the “net” tool with the proper arguments using the “runas” verb.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.