Thursday, January 15, 2015

Powershell scripting - a beginner's lesson

Intro:


Ever enjoy shell scripting in Unix and wonder if Microsoft ever implemented such a device?  yes they did!  Windows has offered it since Server 2k3 and it comes standard with Windows 7 and newer OSes offered up to us.

Some coding:


Lets create an easy-cheesy sample script you can run on your local to see a few (very few) features available.  We could use the classic Hello World, but for my purposes I'll go a little bit l33t for my script sample.

The easiest way to create a script is to fire up the text editor of your choice and get to scripting.  You can create comments in your script (quite useful for pseudo-coding what you want to do) via the pound sign (#).

The simplest script command that exists is called write-host.  For those of you old school enough to remember the greatness of echo in dos command line batch files this is an equivalent.

The following is a quick script I created called test.ps1:
# test.ps1
# here's a comment
write-host
write-host 'scripting roxors!'
write-host 'fridays roxor!!'
# end of script

After you've saved your script you'll want to see what happens.  Open up Windows Powershell via Accessories | Windows Powershell | Windows Powershell and navigate to your script.  To execute it: type .\test.ps1 (or whatever you named it) and hit enter.  Most users will receive an error like the following:


The quick solution to the problem in front of you: User rights!  There are 4 options available for execution rights: Restricted (the default), AllSigned (only scripts by trusted publishers are executable), RemoteSigned (downloaded scripts have to be signed by a trusted publisher to be executable) and Unrestricted (no restrictions, no security however).

TEMPORARILY change the security of your scripts by the following command: Set-ExecutionPolicy Unrestricted.  Now run your script, you should see the following output:

Huzzah!  Don't forget to put your security settings back via the command: Set-ExecutionPolicy Restricted.  Hey, at least the commands aren't case sensitive :)

Tune in next week where I talk about some real commands available that can be scripted along with signing your script so security settings aren't as much of a hassle.

Resources:


powershell rights

No comments:

Post a Comment