Your basic ITPro blog... What's going on at work, what I'm interested in.

Monday, August 4, 2008

More to Learn

I had a small task today... Replace one drive letter with another in a bunch of text files. Specifically, I was moving my PowerShell scripts to a new drive and I wanted to change any references to the old location in my scripts to point to the new location.

First of all, this showed me how annoying it is to hard-code paths in scripts! There's gotta be a better way. (Hint: This is a solicitation for comments!)

Second, I ran into an oddity that I think is a result of some RegEx-related reality.

Here is the script that I ended up using to search all of my .PS1 files and replace the test string "c:\scripts" with "u:\scripts".

$files = Get-ChildItem -Recurse "U:\Copy of scripts\*\*.ps1"
foreach ($file in $files) {
    $content = (Get-Content $file) -replace "c:\\scripts", "u:\scripts"
    Set-Content $file $content
}
The oddity is the double-backslashes in the quoted text after the -replace. After reading a bit out RegEx (still and very new topic to me) it looks like the '\' is used as an escape character. So, to actually search for that character, you need to double them up.

2 comments:

/\/\o\/\/ said...

You can get to the scriptpath withing a script by using $myInvocation e.g. :

$path = split-path $myinvocation.MyCommand.Definition

Enjoy,
Greetings /\/\o\/\/

Derek Mangrum said...

I didn't know about that. Pretty cool! I have also been thinking about putting a variable definition in my profile... A constant called $ROOT_FOLDER or something. Then I can use this as a default location in my scripts. That way, I only need to change the path in one place if I ever want/need to move things again.

Additional Info

My photo
email: support (AT) mangrumtech (DOT) com
mobile: 480-270-4332