Wednesday 27 January 2010

PS1 – the scripting side of Powershell

OK… Powershell effectively has two ways of being used.  You can type straight onto the command line or you can script.  This is similar to your traditional command prompt (cmd) where you could open cmd and type your command you want or you can open notepad and write your command into a .bat script file.  I have given a few commands in previous posts  but I haven’t explained how to make an actual script yet, or even what a script is.

If you have been working with computers for a while (especially if your in an admin/tech person role) you will have come across .bat, .vbs, .kix or possibly Perl or Java script files.  Good new for everyone is that we can say bye bye to them and say hello to the .ps1 file.

Something to be aware of before trying to run a .ps1 file in powershell is that you will need to sign your script or make sure that powershell has it’s execution policy set to remote signed.  To check what your current execution policy is set to, in powershell console type: get-executionpolicy .  To view available options type get-help set-executionpolicy and that will give you more details on this.  If you don’t want to open up your script execution policy then your can sign your scripts, I won’t go into that on this blog as I haven’t done this yet, when I do give it a go (sometime soon) I will blog how to do it (or how I did it – hopefully that should be like how you are meant to do it?).

Anyway I have waffled around the subject of this post for long enough so I will get straight onto it. 

You can make a .ps1 file in many ways, the most basic way being opening notepad, writing some Powershell commands, and saving with the extension .ps1 at the end of the file name.  If you would prefer to have Powershell on tap whilst writing your script then try the Windows Powershell ISE.  This will give you a tabbed scripting window, a Powershell command input console and a shared output window.  This is a useful environment  to script in because it allows you to write and test either sections or the whole of your script from the same window you are working in.  The Powershell command input console also allows you to run get-member and help on anything you are putting into your script.

Now we know what the script is when should we write one and for what?

When to write a script seems to be a common question, generally if you are planning to use a command regularly then why not make a script and save wearing out your keyboard?  In my last post I gave the script for a making a powershell logo, it wasn’t very useful but it’s a script and a good example for this post.  Many tutorials you find online will be working with making a script for a task, by starting with the basics you can be ready to work on anything you find online.  You can use a script for many a task, think what you do regularly and think, “Can I script this?”

One last point that I won’t really go into on this post (big topic so needs it’s own but it ties in with this) is your profile.  Your profile is something that loads when you open up powershell, you can set lots of useful stuff in there and it’s editable by you.  I currently have a very basic profile which I have set to change my default directory, load my powershell logo script (it calls in a ps1 file to do that) then clears my screen ready for use.  It’s not much but it’s all I need so far.  As I head off onto a future post I will steer back to the current one but pointing out that your profile is basically a ps1 file that loads when powershell loads.

At this point I think we now a bit about scripts and I’ll hopefully be guiding you through more of what to do with them in up coming posts so check back again and thanks for reading.

Dave.

Tuesday 19 January 2010

A Cool but pointless script

Ok, Powershell may be the best thing to happen to windows (and other) administrators since the slicing of bread… or more likely since the mmc console.  But for everything useful you can find a completely pointless task for fun… this is what I have be spending a few hours doing recently.

