Milan Nankov – Blog

Replacing multiple files with Windows PowerShell 2009/08/23

A couple of days ago I had to overwrite several files with another file and Windows PowerShell came to the rescue. At first it might seem that such task is trivial and it could easily be done in a minute using copy, paste, and Windows Explorer. That might be true if you are dealing with just a few files but if that is not case – if you are dealing with 50+ files which have different names – you should consider another approach.

I have created a simple PowerShell script that will search for specific files in a directory and after that replace those files with a single file, which is specified in the script. Here is the scripts:

This version of the script will search recursively for all PNG files in myFolder and overwrite every PNG file with new.png. 

The script is very simple but if you are new to PowerShell (like me) you might not be familiar with all of the script’s building blocks. The first one is the “get-childitem” cmdlet. It retrieves items from a specified location, which could be anything – directory, registry, etc. The recurse switch indicates that the scripts will retrieve files not only myFolder but also from all of its subfolders. Get-childitem accepts many parameters which allow you fine tune the search query but that is outside the scope of this post. Here you an find more information about get-childitem.

In its current form get-childitem will return all files in myFolder regardless of their extension. That is where another commandlet comes into play. Where-Object (alias where) cmdlet is used to filter results from other commandlets and I use it in the script to select files with a specific extension (in this case PNG files).

Finally the script goes through the list of all files in FilesToOverride and overwrites each file using the copy-item cmdlet.

Helpful links:

Guide to Windows PowerShell Cmdlets

Piping and the Pipeline in Windows PowerShell

Get-ChildItem Cmdlet

Where-Object Cmdlet

Copy-Item Cmdlet

Download File – Replace Files Script

  • http://- eternalrecluse

    I realise I am a little late to this article, however I have been searching for a mechanism to automate this exact type of task for ages and this works perfectly for me. Many thanks!

  • Milan

    I am glad that this post was helpful.

  • http://- Danny

    Thanks for the script Milan, works great for me.

  • Milan

    Thank you, Danny.