Wednesday, January 25, 2012

Regular Expressions: Using Lookaheads to Group and Grab Exactly the Text You Want

My previous post used zero-width lookahead and lookbehind assertions to grab some text from a gnarly-looking string, so I thought I'd follow up with a quick post on how that works.  It's not as complicated as the name sounds.

I had this string, from which I wanted to extract the domain and username:

\\SERVER\root\cimv2:Win32_Group.Domain="MYDOMAIN",Name="adminuser"

I know that I want the text between the double-quotes immediately following the words "Domain" and "Name".  I decided on this approach:

$string -match '(?<=Domain\=")(?<domain>[^"]+).*(?<=Name\=")(?<name>[^"]+)'

The characters in blue are, as described in the previous post, named groups, which will be captured and assigned in the automatic variable $matches with those names (Eg. $matches.domain).  The characters in red are the zero-width lookbehind assertions.

So what are they good for?  You can use lookaheads and lookbehinds if you want to make sure that a specific pattern comes before or after the pattern you want to capture, but don't actually want that pattern to be captured.  They look like groups, but will not be added to $matches.

A lookbehind assertion looks like this:

(?<=YOUR_PATTERN_HERE)

A lookahead assertion looks like this:

(?=YOUR_PATTERN_HERE)

Ah, but what if I want to make sure that a certain pattern does not follow my group?  Just replace the equality sign with an exclamation point, like so:

(?<!YOUR_PATTERN_HERE)
(?!YOUR_PATTERN_HERE)

So let's break down what my regex does:

