Test if a File Exists with Powershell

Another post for me that is simple and hopefully serves as an example for people trying to get blogging as#SQLNewBloggers.

Awhile back I wrote a PowerShell script (PoSh) to download the SQL Saturday XML files used for the Guidebook application. These contain a bunch of the information that I wanted to collect, transform, and keep around.

However the script wasn’t great. It basically looped a set number of times and re-downloaded the files. Not the more efficient solution, especially if I want this to run regularly.

One of the enhancements I wanted to make was check if the file exists, and if not, then download it. However, if it does exist, then I’ll skip the file. I know this means I don’t get updated files if schedules change, which is possible, but in that case, I can just delete the file from my desktop and go from there.

I made a quick search, and found a few links to the Test-Path cmdlet. Essentially you give this a file path and it returns true or false. Almost exactly what I need. This is what I added to my code:

if (Test-Path $DestinationFile) {

#do something

}

However I want to take action if the file doesn’t exist. In most languages, I’d add a ! in front to signify "not". However that doesn’t work in PoSh, just like > doesn’t mean greater than.

Another search showed me the -NOT operator. That’s what I need, but I can’t do this:

if (-NOT Test-Path $DestinationFile) {

#do something

}

Instead, I need to have a single expression for -NOT, which means more parenthesis. Not a big deal. I used this code:

if (-NOT (Test-Path $DestinationFile)) {

#do something

}

That worked great and now I only download the files I need. If I want to re-download (for newer events), I just delete those files and re-run the script.

SQLNewBlogger

This post came about when I started working on the script. It actually took longer to write this than find the solution, add it to code, and test it. That process was about 5 minutes.

This post took about 10 minutes to write. I also had a second post based on similar modifications to the script, so I’m did that in another 5 minutes.

References

A few of the links I used:

About way0utwest

Editor, SQLServerCentral
This entry was posted in Blog and tagged , , . Bookmark the permalink.

4 Responses to Test if a File Exists with Powershell

  1. rsterbal says:

    It might be nice to post this on the SQL Saturday Wiki – http://wiki.sqlsaturday.com/MainPage.ashx

    • way0utwest says:

      Where/why? I’m not sure what value this has for the SQL Sat organizers. It’s more a way to play with the data and start to see what is happening across events. I guess it could be an alert for a specific event, but is there something I’m missing?

  2. brianary says:

    Actually, “!” does mean “not” in PowerShell.

    help about_Logical_Operators
    https://technet.microsoft.com/library/hh847789.aspx

Comments are closed.