I had seen some ones script to make a Powershell Christmas tree about a month back and thought that was quite cool, then having started this blog I created a twitter account to go along side.  I was happy with the little bird type icon that you get as a default Profile Picture but my wife told me I had to do something more interesting.  I didn’t want to have the standard Powershell picture that most Powershell tweeters use so I thought I could do one in the same style as the Christmas tree I had seen before.  Not knowing where to start I searched for the code of the Christmas Tree (can be found here: http://dnn.itprotoronto.ca/Blogs/tabid/62/EntryId/80/Powershell-Christmas-Tree-ndash-Again.aspx ) and I got to editing.  What I ended up with was great in a massively geeky way to the point I had to show it off.  having shown it to my wife and in-laws where better to next show it off than here.  I will attach the script in a quote below this paragraph and also show off the screen shot.

clear-host
write-host

$Rows = 15
$Slash = 1
    $oldpos = $host.ui.RawUI.CursorPosition

# > sign

    Foreach ($r in ($Slash ..2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14)){
        write-host $("   " * $r) -NoNewline
        1..((($rows +$r) * 0)+1) | %{
                write-Host " ***" -ForegroundColor White  -nonewline
       }
        write-host ""
    }        
    Foreach ($r in ($rows..2)){
        write-host $("   " * $r) -NoNewline
        1..((($rows -$r) * 0)+3) | %{ 
                write-Host "*" -ForegroundColor White  -nonewline
       }
        write-host ""
    }          

    # Underscore

    write-host $("{0}*************************" -f (' ' * ($Rows +10) ))  -ForegroundColor White
    write-host $("{0}*************************" -f (' ' * ($Rows +10) ))  -ForegroundColor White
    $host.ui.RawUI.CursorPosition = $oldpos
    sleep .05

I have to say it’s not the cleanest of scripts possible but it’s a good start.Powershell Logo This blog post has overtaken my last post for what will be published first as I am still writing my other one which is about the PS1 file that is for Powershell scripts but it will be ready soon.   Now you may wonder if this may ever be of use at all but I have a use for it already (besides my profile picture on twitter).  Something else I will cover in the near future is your profile.  In brief your profile is a script that runs when you open Powershell, it is customisable and so as I could I customised it.  I have my profile set so it changes directory to where my scripts live, runs this script to make the logo, then clears the screen again.  It’s not of much use but it’s fun and make Powershell look like it has a boot screen like that of windows when it boots.

So there you have it.  A very useless script but it has a point – I learned about doing something in Powershell whilst having fun.  I am not alone on making pointless scripts for the sake of it and if it’s something you want to do then check out the Scripting Guys scripting games – an annual event for scripters of all levels to try out making a script to for fill a given requirement.

For now anyway it’s time for bed, so have fun learning Powershell and don’t forget to check back another day for more blogs on learning Powershell.

Sunday 10 January 2010

Working With Txt and Csv files.

One of the most useful things I've see so far from using powershell is the way you can work with external files such as txt or csv files. They can be used to both import data into powershell and output to.

We shall start by looking at importing from a txt file.
As the most basic thing we can do with a txt file just type "get-content " and it will display what is in the file - not much use on it's own but the cool stuff comes next. Try this:

get-wmiobject win32_operatingsystem -computername (get-content c:\computers.txt) | select __server,localdatetime
My "computers.txt" file just contains a list of computers names. This one line of script will come back to you and tell you the name of the computer (__server) and the time and date on that computer (localdatetime). That's just 2 of many options you can select. Try

get-wmiobject win32_operatingsystem | get-member
"Get-wmiobject -list" will give you a list of all wmiobject classes available. Your most likely to start looking at win32_operatingsystem and win32_bios.
If you are looking for a specific object like one related to bios type "get-wmiobject -list *bios*" and it will list only those objects with bios in the name.
Remember that if you use the -computer (get-content ) then you can pull in the list of computers you wish to audit.

Importing from CSV files:
For starters just type "import-csv ". The import-csv command on it's own will simply dump the file to screen and by default it will show it in a list format. it can also be viewed in a table like how it would apear in excel. Try:


Import-Csv c:\Book1.csv | format-table
This, like the "get-content " command on it's own, isn't much use without extra options to go with it. So how can a csv file be of use?
As a system admin I can make use of csv files as a way of creating users (I will go into detail in a future blog) in Active Directory. Other uses might will also be covered in future posts as examples come up (yes that does mean I can’t think other other uses atm).

Can I only import?
No… a useful cmdlet is “export-csv <path\file.csv>” and “out-file <path\file.txt>” Try:
get-help | out-file c:\pwrshell_help.txt
notepad.exe c:\pwrshell_help.txt

or

get-process | export-csv c:\processes.csv
import-csv C:\processes.csv format-table

You can also import and output to html and xml files.

If you stick with me on this blog then you will see many more examples when I get more in-depth into powershell.

Thanks for reading,
Dave.

First Post of Learn-Powershell

Welcome to my first post on my Powershell Blog. I am currently in the process of learning powershell.

In this first blog I will explain the basics of powershell including how to get it.

How to get Powershell
The First thing to note is at time of writing the current version of powershell is version 2.0 which ships with Windows server 2008 R2 and Windows 7. For other operating systems it is download able as part of the Microsoft Windows Management Framework from http://support.microsoft.com/kb/968929 or by searching the web for "Microsoft Management Framework". If you search for "Powershell 2.0" then you will find the CTP (Pre-Release) version.

What is Powershell?
Powershell is a (fairly) new scripting and command prompt environment for managing windows clients; servers; server functions such as Exchange 2007 and later; SQL Server 2008 and later; and Microsoft's System Center tools such as Virtual Machine Manager. It is also being used by 3rd party companies like VMware in ESX server.

The eventual aim is for administrators to know powershell and then everything can be done through powershell either in the command line or through scripts (*.ps1 files) which are command line inputs but made to run in an automated way to save typing and allow for scheduling. (If you are used to scripting using *.BAT files then you will understand the similarity with the powershell command line and how to script for it as its similar to that of the relationship between the classic windows command prompt and batch files.)

Where do I start?
  • First place to start is by installing it and get a shortcut to it somewhere accessible - you will want to spend lots of time using it. The best way to start to know what powershell can do is to use it. From now on if you want to use command prompt, don't, open powershell. All you want to do in command prompt is abalible from powershell and generally with the same command names as an alias of the powershell name. (ie. Set-Location uses the more familiar cd or chdir command found in windows and Linux).
  • Once you are started using powershell for your basic day-to-day tasks like ipconfig, file management, etc. you can work your way onto the new powershell commands. These are always formatted in verb-noun. A couple to get you started are Get-Command and Get-Help. A useful feature of V2 is tab completion, start writing a command, hit tab until you find the one you want, if you overshoot then shift + tab will take you back up. Try typing get-comm and hitting tab - it will give you the get-command option. The more you give it the more refined the ablible commands you tab through will be. To find out the availible verbs just type verb.
  • Now you have the hang of using powershell as a replacement for command prompt then you can try writing scripts. There are many ways you can write and edit scripts. You can use your basic text editor such as Notepad.exe or a more scripting focused text editor like notepad++. Personally I am finding the Windows Powershell ISE (Intergrated Scripting Environment) very useful as you can select sections of text and run that or run the whole thing from the one window and imidiately see the output. There are lots of ISE's avalible but this is a good one to start on as it's free and downloads with PowershellV2.
  • To allow scripts to run after you first install you'll be required to input the command "Set-ExecutionPolicy" hit enter and it will ask you to supply the value: The recommended option is "RemoteSigned". To read more on this option type "help Set-ExecutionPolicy".
  • The final getting started tip for this blog is Get-Member. Get-Member will help you know what you want to use in your command. To use it simply type the command you want to use and follow it with the pipe symbol ( | found above the \ key)and get-command like this: "Import-Csv | Get-Member" will tell your what methods are avalible and what NoteProperties (field Names) are ablible for that file.
Where can I find out more?
There are many places to go to find out more of what to do with powershell. I will be continuing this blog as I go through my travels of learning powershell and hopefully pass something useful on like this.
Other places I would recommend to go include:
For now I hope I've got you started ok.
Thanks for reading this blog and hope you enjoy learning powershell.