Posted by Shane Corellian on Wed, Jan 26, 2011
I came across a pretty good YouTube channel featuring PowerShell videos. I haven't finished with all of the videos yet but I dig this guy's (Don's) style. I wish the video examples were a little more magnified sometimes but otherwise I'm quite pleased. Definitely check them out.
When you have an obvious language barrier with someone you work with never, EVER, listen to them and just nod your head. In fact when you don't understand a damn word they're saying, violently shake your head and mutter "oh, HELL no". You'll thank me.
If you're getting ready to add a feature to a script or a program make sure to ask yourself this question: What is the real benefit I get from adding this feature? Seriously? If you can't come up with a semi-literate answer, scrap it. Toss it. Move on. You'll thank me.
Sluffing. Hookey. Skipping. Truant. What did you call it when you missed school? Remember how you'd get in trouble for missing that class or even the entire day of school? Well try sluffing a meeting or two at work. If there are more than 6 people in regular attendance at your meeting, skip one every now and then. If there are more than 15 people then count your blessings and have your make to miss ratio come in around 1:5. You'll thank me.
I don't understand why so many computer geeks get upset at how our industry is portrayed in movies. Let the beliefs live on. I'm happy that my family thinks I can create a network connection between my mac and the aliens that are on the way down to earth. I finally look a little cool. I'm pleased that my extended family all think that I can blow crap up by just hitting a few keys on the keyboard. It keeps them in enough awe that I can cut in line to get the best Bratwursts and potato salad at every reunion. Just sayin' is all.
Follow me on Twitter
@ShaneCorellian
Posted by Shane Corellian on Wed, Dec 15, 2010
OK, if you don't have PowerShell 2.0 on your Windows computers it's time to gird up your loins and just do it.
Thankfully, PowerShell comes included with Windows 7 and Server 2008 R2. For your other Windows OSes go grab the appropriate install file. If you don't already use PDQ Deploy for your simple software deployment needs then grab a free copy right here.
It's quite simple to deploy, actually. Just grab the installer file appropriate for your target OS create a deployment in PDQ Deploy
Below is a screenshot of a basic Installation of Windows PowerShell 2.0 for Vista/2008 32-bit computers.

PowerShell is here to stay and it is a great shell which is something that Windows has been lacking for a long time. I remember when I first started playing with PowerShell back in 2007 I was hooked. For Windows Sys Admins this is a must-use technology.
We are going to add the ability to run PowerShell scripts natively from PDQ Deploy. So get PowerShell 2.0 on your targets systems sooner rather than later... perhaps the slow holiday season perhaps?
Follow me on Twitter
@ShaneCorellian
Posted by Adam Ruth on Fri, Oct 08, 2010

Photo by chigmaroff
We in the system administration community have become used to the name PowerShell. I know I have (I write about it often enough.) The name projects an important image. The image of being Powerful and also... I guess... being a Shell. As is so often the case, one must wonder if the product gives meaning to the name or does the name give meaning to the product. Does "Rolls Royce" bring to mind quality because of workmanship or is the name just a great fit? Well, you be the judge as you consider the top 10 names considered and rejected for PowerShell. One thing we can all agree on is that we're glad Microsoft made the choice they did.
10. AlmostBash
9. YAALShell (Yet Another Admin Language)
8. Cmd#
7. ClippyShell
6. Cmdlet Runner And Processor
5. VBScriptWho?
4. HunkyShell
3. LinuxShminux
2. Microsoft Interactive Keyboard Command Line Interpreter Client Console And Dynamic Script Processor 2008 Version 1 (Release 2)
1. DOS 7
Posted by Adam Ruth on Fri, Oct 01, 2010

Photo by photogirl7.1
PowerShell 2.0 shipped back in 2009 and included over 100 new cmdlets including major new functionality such as Jobs, Modules, and Remoting. That's great to see, but there's still so much more that can be done. So, in the vein of demanding others to do things for me, here are the top 6* cmdlets that PowerShell should ship with.
Threaten-Process: For when you want to keep a process from getting out of line but aren't quite to the point that you want to kill it. Alias: taze
Delete-FileForever: Not only deletes a file, but prevents it from ever being re-created. Pretty handy when dealing with viruses or playing pranks on co-workers. Optional argument -past goes back in time and stops the file from originally being created (the Sarah Connor option.)
Convert-RegistryToIni: Removes the registry completely from the system and replaces it with hundreds of .ini files in the Windows directory. Alias: out-of-the-fryingpan
Set-UACAutoClick: Creates a process to automatically click the accept button on all UAC prompts. For the wishy-washy person that's too scared to disable UAC but wants to get rid of the inconvenience (usually an MBA.) Alias: miss-the-point
Enable-FullSpeed: Makes the processor run at its actual speed, not the speed that's been imposed by the Trilateral Commission to keep the masses from decrypting secret government communications embedded in lolcats. Requires the tinfoil hat extensions.
Set-MovieInterface: Changes the UI to have really large text, make a clicking sound whenever a character is typed, add unnecessary maps and graphics to search functions, and the ability to extract gigabytes of image data from half an pixel. Alias: fakeintosh
* The list is limited to only the top 6 because there isn't a Finish-MyBlogPost cmdlet. Oh, I guess it's really a top 7 list.
Posted by Adam Ruth on Fri, Sep 17, 2010

Photo by nineball2727
If you've spent any time working with PowerShell you've probably built a function or two. Function parameters are a handy way to make general purpose functions that can be used in a number of different ways. Consider, for example, that you have a function that restarts a service that, for whatever reason, is misbehaving. You could have this:
function RestartService($name) {
net stop $name
net start $name
}
Sometimes you need to add a sleep between the start and stop to make sure that the service comes back up correctly, but you don't want to make a new function (one that sleeps and one that doesn't) so you add a new parameter.
function RestartService($name, $sleep) {
net stop $name
sleep $sleep
net start $name
}
This works great, except now you have to pass in a 0 most of the time, and only use the sleep parameter on those rare occasions. To fix this, you can make the $sleep parameter default to 0 so that if you omit it you don't get a sleep.
function RestartService($name, $sleep = 0) {
net stop $name
sleep $sleep
net start $name
}
This will give you the flexibility you need.
# Don't sleep
RestartService SomeService
# Sleep for 10 seconds before restarting
RestartService SomeService 10
Posted by Adam Ruth on Mon, Aug 23, 2010

