<<

Windows PowerShell Simple commands, powerful administration Don Jones

It’s been a long time coming, but Windows great language that has been frequent­ ly misused to create malicious scripts. PowerShell is almost ready to launch. That VBScript isn’t going away either, but you’ll likely find that Windows Power­ means it’s time for Windows administrators Shell is easier to use for many differ­ ent tasks. to start taking notice. Windows PowerShell You can do most anything with Win­ dows PowerShell that you would have offers what is perhaps the easiest and most done with Cmd.exe. For example, you can run ipconfig and you’ll get the flexible way to automate a wide variety same familiar output. But Windows PowerShell introduces a whole new of administrative tasks, making you more set of commands that aren’t external files. These cmdlets (pro­ efficient and more effective in your work. nounced ‘command-lets’) are built right into Windows PowerShell. (For a But even more importantly, Micro­ there are few reasons to continue us­ look at some of the most useful cmd­ soft is building the graphical admin­ ing Cmd.exe. lets to get you started using Windows istrative consoles of products like Using Windows PowerShell isn’t PowerShell, see the sidebar ‘Top 10 Exchange Server 2007 and System all that different than using Cmd.exe cmdlets to start using immediately’.) Center 2007 on top of Windows – except that Windows PowerShell is, All cmdlets are named with a stan­ PowerShell. This means you’ll be able well, more powerful. Like Cmd.exe, dard verb-noun format, making them to perform almost any administrative Windows PowerShell has a built-in easy to learn and remember. For in­ task from within Windows Power­ scripting language, although it is much stance, running the Get-Command Shell. Microsoft plans to do the same more flexible than Cmd.exe’s primitive cmdlet will list all the available cmdlets. with the administrative capabilities of batch language. How flexible? With Perhaps the most useful cmdlet for an more products over time. Thus, Win­ Windows PowerShell, you can auto­ administrator is Get-WMIObject. Say dows PowerShell could eventually mate extremely complex tasks with a you want to find out what service pack become the first all-purpose tool for language that includes only about a Server2 is running. Simply run:

administering nearly any Microsoft half-dozen built-in keywords. Get-WMIObject Win32_OperatingSystem –Property server product. To help you get start­ Now that I’ve mentioned scripting, ServicePackMajorVersion –Computer Server2 ed, I’ll discuss Windows PowerShell I should probably touch upon securi­ regularly in this new column. Be sure ty. Windows PowerShell benefits from To discover this same information us­ to download a copy of the software at: what Microsoft has learned about se­ ing VBScript, you would have to microsoft.com/powershell curity over the past decade plus. By several lines of code. Other cmdlets let default, Windows PowerShell won’t you work with services (Start-Service, Power and simplicity run scripts; it can only be used inter­ Stop-Service, and so forth), process­ As the name implies, Windows actively to run individual commands. es (Stop-Process and others), files PowerShell is a shell, not unlike the If you do enable scripting, you can di­ (Rename-Item, Copy-Item, Remove- Command Prompt (Cmd.exe) that’s rect Windows PowerShell to run only been around since Windows NT 3.1. digitally signed scripts. All of this is to This column is based on a prerelease Cmd.exe isn’t going away, but with the help ensure that Windows PowerShell version of Windows PowerShell. All availability of Windows PowerShell, doesn’t become the next VBScript – a information herein is subject to change.

68 To get your FREE copy of TechNet Magazine subscribe at: www.microsoft.com/uk/technetmagazine

68_71_PowerShell_UK_desFIN.indd 68 27/3/07 14:04:26 Item, Move-Item, for example), and Administrators can you can save the computer name into much more. Many of these cmd­ a String variable and use the Replace lets even have names, called now work directly method to replace backslashes with aliases. In the case of Get-WMIObject, empty strings, as shown here: you can just type gwmi. Running Get- with rich objects [string]$ = -Host “Enter computer name” Alias will provide you with a list of $c = $c.Replace(“\”,””) Get-WMIObject Win32_OperatingSystem these shortcut names. –Property ServicePackMajorVersion right within a text- –Computer $c Why object oriented matters based shell The value for the –Computer pa­ Built on the Microsoft .NET Frame­ rameter has been provided in the $c work, Windows PowerShell is com­ variable. That variable was initially cre­ pletely object-oriented. Usually, only a PowerShell so capable. Using this char­ ated as a string, so it picked up all the software developer would get excited acter, you can pass (or pipe) objects functionality of the .NET Framework about that, but in this case, the object from one cmdlet to another, allowing String type, including the Replace orientation results in a huge time sav­ each to further refine the results, for­ method. Of course, learning about all ings for administrators. This is because mat them for display, and so on. This of these capabilities will take a while, administrators can now work directly mechanism works because every cmd­ but you should find them easy to with rich objects right within a text- let returns one or more objects, rather pick up through examples. Windows based shell. Consider this example: than pure text, giving subsequent cmd­ PowerShell itself helps to simplify Get-Process | Sort-Object pm –desc | Select-Object –first 10 lets the full object to work with. learning. For example, if you type $c = This is just a single line with three The use of objects in Windows $c. (don’t forget the ) and press different cmdlets separated by pipes PowerShell is pervasive, all the way Tab, Windows PowerShell will display (more on this in a moment). The first down to its variables. And you don’t Clone(), the first method of the String cmdlet retrieves all running process­ have to declare variables up front; you type. If you keep pressing Tab, Windows es and then passes, or pipes, those can just start using them by placing a PowerShell will cycle through all the objects to Sort-Object. This second dollar sign ($) before a variable name. available methods. Essentially, when cmdlet sorts on each process object’s While it’s not required, you can also you do this, Windows PowerShell is pm (meaning Physical Memory) prop­ tell Windows PowerShell what type of showing you what it knows how to do erty, placing them into descending or­ data you want to put into the variable. with a String! der. The sorted collection of process That lets Windows PowerShell map Here’s a tougher task. Read a list of objects is then piped to Select-Object, the variable to one of the extreme­ computer names from a , with one which picks the first 10 and displays ly powerful .NET Framework types, name per line, and show each comput­ them. The result? This simple line dis­ giving you a lot of additional built-in er’s service pack number. In VBScript, plays the top 10 physical memory con­ functionality. For example, suppose this task would require a dozen or sumers on the machine, as shown in you want to prompt for a comput­ more lines of code. In Cmd.exe, you Figure 1. This is an extremely efficient er name and retrieve the service pack would have to use a complicated batch way to take a quick look when doing version from that computer, but you file. In Windows PowerShell, this task some troubleshooting. don’t know if the person typing in takes just one line: The use of pipes (the vertical line the computer name will include two Get-Content “c:\computers.txt” | foreach { $_; gwmi Win32_ character typically located on the backslashes (such as \\Server2). Since OperatingSystem -prop ServicePackMajorVersion -comp $_ } backslash key on US keyboards) is an you know that the Get-WMIObject The Get-Content cmdlet reads the essential part of what makes Windows cmdlet doesn’t need the backslashes, contents of C:\Computers.txt. Each line of the file becomes an object in its own right. This collection of objects – computer names, that is – is piped to the foreach command, which is real­ ly just an for the ForEach-Object cmdlet. The commands inside the curly braces are repeated once for each Figure 1 Using a object that is piped in – for this exam­ simple cmdlet to ple, that means they run once for each troubleshoot computer name. The special $_ vari­

TechNet Magazine April 2007 69

68_71_PowerShell_UK_desFIN.indd 69 27/3/07 14:04:26 running. Once you the shell, the function vanishes. You can copy the Top 10 cmdlets to start using immediately function into your Windows Power­ Get-Command retrieves a list of all available cmdlets. Shell profile, which is a sort of auto- Get-Help displays help information about cmdlets and concepts. run script that executes each time Get-WMIObject retrieves management information by using WMI. Windows PowerShell starts. Doing so Get-EventLog retrieves Windows event logs. would make the function available in Get-Process retrieves a single or list of active processes. every Windows PowerShell window Get-Service retrieves a Windows service. you . Or, if you want, you can Get-Content reads in text files, treating each line as a child object. make the function into a standalone Add-Content appends content to a . script, which you can then execute Copy-Item copies files, folders and other objects. simply by typing the script’s and Get-Acl retrieves access control lists (ACLs). file name.

