PowerShell ate my C: Drive

By | December 8, 2008

Or at least it nearly did.

I was working a script and because of a small typo very nearly lost most of the data on my C: drive.   It’s very easy to get wrong, so treat this as a cautionary tale.   The example below shows the error I made and the potential impact.  I’ve used the command line instead of my script in the example, but the effect is the same.

 First of all I set a variable to point to a folder off the root of the C: drive.  Then I cleared the contents of the folder using the variable together with the Remove-Item command.

 The screenshot below shows how to do this correctly.

powershell1.jpg

 Now look what happens when you mistype the name of the variable.  PowerShell basically ignores the variable and assumes you want to remove everything from the root of the drive. 

 powershell3.jpg

In my case only the fact that I didn’t use the  -recurse parameter saved me.  If I had used the -recurse parameter I would have lost everything except for items protected by the system.

Nasty.

One thought on “PowerShell ate my C: Drive

  1. Rick C

    “PowerShell basically ignores the variable and assumes you want to remove everything from the root of the drive.”

    No, it apparently tries to use the nonexistant value of a previously-undefined variable. It’s not pleasant, but I bet the same thing would happen under Unix if you tried this:

    rm -rf $foo/

    and foo wasn’t defined.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.