Photo by Dave_B_
In two recent posts I went over the PowerShell formatting cmdlets and calculated properties. Today I'm going to cover Views. You'll notice that when you display a normal object (such as the built-in FileInfo objects when you run dir) you don't see all of its properties. This is because PowerShell is using a View, which is selected based on the type of object you're outputting and which type of output is being used (table, list, or wide.)
The views are stored in XML files in the PowerShell directory which you can examine to see how the formatting is being performed. Not only that but you can add your own views and even override the default views used by PowerShell.
The standard views are stored in %systemroot%\System32\WindowsPowerShell\v1.0 in a files with the extension format.ps1xml. There are several files, but the one we'll be looking at is FileSystem.format.ps1xml. This file holds the formatting for the various file system objects, such as FileInfo and DirectoryInfo. The section that defines the normal file system table output is this:
<View>
<Name>children</Name>
<ViewSelectedBy>
<SelectionSetName>FileSystemTypes</SelectionSetName>
</ViewSelectedBy>
<GroupBy>
<PropertyName>PSParentPath</PropertyName>
<CustomControlName>FileSystemTypes-GroupingFormat</CustomControlName>
</GroupBy>
<TableControl>
<TableHeaders>
<TableColumnHeader>
<Label>Mode</Label>
<Width>7</Width>
<Alignment>left</Alignment>
</TableColumnHeader>
<TableColumnHeader>
<Label>LastWriteTime</Label>
<Width>25</Width>
<Alignment>right</Alignment>
</TableColumnHeader>
<TableColumnHeader>
<Label>Length</Label>
<Width>10</Width>
<Alignment>right</Alignment>
</TableColumnHeader>
<TableColumnHeader/>
</TableHeaders>
<TableRowEntries>
<TableRowEntry>
<Wrap/>
<TableColumnItems>
<TableColumnItem>
<PropertyName>Mode</PropertyName>
</TableColumnItem>
<TableColumnItem>
<ScriptBlock>
[String]::Format("{0,10} {1,8}", $_.LastWriteTime.ToString("d"), $_.LastWriteTime.ToString("t"))
</ScriptBlock>
</TableColumnItem>
<TableColumnItem>
<PropertyName>Length</PropertyName>
</TableColumnItem>
<TableColumnItem>
<PropertyName>Name</PropertyName>
</TableColumnItem>
</TableColumnItems>
</TableRowEntry>
</TableRowEntries>
</TableControl>
</View>
If you're not used to XML this may appear a bit daunting, but you can get a quick sense of how it works. There are four main sections of the file.
- <ViewSelectedBy> indicates which object types are used by this view. In this case, the name FileSystemTypes refers to another section in the file that lists the types. That section is <SelectionSets>. The individual type names can be listed instead, but this reference makes the code shorter.
- <GroupBy> tells the table of files to be grouped by thier parent path. This also refers to another section of the file called <Controls>.
- <TableHeaders> sets up not only the titles that appear on the table columns, but also their width and alignment.
- <TableRowEntry> the actual values to show in the table. Three of the colums just pull out a property by name, but the LastModifiedTime uses PowerShell code to format the date in a particular way. Any PowerShell code can be used which gives a great deal of flexibility.
There are a lot of possibilities for how to create views and the documentation is a bit limited. To learn about formatting it's best to look at the included format files to see how things are done.
To make a custom view you will need to create your own format.ps1xml files since you can't edit the built in ones. If there is more than one view for an object then the first one found will be used. Otherwise they can be selected by name using the -View parameter of the format cmdlets. Once you have a file created you import the formats using the Format-UpdateData cmdlet. As an example of a new format, I've create a format file that adds a CreationTime column in addition to LastWriteTime. Download the file, save it with the extension .format.ps1xml and run the following command:
Format-UpdateData -PrependPath [filename]
Now when you list the contents of a directory you will see the new column. Alternately you could have used -AppendPath to put the file after the built in formats and then you would need to use the view by name:
dir | Format-Table -View MyFormat
To make the custom format persistent between sessions, add the Format-UpdateData command to your PowerShell profile. One of the principles of PowerShell is the ability for you to configure it to your tastes and Views are a very powerful, if somewhat complex, way to get just want you want.
Need help using formats (or anything else) in PowerShell? Post a question in our
PowerShell forum to ask one of our engineers.
Posted by Adam Ruth on Mon, Aug 02, 2010

