Search for a file, across multiple volumes

Question:

I had recently, come across this post but it’s old and I figured ya’all would want me to start a new thread.

Basically, I’m writing a PS script for deploying WIMs. We map a UNC path as a mapped drive and then run a batch file that searches for specific files and creates a variable based on their paths. Once the variable is in place, the script continues – using said variable. A sample of the code in the batch file looks like this:

How does one duplicate something like that within PS? Normally, I’d hard-code the drive letter but if someone else maps a drive with a different letter, the script breaks. So, that’s why it searches through the drive letters…

Answer:

Here’s is one way to do that in PowerShell:

First you will make an Array with the Drive letters. By wrapping in either quotes or double quotes each letter will be a string and then use commas to separate each value so that the variable will be an array of strings.


Then use a foreach loop, which loops through each value of the array.

Then use an if statement for the test, and inside the if you can test if a folder or file exists with the Test-Path cmdlet. The ${} is so that I can put the variable inside the quotes and have it all be one string, without the parser getting confused by the :. Alternatively you could build the path with concatenation Test-Path $($Drive + ":\win10.wim") Where $() is a sub-expression to be evaluated first and then the + operator will concat the two strings.

Finally you can set a variable to equal to the $Drive variable when the if statement succeeds

Here’s what it looks like altogether:

Source:

Search for a file, across multiple volumes by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply