Ultimate Scripting Powershell explained · Ultimate!Scripting:!PowerShell!explained! Autumn2011!...
Transcript of Ultimate Scripting Powershell explained · Ultimate!Scripting:!PowerShell!explained! Autumn2011!...
Ultimate Scripting: PowerShell explained Autumn 2011
Technical Seminars – Autumn 2011 © RM Education 2011
1
Introduction From my experience, typically scripting is limited in educational establishments; in depth scripting anyway. We may write occasional batch files, use the command line for one or two tasks and if you’re that way inclined, maybe a vbs script or two. So why would we, the technical seminars, agree to do a session on scripting? There are no two ways about it, scripting is powerful when you know what you are doing. In fact everything we do as administrators involves scripts, we just prefer to use GUIs. A sweeping generalisation I know, but ask most network admins, whether in education or industry and most will say they want nothing to do with scripts. I can completely understand, especially if you’ve ever tried Unix scripting. Chris Day did a few years ago and I remember even he was banging his head off the wall of a morning, afternoon and evening. Why is that? First of all, you have to learn another language. New languages are tough to learn, especially if you have grown up only knowing one. With most new languages you are graced some room for error, we’ve all been there on either end of a broken language conversation and trying to work out what each other are trying to say. Scripting can be extremely frustrating in this light as writing a script,
Ultimate Scripting: PowerShell explained Autumn 2011
Technical Seminars – Autumn 2011 © RM Education 2011
2
taking great care on every grammatical nuance and when you deliver the final output the computer throws up an error like ‘triple panic abort’. This is about as much use as your foreign speaking friend screaming ‘I don’t know what you are saying!’ at you in the language you are struggling to learn. It leaves you confused and often frustrated. Scripting is also time consuming. Learning a few sections of the language is only useful to creating very specific scripts. Like learning ‘le chat est sur la table’ in French lessons, while learning other parts of the language you may be able to point out the cat is in other situations or indeed add a dog to the conversation but it’s not going to help you get by when you’re attempting to find a hospital in an emergency. To learn the art of constructing a script is a lot like this, you need to learn the syntax and then apply all the other bits you pick up while living in that world. Most of us don’t have time to live in that world all the time. Even once you’ve learned the language well enough to get by scripts that do useful things are long pieces of text, that with one error that needs to be found by trawling back through said text. Finally what if you type something that means one thing to you and while it makes sense to the computer it means something entirely different. It is forever the worry of even the experienced scripting professional that they write a script that accidently does something bad. Scripts are massively powerful and getting things wrong can mean very bad things happen, there are no ‘are you sure’ buttons in this world. Once you press enter your career can sometimes hang in the balance. Is that a world we want to live and work in? I certainly don’t. Now I’ve taken the time to put the fear into you about scripting it’s time we took a step back, this session is not about scripting as we know it. This session is about a very powerful tool called Powershell. The purpose of this session is to show you how Powershell is changing the way we use Windows.
Ultimate Scripting: PowerShell explained Autumn 2011
Technical Seminars – Autumn 2011 © RM Education 2011
3
Scripting: basic terminology I am working on the assumption that we are not all scripting experts. In fact I would encourage more people who have historically avoided scripting to view these notes and see the session. What once seemed a very confusing world suddenly seems to make sense with Powershell, which I hope you’ll see over the course of this session. There are some basics we need to cover before moving on, while I’d love to assume everyone understands the terminology, generally people get lost before they’ve even started. As a caveat, I’m only going to be talking about shells here. There are Job Control Languages (JCL) which pre-‐date shells by a decade but were used on mainframes and not designed for interactive computers. Shells started to be used as computers were linked together. Computers talk in binary (1s and 0s), this is very difficult to read and write sufficiently as a human. Shells act as interpretations (like using babel fish to translate languages) for the binary. A shell
Ultimate Scripting: PowerShell explained Autumn 2011
Technical Seminars – Autumn 2011 © RM Education 2011
4
means you can type, typically in English, and the commands are turned into binary, each shell can carry out most of the same tasks.* *This is certainly true for Linux. MS-‐DOS (the original Windows shell) is commonly known, certainly in Unix forums, as a far less powerful shell. The shell communicates with the kernel. The kernel is the core of the operations passing commands and actions between application, hardware and shell. To put it very simply and in a diagram.
I want to say good morning to all my users when they log on...
#!/bin/bash temph=`date | cut -c12-13` dat=`date +"%A %d in %B of %Y (%r)"` if [ $temph -lt 12 ] then mess="Good Morning $LOGNAME, Have nice day!" fi....
1011110100001000100101010100010101001111110010100100100101001.....
Good morning Ken.Thomson, Have a nice
day!
Ultimate Scripting: PowerShell explained Autumn 2011
Technical Seminars – Autumn 2011 © RM Education 2011
5
Different types of scripting We’ve seen the basics of scripting, now we need to look at the shells or languages used. There are various languages that can be used for various different platforms. Each of these languages has advantages and disadvantages, in the eyes of Jeffrey Snover (creator of Powershell) they all had their faults and none quite hit the mark when he started to think about it. There are lots and lots of different languages, have a look here to get an idea of how many. If you’ve ever been immersed in UNIX coding you’ll know about BASH and KSH. These languages were a good standard, introduced in the early 80s they stood the test of time and are still used today. These scripting languages are very powerful and in depth but when it came to solving something you needed to use a program like Perl, Python or Ruby. None of the above shells were designed with the professional in mind though. ‘Production oriented’ as Jeffrey Snover puts it. AS400 CL and VMS DCL were created with professionals in mind and were far more ‘stable’ than the other shells. Jeffrey Snover looked at all of the different types of coding and had a dream. He thought to himself, why can’t we have a language that can do in depth tasks, solve problems and be stable and ‘prodcution oriented’? In fact he thought a lot further than just that. He thought why can’t it just be simple? I’ve often wondered this. The world of coding is shrouded in mystery, at least that’s how it seems from the outside. Why should it be? We are all using ‘English’ aren’t we? That’s exactly where Powershell came from.
Ultimate Scripting: PowerShell explained Autumn 2011
Technical Seminars – Autumn 2011 © RM Education 2011
6
The story of Powershell (and Jeffrey Snover) When Jeffrey Snover talked about Powershell in a recent presentation, he talked about his journey with it. It’s an interesting story of a man who was determined to change the way coding worked. He wanted to create a new shell that could manipulate Windows (with the removal of MS-‐DOS it was needed), so he set about work as a Microsoft architect in 1999. He came up with this idea for a new shell scripting language, Microsoft said it wasn’t that important. He disagreed, so he came to a compromise. Jeffrey took a demotion to concentrate on creating this new language. Five years later they shipped Powershell, he was promoted back to his original position in the company. People had seen its potential and were beginning to get excited about it. A couple of years later version 2.0 was released (the one we’ll look at today) and people were bowled over. Jeffrey got a promotion. This year Microsoft started to talk about Powershell being the core of Microsoft technologies. If you don’t know Powershell in few years time you will be well behind the curve. This will be one of the core Microsoft IT skills, according to Jeffrey: “If you are not cognisant and competent in using Powershell as an IT pro, you are going to be well behind the curve.” This session aims to introduce Powershell to beginners, but that doesn’t mean people experienced with scripting have nothing to learn here. While it’s easy to be envious of Jeffrey’s story of moving
Ultimate Scripting: PowerShell explained Autumn 2011
Technical Seminars – Autumn 2011 © RM Education 2011
7
up and down the Microsoft ladder, when we start to look at what he’s done you will start to realise just how much Powershell has challenged the norm. Powershell vs. VBScript During Jeffrey’s recent presentation at tech-‐ed in Berlin he talked about the ability of Powershell to reduce the amount of script you need to run for situations. I’ve shamelessly taken this information from his slides. It shows the difference between VBS and Powershell in lines of script. The table looks pretty bad in the notes, but I’ve lifted some of the scripting as an example. In VBS you would need to write fifteen lines you now only need to write one in Powershell for example. I have some even more mind-‐blowing examples he talks about in a moment. With all of this the ‘cmdlets’ (which I’ll cover later) make things so much simpler. Here’s an example. Say you are running Exchange 2003 on your network and you wanted to find your mailbox statistics here’s the VBScript you’d have to create “Set listExchange_Mailboxs = GetObject("winmgmts:{impersonationLevel=impersonate}!\\COMPUTERNAME\ROOT\MicrosoftExchangeV2").InstancesOf("Exchange_Mailbox") For Each objExchange_Mailbox in listExchange_Mailboxs WScript.echo "AssocContentCount =” + objExchange_Mailbox.AssocContentCount WScript.echo " DateDiscoveredAbsentInDS =” + objExchange_Mailbox.DateDiscoveredAbsentInDS WScript.echo " DeletedMessageSizeExtended =” + objExchange_Mailbox. DeletedMessageSizeExtended WScript.echo " LastLoggedOnUserAccount =” + objExchange_Mailbox. LastLoggedOnUserAccount WScript.echo " LastLogoffTime =” + objExchange_Mailbox. LastLogoffTime WScript.echo " LastLogonTime =” + objExchange_Mailbox. LastLogonTime WScript.echo " LegacyDN =” + objExchange_Mailbox. LegacyDN WScript.echo " MailboxDisplayName =” + objExchange_Mailbox. MailboxDisplayName WScript.echo " MailboxGUID =” + objExchange_Mailbox. MailboxGUID WScript.echo " ServerName =” + objExchange_Mailbox. ServerName WScript.echo " Size =” + objExchange_Mailbox. Size WScript.echo " StorageGroupName =” + objExchange_Mailbox. StorageGroupName WScript.echo " StorageLimitInfo =” + objExchange_Mailbox. StorageLimitInfo WScript.echo " StoreName =” + objExchange_Mailbox. StoreName WScript.echo " TotalItems =” + objExchange_Mailbox. TotalItems Next”
That’s eighteen lines of script you have to write, hope you’ve got right and then execute. I suspect for a fluent ‘VBScripter’ this doesn’t seem to be too much of a hassle. Write it, test it and save it away for whenever you need it. Jeffrey Snover as we’ve seen asked the question, why? Why do I have to write fifteen lines? On Exchange 2007, as 2003 doesn’t have Powershell installed by default*, here’s how to get exactly the same information. get-‐mailboxstatistics –server $servername
Ultimate Scripting: PowerShell explained Autumn 2011
Technical Seminars – Autumn 2011 © RM Education 2011
8
Two lines of entirely readable text. No catches, just two lines. As I stated, you could show this to pretty much anyone who can read and has only a small clue about IT and they are more than likely going to be able to work out what these lines are doing. *Powershell can be installed on Exchange 2003. Most admins choose to administrate Exchange through a GUI or VBScript. Both of which plug into WMI data, Powershell is extremely efficient at plugging into WMI by using the ‘WMI-‐getobject’ cmdlet or ‘–gwmi’ for short. Fifteen lines to two lines, is that really worth the fanfare I’ve given Powershell? One anecdote described how an admin had reduced a seven hundred and fifty one line VBScript down to just fifteen lines of Powershell. Now that is impressive! That’s a ratio of just over 50:1 VBS lines to Powershell lines. How about collecting WMI info and piping it into a HTML script? In this instance one admin had managed to squeeze a four hundred and eighty line VBScript to a one line Powershell script. That’s 480:1, just in-‐case you were still wondering how and why you haven’t used Powershell for more jobs. So when I say Powershell is changing the world of scripting, I’m not exaggerating. You can see why system administrators world-‐wide have been blown away by this technology (and not just the scripters). Getting to know the shell This could end up being a very dry session with me explaining what each piece of syntax means. I have no intention of writing up tables of script to learn. There are two reasons for this:
1. It would be a horribly dull re-‐invention of the wheel for me to go through when I could redirect you to a website
2. Studies show that knowing the script well isn’t what differentiates between an experienced script writer and an inexperienced script writer, it’s the ability to work around problems
Here we will look at how to use Powershell. There are a lot of features that you may stumble across accidently after learning all the syntax. In this section I’ll show some of the nice little features that will help you get around things that can make your life far easier. Powershell is a command line and scripting language. So you can still run programs from it like you would in the command prompt. Open notepad: ps> notepad Open calculator ps> calc Check IP configuration ps> ipconfig All run exactly the same tasks as you would expect in the command prompt. ps> history
Ultimate Scripting: PowerShell explained Autumn 2011
Technical Seminars – Autumn 2011 © RM Education 2011
9
Of course you could just press F7
Some of you may notice that actually the F7 function is in the command prompt too, history however is not. This is part of the Powershell philosophy. The developers appear to have constantly asked, why not use shortcuts people already know? Why type a whole word or phrase when you can shorten it? Powershell is packed full of these neat features. Typing code can be an arduous task, you have to make sure every character is right and in the right place. While getting characters in wrong places is going to cause problems in Powershell, it’s far easier to find words and phrases. To start with let’s look at some script we may use on a regular basis. Get-‐process for instance, again the syntax is simple and easy to understand. You are asking for the processes on the local computer.
Ultimate Scripting: PowerShell explained Autumn 2011
Technical Seminars – Autumn 2011 © RM Education 2011
10
How about if I want to find a specific process? I need to use ‘get-‐process –name [process-‐name]’ easy to understand and straightforward
With Powershell you don’t necessarily have to type the whole string. This comes into its element when you are doing long tasks at speed. Using the example above ps>get-‐process –name dropbox becomes ps>gps –name dropbox So get-‐process can be shortened to ‘gps’. You can also shorten other parts of the string ps>gps –n dropbox Powershell not only shortens the line count compared to other scripting it also shortens the amount of characters needed.
Ultimate Scripting: PowerShell explained Autumn 2011
Technical Seminars – Autumn 2011 © RM Education 2011
11
For the purpose of ease of understanding I will continue to use full script throughout the notes, this is for ease of reading should you chose to skip this section. Jeffrey Snover talked about how most scripting is either built for interactive use (where you need to do things on the fly) or production use (pre-‐written scripts that run as part of a process). It was often assumed you could have one or the other but never both. Powershell challenges that theory as it can be used effectively in both environments. Interactive scripting requires the script to be written quickly, like command prompts. So the balancing act between these two ends of the scale is a quick and easy language versus a powerful tool underneath. The interactive side of Powershell is easy to see. Say you are looking to stop a process but can’t remember its exact name, you know it starts with a ‘d’ has a ‘p’ in it somewhere but your not sure what it ends with. ps>get-‐process –name d*p*
In fact we can go even further than that and be super pithy
The use of wildcards is not a new thing if you’ve ever scripted in Unix. However the ability to be able to do this in Windows is something of a breakthrough. Powershell is designed with the administrator in mind. Powerful scripting languages are dangerous; if you are able to get in behind the scenes and change things around without being warned you could potentially bring the network to its knees just by hitting return. This is the administrator’s nightmare, writing a script and running it for the first time. If you don’t get it right, you potentially could be in the dog house at work for a long time. That’s if you are invited back. Powershell is designed to be intuitive and powerful at the same time. I’ve been through some of the intuitive stuff, where most of the language is straight forward and you can use various methods to
Ultimate Scripting: PowerShell explained Autumn 2011
Technical Seminars – Autumn 2011 © RM Education 2011
12
find information your brain is having trouble recalling. Using wildcards is one of those options, but wildcards can also be dangerous. So you could find yourself stuck in the middle. If you wanted to stop a load of processes and you need to do it quickly, it’s going to take a long time to type ps>get-‐process –name [process1] | stop-‐process ps>get process –name [process2] | stop-‐process ps>get-‐process –name[process3] | stop-‐process Even abbreviated to aliases this is a slow way of doing things. If you know that all process start with letters between a and m then you can use a wildcard to find them, if you know the range of letters the process end with you can use this too. So a long list of stop process commands becomes
This can actually be abbreviated down to ps>gps [a-‐m]*[b-‐p] | stop-‐process So what was lines of information can be written out in a few characters. When doing this you open yourself up to the danger of the power of Powershell. You’re in a rush though. So in doing this you may kill an important process that you didn’t think of. So maybe it is worth writing out all those lines of code? Wouldn’t it be nice if you could just ask what happens if I do this? What am I going to kill. Well you can, and you do it by typing –whatif
Ultimate Scripting: PowerShell explained Autumn 2011
Technical Seminars – Autumn 2011 © RM Education 2011
13
So I can now see what I’m about to stop. Luckily I didn’t go ahead as I would have killed some of the applications I’m in the middle of using. If I’m in a rush though and need to stop these processes –whatif hasn’t helped it’s just told me I could have made a mistake. Try adding –confirm instead of –whatif
So each command can be checked before stopping any processes. If you are not sure what a process is use s to suspend the current command and check what it is you’re actually looking at. Once suspended you can get the process using it’s id or name and check it using the format-‐list function. ps>get-‐process –id 3488 | format-‐list * This will give you all the detail you need to decide whether it’s a process you want to stop or not. Once you’ve made your decision simply type exit and it takes you back to where you were. Even that is a nice feature that means you don’t need to redo all the work you’ve already done. Generally stopping processes isn’t done by name, you’d do it by the ones that are using too much resource. If we look at the output of ps>get-‐process we’ll see the different variables we can look for within get-‐process
Ultimate Scripting: PowerShell explained Autumn 2011
Technical Seminars – Autumn 2011 © RM Education 2011
14
Ultimate Scripting: PowerShell explained Autumn 2011
Technical Seminars – Autumn 2011 © RM Education 2011
15
We can get process where they are greater than in a certain variable. For instance
Most of this syntax should make sense.
• Get-‐process = get process • Where-‐object = where the object is... • {$_.workingset = target object (this can be abbreviated to $_.ws in this case • -‐gt = if after the cmdlet where-‐object means ‘greater than’ • 5Mb = 5 megabytes
Ultimate Scripting: PowerShell explained Autumn 2011
Technical Seminars – Autumn 2011 © RM Education 2011
16
Powershell is simple to understand and easy to use. You may have noticed that you don’t need to be an amazing mathematician to work out what you are looking for. 5Mb is written 5mb not...er...5242880 bytes. I had to check that. I checked it in Powershell.
Originally the Powershell developers thought they would use Unix tools, Awk, Grep and Sed. These utilities are well known by Unix administrators. Awk is a utility used for creating reports on Unix systems, Grep is a search functionality and Sed is a utility that parses text. These three utilities are the base of many languages these days. They each have a weakness Awk doesn’t work in the registry, Grep doesn’t work with WMI and Sed isn’t able to work with Active Directory. This means that using Windows systems based on these tools lacks power. Using cmd in Windows we can see what drives there are with the command fsutil fdisk drives this will return your drive letters. With Powershell you need to use ps>Get-‐PSDrive
You’ll note this cmdlet returns more than your C and D drives but also includes the registry. Which means you can access the registry from a script. Don’t forget, with great power comes great responsibility.
Ultimate Scripting: PowerShell explained Autumn 2011
Technical Seminars – Autumn 2011 © RM Education 2011
17
Powershell| get-‐help Towards the end of the last section you may have found yourself thinking, this is a new language and no-‐where near as easy to learn as I’d made out. There are a certain amount of commands you need to learn, there are even more out there. So what if you forget? Powershell also has powerful help menus and options. This means even if you are under pressure it’s possible to find the cmdlet you’re looking for without having to search the net. While in the middle of writing out a line if you get stuck with a cmdlet you can use tab to cycle through the possible options. We all have mind blanks and it’s reassuring to know that a script can be used jog the memory. So for instance you can cycle through the get-‐ cmdlet to find get-‐acl, get-‐alias, get-‐authenticodesignature, get-‐childitem, get-‐command, get-‐computerrestorepoint and so on. This is a long list of cmdlets so if you know what the cmdlet starts with it makes life a lot easier. If your memory serves you well enough you’ll know it when you see it, but what if you’re not sure? Well you can use ps>get-‐help [cmdlet] to double check it is what you were thinking. This will bring up a short explanation, the syntax you would use with it and a longer description. What’s really interesting is the related links, this points you to other related cmdlets and a web page. The web page is the most up to date information available about Powershell. The communities that are available on Powershell give this scripting language a massive advantage as new scripts are created on a daily basis it’s well worth checking you aren’t reinventing the wheel. At the bottom of the return here you’ll see a ‘REMARKS’ section. This shows three other options for getting more info on the cmdlets you’re looking into. By adding –examples you’ll get examples of how to use the cmdlet, it returns commonly used syntax for the cmdlet. Using –detailed gives a fuller picture of the cmdlet and –full gives detailed technical information about the process. So if you are ever in doubt, there really is no excuse for just hitting enter to see what happens. Knowing the language to certain extent is probably all you can hope for, even the experts need to use the tabbing scroll method and will use get-‐help too. A study carried out showed the difference between beginner Unix code engineers and experienced code engineers wasn’t hugely noticeable in a written exam, once you have a basic grasp of the language written exams won’t separate you from the top or bottom. When a practical exam was given, the difference was noticeable. Why? Because experienced coders know how to get around issues and work with the code to get to where they want to go. Learning the language is the beginning, learning how and where to ask for help is the key to successful scripting.
Ultimate Scripting: PowerShell explained Autumn 2011
Technical Seminars – Autumn 2011 © RM Education 2011
18
Objects, collections and cmdlets So far I have talked about the language in the words that are typed. A lot of this involves talk of objects and cmdlets. This is often where people get stumped; if this were a four year degree this would be a year of it. So I am not going to promise you will know the subject inside out after this section, but you should have a better understanding. I’ve certainly switched off when trying to learn other languages because the teacher or author has flown into using words and phrases with no explanation. Here we will cover the three big words that get thrown around and what they actually mean. While it seems back to front to go through this now, it actually makes sense. If you don’t have working examples to work from it’s very difficult to understand what they are. For this example I am going to use computer games, specifically ‘FIFA’ (any after about 2001) and ‘Grand Theft Auto: San Andreas’, as an analogy. All will become clear in a moment. Objects (Properties and Methods) I’ve discussed this with some of our guys in development who have learned this in detail. We looked at ways of describing objects. Jeffrey Snover used a bicycle as an analogy; this troubled my understanding of objects. Then we started talking about a person as an object. A person has parts, these can be age, height, eye colour, weight, build, skin tone and fitness level for instance. Each of these parts can be interacted with. You can become taller, older and heavier (unfortunately), so each attribute has a how to use section. This may not seem to make sense entirely yet. As it doesn’t explain which bit the object is or really what an object is. I have to admit something rather sad about myself here, I rarely play online games or two player. I tend to play games where I can make my own characters. FIFA for instance (I currently still play 07 on my PS2) I set up a team of my old team mates. Here I was (without thinking about the code) directly editing objects. So what are the objects? In FIFA the first object I’m editing is the team. Part
• Name • Kit-‐Style • Kit-‐Colours • Players • Stadium-‐Type
How to use • Edit() • Choose() • Add • Remove
Ultimate Scripting: PowerShell explained Autumn 2011
Technical Seminars – Autumn 2011 © RM Education 2011
19
I can edit the team name (Milton United is my usual choice), Kit-‐style and colours. I can choose a stadium type and add or remove players As I mentioned I don’t just add or remove players (I do tend to throw in some superstars) I also edit players. Players are objects with the team object and as the team have parts and how to use them so do players. Parts
• Name • Age • Hair colour • Eye colour • Skill • Position
How to use • Edit() • Set() • Increase() • Choose()
You might ‘edit-‐name...’ and then ‘choose-‐haircolour...’ if this was all using Powershell. Skill could be another object within that with speed, reactions and ball-‐control as parts; increase and decrease could be the how to use. In programming these are referred to as properties (parts) and methods (how to use). All of these abilities to configure objects in computer games It can become quite complex and this is where the Gran Theft Auto: San Andreas analogy comes in useful. Changes to objects happen on the fly in this game. You don’t immediately have the ability to change anything about the main object at first (the main object being the character you are playing as). You need to gain levels of properties to be able to use methods for other properties, changes to other properties will cause chain changes. If you’ve played the game this makes sense, if you haven’t here’s what I’ve just explained. Properties
• Cash • Hairstyle • Clothes() • Weapons() • Health • Build
Method
• Spend • Change() • Use() • Earn() • Eat • Increase()
In the game you control everything your character does from eating to haircuts to going to the gym. To be able to do things like eating you have to have enough cash, therefore these properties rely on each other. If you eat too much and don’t exercise enough you get fat, if you exercise a lot you
Ultimate Scripting: PowerShell explained Autumn 2011
Technical Seminars – Autumn 2011 © RM Education 2011
20
become very muscular. Once you’ve mastered keeping your character alive through eating and exercising you may choose to go and buy a weapon. This is now an object interacting with an object because the gun has properties of its own. This would include number of bullets for instance. Now we get into objects interacting with other objects. This is as far as I need to go in this session explaining objects and how they work, otherwise this may extend for a year. Collections A collection can be a list or array (these are terms you may hear) for instance. These are objects that are grouped together. In the get-‐process cmdlet the processes are individual objects, the list it produces is a collection of objects. You can call out individual objects by using squared brackets [] For example looking at the get-‐process cmdlet we can call up all the processes. But what if you only want to look at one of those, you can use –id or –name but you can also use the [] to call the process. Remember counting starts from 0 so if you want the 4th process you need to use [3] at the end of the command.
As you can see below, task manager shows this as the 4th process when arranged by ‘Image Name’. This is the default arrangement for Powershell. We can change this if we wish, we’ll have a look at that in a moment.
Ultimate Scripting: PowerShell explained Autumn 2011
Technical Seminars – Autumn 2011 © RM Education 2011
21
Cmdlets You would be forgiven for thinking this is too good to be true. There is no way that these simple commands can work with so little text. If it was that simple to make code then someone would have noticed it a long time ago. You’d be right, Powershell is run mainly by cmdlets, these are like shorthand for long pieces of code. You can write your own cmdlets. Jeffrey Snover is the creator of PowerShell, Lee Holmes is the guy that has written in great detail about it. I’d recommend getting a copy of Windows PowerShell Cookbook, within this meaty manual there is a section writing cmdlets. To go into how to create cmdlets here would be taking a huge leap. What Lee has to say about creating cmdlets is “[cmdlets] are incredibly easy to write when compared to the amount of power they provide” If you’ve been tinkering with VBScript or other languages you may want to try your hand at creating cmdlets. There is a huge community of admins already doing so, and that community is growing.
Scripting I’ve talked a lot about scripting in this paper so far but haven’t actually shown any scripts, not as you would expect to see them. The fact is anything you can type into PowerShell directly you can put into a PS1 script and run (this works the other way round too). So much of what we’ve looked at so far is relevant to scripting but perhaps getting processes isn’t something you’d want to script I suspect. What if you want to find a list of users? Stop and start services? This can all be done through the command line, but if it’s something you need to do again and again why not write a script. With PowerShell you can write scripts that have a level of intelligence. You can program them to stop services in order (no big deal) but also wait until the previous task has finished and also make sure the service is disabled so that it doesn’t accidentally start up again for some reason. Doing this through running a script ensures you are not only able to stop the right services in the right order at the click of a button but it also mean consistency. If someone in the know isn’t there they won’t have to click through stopping services while following a process document. There are some things we would recommend for creating scripts though. Make sure there are comments on the script, we use a set process for scripting comments which we’ll look at. It means that anyone who is involved in creating a script can pick up yours and understand what you’ve done. Another part is testing; make sure you test any scripts before unleashing them on the network. This can be done on a virtualised test network or a test PC if it’s a script for a computer. Finally you’ll need to make sure that you have enabled scripts to run on the computers you are using. By default scripts won’t be able to run (a useful feature).
Ultimate Scripting: PowerShell explained Autumn 2011
Technical Seminars – Autumn 2011 © RM Education 2011
22
Enabling scripts When you try to run a script you’ll get a return of some red text – as shown below.
The text is straight forward and explains why there’s a problem and how to work around it. I’ll pick out the two parts that are helpful here. “...[file path\file] can not be loaded because the execution of scripts is disabled on this system. Please see “get-‐help about_signing” for more details.” Not only does it mention the scripts are not allowed to be run but tells you where to look for more information. Try running the command ‘get-‐help about_signing’, it is a long stream of information. Here’s a tip use ‘get-‐help about_singing | more’. This will give you a one page at a time view. To see page by page press the spacebar or you can use the return button to view line by line. This makes reading reams of information far easier.
Ultimate Scripting: PowerShell explained Autumn 2011
Technical Seminars – Autumn 2011 © RM Education 2011
23
Summary I’ve kept these notes short and sweet, I find scripting manuals can deter you from learning how to use the script. I want this session to encourage you to play with the features that are bundled up in PowerShell, after all that is the best way to learn. All the tips and tricks I’ve been through can help you get started with PowerShell and to start understanding the world of scripting. Remember, this is and will continue to be the core to Microsoft Technologies. It is well worth spending some time getting to grips with. Don’t forget, get-‐help where you need to and if you’re not sure ask the community.
Ultimate Scripting: PowerShell explained Autumn 2011
Technical Seminars – Autumn 2011 © RM Education 2011
24
This help file gives information on how to setup various levels of signing. To get a better understanding of the levels you can set try get-‐help about_execution_policies here’s the section that describes each level. WINDOWS POWERSHELL EXECUTION POLICIES -‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐ The Windows PowerShell execution policies are as follows: "Restricted" is the default policy. Restricted -‐ Default execution policy. -‐ Permits individual commands, but will not run scripts. -‐ Prevents running of all script files, including formatting and configuration files (.ps1xml), module script files (.psm1), and Windows PowerShell profiles (.ps1). AllSigned -‐ Scripts can run. -‐ Requires that all scripts and configuration files be signed by a trusted publisher, including scripts that you write on the local computer. -‐ Prompts you before running scripts from publishers that you have not yet classified as trusted or untrusted. -‐ Risks running unsigned scripts from sources other than the Internet and signed, but malicious, scripts. RemoteSigned -‐ Scripts can run. -‐ Requires a digital signature from a trusted publisher on scripts and configuration files that are downloaded from the Internet (including e-‐mail and instant messaging programs).
Ultimate Scripting: PowerShell explained Autumn 2011
Technical Seminars – Autumn 2011 © RM Education 2011
25
-‐ Does not require digital signatures on scripts that you have run and that you have written on the local computer (not downloaded from the Internet). -‐ Risks running signed, but malicious, scripts. Unrestricted -‐ Unsigned scripts can run. (This risks running malicious scripts.) -‐ Warns the user before running srcipts and configuration files that are downloaded from the Internet. Bypass -‐ Nothing is blocked and there are no warnings or prompts. -‐ This execution policy is designed for configurations in which a Windows PowerShell script is built in to a a larger application or for configurations in which Windows PowerShell is the foundation for a program that has its own security model. Undefined -‐ There is no execution policy set in the current scope. -‐ If the execution policy in all scopes is Undefined, the effective execution policy is Restricted, which is the default execution policy. Note: On systems that do not distinguish Universal Naming Convention (UNC) paths from Internet paths, scripts that are identified by a UNC path might not be permitted to run with the RemoteSigned execution policy This may seem worrying, if a user can access PowerShell then surely they can change the execution policy and then have a free reign. The hierarchy of restrictions is set so that group policy superceeds PowerShell commands. EXECUTION POLICY PRECEDENCE -‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐ When determining the effective execution policy for a session, Windows PowerShell evaluates the execution policies in the following precedence order: -‐ Group Policy: Computer Configuration
Ultimate Scripting: PowerShell explained Autumn 2011
Technical Seminars – Autumn 2011 © RM Education 2011
26
-‐ Group Policy: User Configuration -‐ Execution Policy: Process (or PowerShell.exe -‐ExecutionPolicy) -‐ Execution Policy: CurrentUser -‐ Execution Policy: LocalMachine So if you want to be able to run scripts on your computer you’ll need to check the group policy is disabled for your PC (not the whole network!) Check the help file in full to find out more how to set and check policies. Testing scripts Full scripts are not as easy to just type –whatif after and check the results. It’s far more useful to setup a test environment to make sure anything that goes onto the live network is not going to cause problems. If you can gets a test network running (if you don’t already have one) then check any scripts (even the ones you download or copy) are not malicious or just badly written. While I have great trust in the PowerShell community, I trust no-‐one when your job or integrity could be on the line. Whatever you do, make sure it can be undone. The last thing you want is to not spot something in testing, find it in the live environment and then have to work out quickly how to undo it. Commenting on scripts Make sure any scripts you write have help in them. While PowerShell is easy to understand, it’s a lot easier if the author has added what that script does or when it has been updated and why. If that lottery win does come in there’s no need to leave your establishment and successor high and dry. Have a standard comment style across your establishment, so everyone using scripts is able to pick up scripts and understand them.