The world is a file (or folder) There’s more to Windows PowerShell than just functions and cmdlets. Let’s look at file management as a quick ex­ able will contain the current object jects to loop through and what variable ample of what else is in store. You’re (that is, the current computer name). to store each object in – the part that probably more than familiar with Inside the curly braces are actually says ($name in $names). Everything drive and folder navigation in Cmd.exe two commands. The first simply dis­ else is pretty much the same, and as – type C: to switch to the C drive, and plays the current computer name by soon as you hit Enter, the code is ex­ type cd \test to change into the C:\Test outputting the contents of $_. The ecuted and the results displayed. folder. Windows PowerShell works in second is the now-familiar gwmi. The If you want to use this same code re­ the same way, although cd is just an result is a list of service pack versions peatedly, you can simply make a func­ alias for the Set-Location cmdlet. for every computer listed in the file. tion out of it. Once again, type this Try running Get-PSDrive, the cmd­ All this was done with one relatively directly into the shell: let that lists all available drives. In addi­ straightforward line of commands. PS C:\> function Get-ServicePacks ($file) { tion to the usual C:, :, and perhaps A: >> $names = get-content $file Notice that the –Property and –Com­ >> foreach ($name in $names) { drives, you’ll also find one named Cert, puter parameter names have been ab­ >> $name >> gwmi win32_operatingsystem -prop servicepackmajorversion another named Env, and others named breviated. Windows PowerShell only -comp $name HKCU and HKLM. Windows Power­ >> } requires enough to uniquely distin­ >> } Shell actually exposes many different guish the parameter names. >> types of storage resources as ‘drives’, As you can see, not much has actual­ making things like the local certificate Readability and reuse ly changed. This simply encloses the store, environment variables and regis­ Writing a single line of commands and previous example in a function named try available through a familiar file-like parameters, however, doesn’t help with Get-ServicePacks (in keeping with the navigational interface. readability. Windows PowerShell lets Windows PowerShell verb-noun nam­ You can change the HKEY_LOCAL_ you break this into something more ing convention). The function now MACHINE registry hive by typing readable, which you can type directly has an input parameter named $file, Set-Location HKLM: (or cd hklm: if into the shell without ever writing a which has been substituted in the Get- you prefer the shortcut) and hitting script. Here’s how it might look: Content cmdlet so that a different file Enter. Then run cd software\micro­ PS C:\> $names = get-content “c:\computers.txt” can be specified when the function is soft to change into the SOFTWARE\ PS C:\> foreach ($name in $names) { >> $name run. Now that the function is defined, Microsoft key. You can use – an >> gwmi Win32_OperatingSystem -prop ServicePackMajorVersion you can simply run it by calling its alias for the Get-ChildItem cmdlet – to -comp $name >> } name, almost like a cmdlet, and pass­ list the sub-keys in this portion of the >> ing the input parameter: registry. If you want to remove a key, This time, the contents of the file are PS C:\> Get-ServicePacks c:\computers.txt use del to delete it as if the key were a stored in the variable $names. This ex­ Figure 2 shows the results. file or folder. (Be very careful though ample still uses foreach, but it isn’t be­ The downside here is that this func­ – serious problems might occur if you ing input through a pipeline, so you tion will only exist for as long as that remove required keys or modify the have to tell it which collection of ob­ instance of Windows PowerShell is registry incorrectly.)

70 To get your FREE copy of TechNet Magazine subscribe at: www.microsoft.com/uk/technetmagazine

68_71_PowerShell_UK_desFIN.indd 70 27/3/07 14:04:26 All of this flexibility comes from iest way to develop and test scripts. which will indeed stop them! The re­ providers, which map resources (like The AllSigned mode doesn’t run any sult is a blue screen STOP error after the registry and certificate store) into scripts unless they’ve been digital­ about five seconds as critical Windows a format that looks like a . ly signed, using a certificate issued by processes are killed off. But you can Microsoft plans to extend Windows a trusted publisher. Finally, the Unre­ see what will happen, without actual­ PowerShell through additional provid­ stricted policy runs anything. I don’t ly letting it happen, by adding the very ers, giving you the ability to, for exam­ recommend this at all, as it opens up convenient –Whatif parameter: ple, navigate an Exchange Server store Windows PowerShell to run malicious Get-process | Stop-Process -Whatif as if it were a file system. This is a very scripts that may find their way onto Running this in Windows PowerShell important technique in that it takes your computer. Note that the execu­ results in a bunch of statements that the huge variety of repositories used tion policy can also be governed by tell you what the cmdlets would by Windows and makes them all ap­ Group Policy, which overrides any lo­ have done without actually letting pear identically, plus it makes them all cal settings. (Set-ExecutionPolicy will them do it. The online help system in manageable through a system of com­ warn you if a Group Policy setting is Windows PowerShell (accessible by mands and techniques that you’re al­ overriding your local settings.) using the help alias) doesn’t yet docu­ ready familiar with. In addition, Windows PowerShell ment the –Whatif parameter, but keep won’t run scripts from the current di­ it in mind. It’s a great tool for testing Designed for safety scripts and cmdlets to verify their re­ I’ve already mentioned that Windows sults without actually doing anything PowerShell was designed with securi­ PowerShell was potentially harmful or disruptive. ty and safety in mind. The primary se­ curity feature in Windows PowerShell designed with Wrap-up is its execution policy. By default, Among the features that didn’t make this policy is set to Restricted, which security in mind it into this version of Windows you can verify by running the Get- PowerShell, perhaps the most signifi­ ExecutionPolicy cmdlet. In Restricted rectory unless you specify the path. cant is support for Active mode, scripts don’t run. Full stop. Since This is designed to prevent com­ Services Interface (ADSI). While Win­ that’s the default mode, Windows mand hijacking. Say someone creates dows PowerShell can utilise the very PowerShell can’t be used to run scripts a script named IPConfig.ps1 (PS1 is robust .NET classes that work with out of the box. the file-name extension for Windows Active Directory and other directory You can specify other modes us­ PowerShell script files). If files could services, it doesn’t yet have a conve­ ing the Set-ExecutionPolicy cmdlet. I be run out of the current folder, there nient Get-ADSIObject cmdlet. The re­ personally prefer the RemoteSigned would be a risk that you might type sult is that it is a bit difficult to work mode. This allows local scripts (but ipconfig and run this user creat­ with directory objects. not remote scripts) to run without be­ ed script when, in fact, you were Also, Windows PowerShell often of­ ing digitally signed, providing the eas­ expecting to run the Windows pro­ fers a number of different ways to per­ gram Ipconfig.exe. Since Windows form the same task. That’s good, but PowerShell does not run scripts out of it can make learning Windows Power­ the current folder, this mistake can’t Shell more confusing since for any happen. If you do want to run a script given task you might see a half-dozen out of the current folder, just specify different examples of how to do it. the path: .\myscript, for example. The All of that will settle over time and the explicit reference to the current folder Windows PowerShell team will contin­ ensures that you know you’re running ue to add features and capabilities to the a script and not a shell command. product. To stay in the loop, visit the team’s Windows PowerShell also has fea­ blog at: blogs.msdn.com/powershell ■ tures that make experimentation saf­ er. For example, consider (but please do not try) this frightening combination: Don Jones is the founder of Get-Process | Stop-Process ScriptingAnswers.com, and the coauthor The Get-Process cmdlet creates a col­ of Windows PowerShell: TFM Figure 2 Results of running the lection of process objects and pipes (SAPIEN Press, 2006). Contact him at Get-ServicePacks function them to the Stop-Process cmdlet – [email protected].

TechNet Magazine April 2007 71

68_71_PowerShell_UK_desFIN.indd 71 27/3/07 14:04:27