# Check that the pattern 'Domain\="' is in the string, 
# but do not capture this group.
(?<=Domain\=") 

# Immediately following it, capture one or more characters that are not the 
# double-quote character and name this group "domain"
(?<domain>[^"]+)

# Match zero or more of any character.
.*

# Check that the pattern 'Name\="' is in the string, 
# but do not capture this group.
(?<=Name\=")

# Immediately following it, capture one or more characters that are not the 
# double-quote character and name this group "name"
(?<name>[^"]+)



Tuesday, January 24, 2012

Named Groups in Regular Expressions

I don't know how I went this long without discovering named groups in regular expressions, but I'm genuinely excited about them (yes, I'm a nerd).

A quick recap of the most common way to use regular expressions in PowerShell. Let's say I have a string like the one below (sorry it isn't a more simple example, but this is literally something I ran into today).  I got it by querying the local administrators of a system using SCCM.  The problem is, I want it in domain\user format.

\\SERVER\root\cimv2:Win32_Group.Domain="MYDOMAIN",Name="adminuser"

My first thought was to do something like this:

$string -match '(?<=domain\=")([^"]+).*(?<=name\=")([^"]+)'

It evaluates to True on my test string, so I go look at $matches:

$matches


Name                           Value
----                           -----
2                              adminuser
1                              MYDOMAIN
0                              MYDOMAIN",Name="adminuser

Okay, I've captured my groups, but I notice something strange.  Why is $matches a hashtable instead of an array?  Because of named groups, that's why.

To create a named group, you put the parentheses around it just like normal, but you add
'?<groupname>' to the beginning of the capture.  This stores the group under the name 'groupname'.  Let's try that with the above example:

$string -match '(?<=domain\=")(?<domain>[^"]+).*(?<=name\=")(?<name>[^"]+)'


$matches


Name                           Value
----                           -----
name                           adminuser
domain                         MYDOMAIN
0                              MYDOMAIN",Name="adminuser

It makes my regex a little longer, but it is so much easier now when I go to use the values I've collected to remember $matches.domain and $matches.name instead of $matches[1] and $matches[2].



Tuesday, January 10, 2012

Harnessing the Power of PowerShell to Load-balance Sophos Servers

At work we have a decent-sized Sophos installation.  This means that we have to use message relays to manage the status traffic back and forth between the Enterprise Console and the clients.  I recently discovered that although I could use groups to point client updates to their local server for updating, the message routers weren't affected.  As a result almost all clients ended up using the same server as a message relay.  I confirmed with my TAM that this feature is by design, so I set out to fix it with a script.  What I ended up with is basically what you see below.

A few things worthy of note:

  • I've pretty much standardized on using that logging boilerplate for most of my scripts.  It makes it easy to log errors and insert debug statements at the code as I'm writing so that I can always set -loglevel to 'debug' later when troubleshooting.
  • I made the caller pass the name of the mrinit.conf file so that I could create one small SCCM package for the script with all five different mrinit.conf files.
  • If you decide to do this, don't use the mrinit.conf file from the root of the package directory on the Update server.  There should be an mrinit.conf file in the rms subfolder.  Use that one.  If it isn't there, then you might not be configured to use a message relay, and this script won't help you until you are.



WARNING!  ACHTUNG!  AVISO!  LUU Y!
I am doing the QA and testing for my organization.  I make no guarantees that this script will work for yours.  Sophos is a temperamental beast, and you should do the due diligence to test and do the QA and do whatever modifications it takes to make it work for yours.  You may also wish to consult with your Sophos TAM before undertaking a project like this.


Wednesday, October 5, 2011

InnerException: We have to go deeper.

I helped a co-worker with an interesting issue today.  He was writing a PowerShell script that downloads a file.  He wanted to catch any errors with the download, so he had some code like this:

$client = New-Object System.Net.WebClient
try {
  $client.DownloadFile('http://www/files/file.txt', file.txt)
catch [System.Net.WebException] {
  # $_ is set to the ErrorRecord of the exception
  Out-Log $_.Exception.Message
}

This usually works, returning the text of the error, but this time he was getting back:

An exception occurred during a WebClient request.

That's not a very informative error.  Removing the try/catch blocks, he got this on the screen:


System.Net.WebException: An exception occurred during a WebClient request. ---> System.UnauthorizedAccessException: Access to the path 'C:\Users\tojo2000\hosts.txt' is denied.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean 
...


So obviously the information is in there somewhere.  It turns out that WebException usually returns the error code of the request, but if it runs into an error that is not related to the actual download, it will add the second exception to a property of the WebException object called InnerException.  

So the updated code looks something like this:


$client = New-Object System.Net.WebClient
try {
  $client.DownloadFile('http://www/files/file.txt', file.txt)
catch [System.Net.WebException] {
  # $_ is set to the ErrorRecord of the exception
  if ($_.Exception.InnerException) {
    Out-Log $_.Exception.InnerException.Message
  } else {
    Out-Log $_.Exception.Message
  }
}


Now we get the correct output:


Access to the path 'C:\Users\tojo2000\hosts.txt' is denied.


Friday, July 15, 2011

When Is a String Not a String?

I came across a really difficult-to-troubleshoot bug today, a real brain-teaser.

A co-worker asked me to help him figure out why his PowerShell script was running a certain piece of code even though it shouldn't.  He had a piece of code to detect a bad Windows Installer exit code like this:

$result = InstallSomeSoftware
if ($result -eq "1603") {
  #do something...

The "do something part was being executed no matter what value he returned from the InstallSomeSoftware function.  To troubleshoot, he added some Write-Host statements to display the return value on the screen before returning it inside the function.  Sure enough, the expected value was printed on the screen, and it was not 1603.

We both scratched our heads for a while, stepped through the function, and still weren't getting anywhere, when I noticed a few random lines of output.  We realized that there were lines in his function that were returning values and not being captured by any variable or thrown away, so they were also being returned along with the expected value.

So that leaves one last piece of the puzzle.  Why would everything always evaluate to True when compared to the string "1603"?  After a little more digging we had the answer.  The first value being returned had the value True.  -eq, when attempting to determine equality, saw that the two object types weren't the same, so it did what it was supposed to do:  it cast the string "1603" as a System.Boolean and then checked to see if True was equal to  True (which is what the string "1603" evaluates to as a Boolean).

Many hairs were lost in this battle, but at least in the end we had our sanity.

Monday, April 4, 2011

The 2011 Scripting Games Start Today!

Just a reminder to get scripting.  I'm going to try to make the time to participate in each event this year, and then I'll be posting my solutions here after the submissions are closed.

If you're interested in the Scripting Games at all, I suggest you bookmark this URL:  All 2011 Scripting Games links on one page.

Thursday, March 3, 2011

One Approach to Logging in PowerShell

I was writing a script recently, and I realized that I was missing the ability to use the standard logging module from Python.  I decided to make a stripped-down logging function that would make logging easy, and that could be re-used.  I'd be interested to hear what approaches others have taken to solving this problem.  Here's what I came up with:



# Set severity constants
$MSG_INFORMATION = 0
$MSG_WARNING = 1
$MSG_ERROR = 2
$MSG_SEVERITY = @('Information', 'Warning', 'Error')


# Set configurable settings for logging
$LOG_LEVEL = $MSG_INFORMATION
$LOG_FILE = 'my_logfile.log'
$SMTP_TO = 'devnull@tojo2000.com'
$SMTP_SERVER = 'smtp.tojo2000.com'
$SMTP_SUBJECT = 'Script error!'


function Write-Log {
  <#
  .SYNOPSIS
     Writes a message to the Log.
  .DESCRIPTION
    Logs a message to the logfile if the severity is higher than $LOG_LEVEL.
  .PARAMETER severity
     The severity of the message.  Can be Information, Warning, or Error.
     Use the $MSG_XXXX constants.
     Note that Error will halt the script and send an email.
  .PARAMETER message
     A string to be printed to the log.
  .EXAMPLE
     Log $MSG_ERROR "Something has gone terribly wrong!"
  #>
  param([Parameter(Mandatory=$true)][int]$severity,
        [Parameter(Mandatory=$true)][string]$message)


  if ($severity -ge $LOG_LEVEL) {
    $timestamp = Get-Date -Format 'yyyy-MM-dd hh:mm:ss'
    $output = "$timestamp`t$($MSG_SEVERITY[$severity])`t$message"
    Write-Output $output >> $LOG_FILE


    if ($severity -ge $MSG_ERROR) {
      Send-MailMessage -To $SMTP_TO `
                       -SmtpServer $SMTP_SERVER `
                       -Subject $SMTP_SUBJECT`
                       -Body $output `
                       -From $SMTP_FROM
      exit 1
    }
  }
}

Tuesday, January 25, 2011

Nothing To DO With PowerShell

Just a quick update to plug one of my other projects: py-ad-ldap.  Have you ever wanted to run scripts against Active Directory but not wanted to run them on Windows?  You haven't?  Well, if you had, then this would have been the Python module for you.  I haven't packaged it up for download yet (hopefully tomorrow), but it's pure Python, so there are no fancy requirements for installing it, so mosey on down to the repository and take a look at the source files if you're interested.

Sunday, January 23, 2011

Getting Performance Counters in PowerShell

I had a friend ask me recently if there was an easy way to monitor arbitrary performance counters in a script, and I didn't really have time to think about it at the time, but this weekend I decided to give it a whirl, and I came up with this function, that I'll definitely be putting in my profile at work.

The way it works is pretty straightforward, but you need to know some background about Performance Counters if you haven't used them before.  There are basically four pieces of information needed to retrieve a counter:

  • Category
  • Counter
  • Instance
  • Computer
If these don't ring a bell right away, fire up Perfmon, right-click and select Add Counters, and you'll see something like this:


In the top-left box you can see the Categories, and if you expand them you'll see the Counter names, and bottom left are the Instances.

Classic example: you want to find out the Current Disk Queue Length on your C: drive.
  • Category = 'LogicalDisk'
  • Counter = 'Current Disk Queue Length'
  • Instance = 'C:'
  • Computer = '.' (default, it means "this computer")
Using Get-PerformanceCounter, you'd do it like this:

Get-PerformanceCounter LogicalDisk 'C:' 'Current Disk Queue Length'

Or lets say you want to get all of the counters for the C: drive:

Get-PerformanceCounter LogicalDisk 'C:'



Anyway, here's the function, and you can also find it here: http://poshcode.org/2475

Monday, November 30, 2009

A Great Write-Up on WMI Events and PowerShell 2.0

I haven't been inspired to do a full post in a while, but I stumbled across this article by Trevor Sullivan today, and I thought I'd point it out for those of you that are interested.

Friday, October 30, 2009

Working with CSV Files

It's been a while since I had an update to the blog, and I've been waiting for something to jump out at me. Today I read on the news that the White House has released some visitor logs to the public, and they are making them available for download as a CSV file, and it piqued my interest, so I downloaded the file.

PowerShell v1 and v2 both have a module called Import-CSV that makes it ridiculously easy to work with CSV files. They will slurp up the file and output an array of objects, one per row, with properties that correspond to the columns in the file.

Let's import the file and look at a record:

PS> $visitors = Import-Csv .\10-30-waves-posting.csv
PS> $visitors[-1]


NAMELAST : ZIMPHER
NAMEFIRST : NANCY
NAMEMID : L
UIN : U81194
BDGNBR : 72400
ACCESS_TYPE : VA
TOA : 4/1/20091:45:42PM
POA : D0102
TOD : 4/1/20095:50:21PM
POD : D1
APPT_MADE_DATE : 3/25/20095:07:33PM
APPT_START_DATE : 4/1/20092:00:00PM
APPT_END_DATE : 4/1/200911:59:00PM
APPT_CANCEL_DATE :
Total_People : 3
LAST_UPDATEDBY : J7
POST : WIN
LastEntryDate : 3/25/20095:08:57PM
TERMINAL_SUFFIX : J7
visitee_namelast : DOUGLAS
visitee_namefirst : DEREK
MEETING_LOC : OEOB
MEETING_ROOM : 459
CALLER_NAME_LAST : WILKINS
CALLER_NAME_FIRST : ELIZABETH
CALLER_ROOM :
Description :

Interesting. I wonder, who had the most visitors (I snipped out the middle of the results)?

PS> $visitors |
Group-Object visitee_namelast |
Sort-Object Count |
Select-Object Count, Name

Count Name
----- ----
1 ANDREW
1 LONG
1 BINNIX
1 BREWER
...
7 'SUMMERS'
7 JARRETT
8 'POTUS/FLOTUS'
8 'EMANUEL'
9 POTUS/FLOTUS
9 'DOEBLER'
10 DOEBLER
10 'TCHEN'
12 TCHEN
42 'POTUS'
56 POTUS
69 OFFICE
211

Uh oh. There's something funky about this file. There are empty lines, and it's inconsistent about when it puts quotes around text fields. I'm pretty sure we don't have any fields with commas in them, so let's try stripping out any lines that only have whitespace and/or commas in them and then strip out single quotes from the rest of the lines:

PS> Get-Content .\10-30-waves-posting.csv |
?{$_ -notmatch '^(\s|,)*$'} |
%{$_.replace("'", '')} > wh.csv

** Note: that regex after -notmatch above can be read as:
^ start at the beginning of the string
(\s|,)* zero or more whitespace or comma characters
$ the end of the string

There. Now we can try that again, using our new file (snipped for length again).

PS> $visitors = Import-CSV .\wh.csv
PS> $visitors |
Group-Object visitee_namelast |
Sort-Object Count |
Select-Object Count, Name
Count Name
----- ----
1 SHAH
1 LONG
1 PETER
1 ANDREW
...
19 DOEBLER
22 TCHEN
69 OFFICE
98 POTUS

So now we know that the person with the largest number of visitors was the President of the United States of America. Hardly surprising, but you can easily explore this data with PowerShell. Here are a few more queries you might try:

Look at the records of the visits to the President

PS> $visitors |
?{$_.visitee_namelast -eq 'POTUS'}

How many visits occurred in July?

PS> $visitors |
?{$_.APPT_START_DATE -match '^7/'} |
sort APPT_START_DATE |
select NAMELAST, NAMEFIRST, APPT_START_DATE

What was the description given of the appointments for meeting the President?

PS> $visitors |
?{$_.visitee_namelast -eq 'POTUS'} |
select APPT_START_DATE, NAMEFIRST, NAMELAST, Description |
sort APPT_START_DATE


Hopefully this gives you a good idea of how you can manipulate CSV data using PowerShell using Import-CSV and a little filtering.

Thursday, September 3, 2009

A Regular Expression Cheat Sheet for PowerShell

Okay, so there's really not much that is PowerShell-specific about this cheat sheet, but I wrote it up in response to a post on microsoft.public.windows.powershell, and I thought I'd share it here, since I know a lot of new PowerShell users haven't been exposed to Regular Expressions very much.

This is not meant as an exhaustive reference on regular expressions, but just something that may be helpful if you get a little stuck. I hope you find it helpful.

1. What kind of character is it?

[] - any of the characters inside the brackets will match
(use the dash to indicate a range)
Examples: [a-z] will match any letter.
[aeiou] will match any vowel
\w - "word" characters. Basically matches [a-z0-9_]
\s - "whitespace" characters. matches spaces, tabs, etc.
\d - any digit. Basically matches [0-9]
\t - a tab character
. - any character


2. How many characters?
(the below appear after the character class)

{x} - matches x number of characters
{x, y} - matches minimum x number of characters, maximum y characters
Examples: \d{4} matches 4 digits
* - matches ZERO or more of the character (as many as possible)
+ - matches ONE or more of the character (as many as possible)
*? - matches ZERO or more characters (as few as possible)
+? - matches ONE or more characters (as few as possible)


3. Where is the character?

\b - matches a word boundary, without actually absorbing any characters
^ - matches the beginning of a string
$ - matches the end of a string


4. Grouping

() - any characters between the parentheses will be their own group
(try checking the value of $matches after using -match)
| - a pipe character is the OR character
Example: (one|two) will match the word "one" or the word "two"

Wednesday, August 26, 2009

Add a List of Users to the Local Admins Group

Just a quick update here, and another real-world example of where the Split() method of a string can come in handy for day-to-day tasks.

Today I had to add a list of about 20 individual usernames as administrators to a particular machine. Someone sent me the comma-separated list in an IM, and it took me about ten seconds:

PS> 'user1,user2,user3,user4,user5,user6,user7,user8,user9,user10'.split(',') |
>> %{net localgroup administrators $_ /add}

The command completed successfully.

The command completed successfully.

The command completed successfully.

The command completed successfully.

The command completed successfully.

The command completed successfully.

The command completed successfully.

The command completed successfully.

The command completed successfully.

The command completed successfully.

Wednesday, August 12, 2009

Use PowerShell to Get Local Group Members from a Remote Computer

I had a friend ask me recently how to get a list of administrators from a server.

"That's easy" I thought. "You just have to... um... actually..."

It turns out that this can be frustratingly difficult in PowerShell, so I wrote this module to make it easier when I'll need to do this in the future. It's comprised of three functions:
  • Add-NoteProperty: About 90% of the time when I want to create a custom PSObject and add some properties, they're all NoteProperties. This function makes adding a property easy, like so: Add-NoteProperty $my_object 'PropertyName' $property
  • Get-COMProperty: This is a kludgy hack to get around the fact that members of groups gotten through ADSI get returned as __ComObject objects, and you have to call the InvokeMember() static method of the class in order to get at their properties. Now I can just do this: Get-COMProperty $com_object 'PropertyName'
  • Get-LocalGroups: This is the function that we needed. It returns a list of custom PSObjects representing the local groups on a server, and each one has a property called Members that is a list of custom PSObjects for each member, including the Name, Domain, and ADSPath. From there, you can use whatever method you want to the object you want, whether it's using Get-QADUser for domain users, or whatever, for example: Get-LocalGroups computername.
If you're using Powershell v2 CTP3 or higher, you can use help on each of the functions to see examples if you forget. You can download the module from Poshcode.org here.



Saturday, August 8, 2009

String Manipulation: Splitting and Joining Strings

I think it's time to get back to some more basic things, so let's get to it.

The split()method of a string object lets you define a delimiter and "split" the string up into multiple pieces, which are returned as an array.

Let's say I do this:

PS C:\Users\tojo2000> $string = "one two three four"
PS C:\Users\tojo2000> $string.split(" ")
one
two
three
four


As it turns out, though, split() splits on a single whitespace character by default.

Observe:

PS C:\Users\tojo2000> $string = "one two three four six"
PS C:\Users\tojo2000> $string.split()
one
two
three
four

six


What's the practical use for this? Let's say you have a tab-separated values file called people.txt that looks like this:

Doe John California
Doe Jane Texas
Neuman Alfred Nebraska


And you want the output to be First Last, Location. You could do it like so:

PS C:\Users\tojo2000> Get-Content people.txt |
>> %{$data = $_.split("`t"); Write-Output "$($data[1]) $($data[0]), $($data[2])"}
>>
John Doe, California
Jane Doe, Texas
Alfred Neuman, Nebraska


But what if you have a file like this called people2.txt (let's say the first part is some kind of ID)?

2323:Doe John California
827:Doe Jane Texas
982982:Neuman Alfred Nebraska


Now you have two delimiters, but the split() method of a string object takes a string as an argument, so you would have to split twice in order to get each part of the string split into an array. If only there was some way to split on a regular expression... Oh, wait, there is.

PS C:\Users\tojo2000> Get-Content people2.txt |
>> %{$data = [regex]::split($_, '\t|:'); Write-Output "$($data[2]) $($data[1]), $($data[3])"}
>>
John Doe, California
Jane Doe, Texas
Alfred Neuman, Nebraska


('\t|:' is a regular expression for a tab character or a colon)

What if you have an array, and you want to make a string out of it? Then you can join the strings together using join(). Now there are two ways to join a list of strings, depending on whether you're using PowerShell v1 or v2.

The first way works in both v1 and v2:

PS C:\Users\tojo2000> $buncha_strings = 'one', 'two', 'three', 'four', 'five', 'six'
PS C:\Users\tojo2000> [string]::join(' and a ', $buncha_strings)
one and a two and a three and a four and a five and a six


So what practical use would there be? For a completely contrived example, maybe you want to create a new version of people2.txt called people3.txt that uses pipe characters to separate the fields. We'll split the strings up into an array just like before, but then we'll join them back together the way we want them.

PS C:\Users\tojo2000> Get-Content people2.txt |
>> %{$data = [regex]::split($_, '\t|:'); [string]::join('|', $data)} > people3.txt
PS C:\Users\tjo2000> Get-Content .\people3.txt
2323|Doe|John|California
827|Doe|Jane|Texas
982982|Neuman|Alfred|Nebraska


There is one more way that you can join a list of strings, but this method only works in v2: the -join operator. It works the same way as the other join(), but the syntax is slightly different.

For example, here is how you would join a list of strings by tab characters:

PS C:\Users\tojo2000> $list_of_strings -join "`t"


So to wrap this all up, let me give a real-world example. I had a SQL query that I wanted to run that would retrieve the SCCM information for a specific list of computers. I needed to update the list, and I had the computers in a file called machines.txt, with one name per line.

Here's how I slurped up the file to create the new query string:

$query = @"
SELECT * FROM v_R_System
WHERE Netbios_Name0
IN ('{0}')
"@ -f ((Get-Content machines.txt) -join "', '")

Saturday, July 4, 2009

Super Duper Over-Engineered Egg Timer


This was my submission for Event 10 Beginner of the 2009 Scripting Games this year. I usedPrimalForms to design the form and generate the boilerplate code. It's a really great tool.

I added the timer functionality myself. The Windows.Forms.Timer object is very simple. You tell it how frequent to set the ticks, set it to enabled or disabled, and call Start() to kick it off. The Timer itself doesn't keep track of how long it has been going, you do that by adding an event handler for the Tick event. You do that as seen on line 5 below, by calling add_tick() on the Timer object and passing it a script block that will be called every time the event fires. As far as I can tell this should work for any Windows.Forms object, calling add_event(), where "event" is the name of the event you are adding a handler for. The interval is in miliseconds, so in this case
the scriptblock $timer1_OnTick will be called once every second.

I went ahead and gathered the relevant lines in one place below so it's easier to see what I did. They're kind of spread around in the actual script.

  1. $timer1 = New-Object System.Windows.Forms.Timer
  2. $timer1.Enabled = $true
  3. $timer1.Start()
  4. $timer1.Interval = 1000
  5. $timer1.add_tick($timer1_OnTick)




Tuesday, June 30, 2009

Recursively Getting All Folder Sizes

This started out as my entry for Event 8 in the Microsoft Scripting Games 2009 (see more entries here), but it's useful, so I think I'll keep it. This function uses recursion to work its way down the directory tree and get all folders and their sizes, and outputs them as psobjects for easy sorting, etc. It's not the fastest thing in the world, but it does the trick. Make sure to check out the examples in the help documentation.





Tuesday, June 9, 2009

The 2009 Scripting Games!

So the 2009 Scripting Games have begun! There are 10 events this year, and the theme is decathalon. This is my first year participating. The next few posts will be my solutions. Check out the Script Center for updates and event details.

Sunday, May 31, 2009

Using Strict Mode with Set-PSDebug

If you've used Perl in the past, then you're probably familiar with "use strict" (if you've been using Perl without "use strict", then head over here Note: the scoping issues don't apply to PowerShell).

By default, PowerShell is very accommodating. If you tell it to echo the value of $chouderhead, it will happily echo... NOTHING! There is no variable called $chouderhead, you misspelled $chowderhead. PowerShell doesn't like to make waves, though, so it happily creates a new variable named $chouderhead and starts using it. This can lead to very hard-to-debug issues.

You can fix this By adding this line to your profile (or just typing it in at the prompt):

PS> Set-PSDebug -strict

Now if you try to use a variable that hasn't yet had a value assigned to it, you'll get an error like this:

PS> $chouderhead
The variable '$chouderhead' cannot be retrieved because it has not been set.
At line:1 char:13
+ $chouderhead <<<<
+ CategoryInfo : InvalidOperation: (chouderhead:Token) [], RuntimeException
+ FullyQualifiedErrorId : VariableIsUndefined

The error is annoying, but if you've ever wasted a half an hour wondering why your script isn't outputting what you thought it would, only to realize that on line 304 you accidentally used an 'm' instead of an 'n' in your variable name and how could I miss that, it's so stupid, and now I missed dinner, and my back hurts from crouching over my keyboard staring at the screen for too long and curse the day I was born! Why, oh, why didn't I just add 'PSDebug -strict' to my profile? Why?

But I digress...

Tuesday, May 19, 2009

Get-ChildItemRecurse Update

Someone named CrazyDave made an important update to the script I made yesterday. I was checking for the specific type System.IO.DirectoryInfo. The problem with this is, it unnecessarily limits my script to being used on files and folders. Get-ChildItem makes no such distinction. It can be used on any PSDrive.

So here is the corrected version: http://poshcode.org/1115 (highlighted line is the old one)