Photo by Andrew®
A profile in PowerShell is nothing more than a script file that is run when the shell starts. This file is very handy to create variables, functions, or change settings that you find you use a lot. Instead of having to re-import a library of functions or change the shell's settings each time you start up PowerShell.
The variable $profile holds the name of the file that you are using for the current shell. PowerShell doesn't create this file, so it won't exist out of the box, but the variable will still hold the name. For example, on my box it is:
C:\Users\Adam> $profile
C:\Users\Adam\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
You can put anything in this file that you can put into a script file, so feel free to create functions, set variables and run commands. Any changes made to the file won't be used by the current shell, so you'll need to restart to see any effect. And remember that if you are going to load any other script files in the profile you need to precede the script with a single dot (.) for the functions and variables in that script file to remain visible in your new shell:
. \libs\Functions.ps1
There is also a profile on the computer that applies to all users as well as profiles for other shells. Microsoft has all of the lowdown.
Follow me on Twitter @AdamRuth
Posted by Adam Ruth on Wed, Jul 28, 2010
In a previous post I went over three cmdlets for formatting data. Each of those cmdlets let you select which object properties you want to show. You aren't just limited to the existing properties on the objects, though, you can use Calculated Properties which let you format the properties in any way you like. The syntax for calculated properties looks a little odd at first, but it's actually quite simple.
For example, this expression displays the time between the creation and last write times of files:

There are a few things here that need explaining:
- The back-tick at the end of the first line allows you to type in commands on multiple lines, making it easier to read and write long commands.
- Calculated properties are defined as Hash Tables, which are simple name/value containers. They are created by putting the names and values inside of @{} separated by semicolons.
- Calculated properties require that the hash table has two values: Name and Expression.
- The Expression value in the hash table is itself enclosed in curly braces {} which is the way you pass PowerShell script code as a property to a cmdlet.
- The value $_ inside of the Expression is the object that is being formatted. In the above example it is referenced twice to pull out the two properties CreationTime and LastWriteTime.
- CreationTime and LastWriteTime are .NET objects called DateTime and they have a number of properties and actions themselves. The example uses the Subtract method which gives the difference between two DateTime objects.
- The object returned from the Subtract method is called a TimeSpan. It displays as days.hours:minutes:seconds.milliseconds. It also has a number of properties to get these values individually.
As you can see, showing a TimeSpan like that is not the easiest to read. We can display just the days like this:

One PowerShell construct that is very helpful when formatting output is the -f operator. This takes text with embedded placeholders in it and replaces them with formatted values. A simple example:

There are two placeholders which insert the two values (placeholder numbering starts with 0.) Not only can the -f operator insert the given values, but it can also format numbers in a variety of ways. Consider this example:

This example shows the size of each file in megabytes, formatted out to two decimal places. It starts by dividing the Length of the file by 1Mb (which is a built-in PowerShell value handy when dealing with file sizes along with 1kb, 1gb, and 1tb.) This value is then passed to a format placeholder {0:0.00}. The text after the colon defines how the number is to be displayed. In this case, it will show one at least one digit to the left and no more than 2 digits to the right of the decimal. There are many different types of formatting rules you can use, here's Microsoft's documentation for more details.
Once you understand the basics of Calculated Properties, there really isn't any limit to how values can be formatted. Calculated properties aren't just for making output easy to read, but they come in very handy when you need to pass the output of some command to a program that expects things to be in a specific format. Consider using them any time you have to massage data manually.
Need help with PowerShell? Post a question in our new PowerShell forum and get an answer quick.
Posted by Adam Ruth on Fri, Jul 23, 2010
In PowerShell everything is a .NET object, each with a variety of different properties. You'll notice that most of the time the output you see from basic commands only gives you a small subset of what's available. This is because PowerShell has built-in rules for how and what to display for most of the standard objects. Usually this is done so that you normally only see what's most important and aren't overwhelmed with too much data. For example, the dir command returns a set of FileSystemInfo objects but only shows you a few of the 20+ properties that are available.

You can override the default output for any object and PowerShell provides a set of cmdlets for just this purpose: Format-Wide, Format-Table, Format-List, and Format-Custom. I'll cover Format-Custom in another post, so for now here's a brief description of the first 3.
Format-Wide
This cmdlet simple takes one property of each object and writes them out across the window. This is similar to the /w option when using dir in cmd.exe.

Notice that to use the cmdlet you need to pipe the output of the dir command to Format-Wide. Unlike the pipe command in cmd.exe, you aren't just sending the text from the first command but actual .NET objects which allows the second command to have full control when dealing with them.
With Format-Wide you can select the property to show with the -Property parameter. You can also adjust the width of the columns with -Column.

Format-Table
This cmdlet formats objects just like the default dir command, but you have control over what properties show up and how they are formatted. For example:

In order to adjust the widths of the columns independently you need to create a View and pass it to the cmdlet, but that's a topic for its own posting. You can even group the output by unique properties of the files.

Format-List
This cmdlet formats the output as a list of properties. It's similar to the table output, but rotated 90 degrees.

Just like Format-Table you can decide which properties to show. You can use wildcards to select multiple properties (this also works with Format-Table.)

If you just use * for the property list you'll see all of the properties of the object. This is handy while exploring objects to see what information you can work with.
Hopefully this quick overview will get you exploring the different ways to output data in PowerShell. In future posts I'll discuss more advanced topics such as Format-Custom, Views, and Calculated Properties.
Follow me on Twitter @AdamRuth.
Posted by Adam Ruth on Fri, Apr 16, 2010

Photo by *yasuhiro
I find myself having to deal with Windows services quite a lot, probably more than the average system administrator. The two most common tools administrators use are the services.msc MMC snap-in and net.exe (net start and net stop, in particular.) One more tool that I keep close is sc.exe because it gives capabilities that you can't find in the other tools.
It provides pretty much everything that a developer can do when programming directly to the Service Control Manager. The commands that I use most often are create and delete. These are particularly useful when I'm writing a service and I need to test it on one or more machines.
Creating a Service
The create command has the following syntax:
sc.exe <server> create [service name] [binPath= ] <option1> <option2>…
Run "sc.exe create" to see all of the options. The ones you'll use most are:
- start= (auto, manual, disabled)
- obj= (account name)
- password= (password)
- DisplayName= (friendly name)
There are some gotchas that you may run into (I know I have!):
- If using PowerShell you need to use sc.exe instead of just sc since sc is an alias for the built-in cmdlet Set-Content.
- If you get the syntax wrong you won't get an explanation of what why, you'll only get the usage description so it can be difficult to track down typos.
- All of the options follow the same syntax of "binPath= path." Note that there is no space before the equal sign and a space afterwards. That's caught me many times, the command will choke on "binPath = path" and "binPath=path."
- You'll most likely need quotes in the binPath= parameter. For example if the service path is "C:\Program Files\Company\Name\Service.exe" -service you'll need to escape the quotes. This is done differently if you're using PowerShell or cmd.exe:
- PowerShell: sc.exe create name binPath= '\"C:\Program Files\Company\Name\Service.exe\" -service'
Note the \ before the double-quotes and the whole thing is wrapped in single-quotes. - cmd.exe: sc.exe create name binPath= """"C:\Program Files\Company\Name\Service.exe""" -service"
Note that it's wrapped in double-quotes and the inner quotes are three sets of double-quotes.
Editing a Service
There is a config command that lets you change all of the service's settings without re-creating it. It has the same options as the create command.
Deleting a Service
Deleting a service is a lot simpler:
sc.exe <computer> delete [service name]
If the service is still running when you do this, it will be "marked for deletion" which is a kind of limbo state where the service can't be controlled any more (can't be stopped.) If that happens, most of the time you can flush the delete by killing the service's process. In the rare case where that doesn't work, a reboot will be required.
Services on Other Computers
In order to work with services remotely on other computers you need to have File Sharing turned on and opened through a firewall. If you can get to a file share on the computer, you'll be able to modify its services.