Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search for a file, across multiple volumes

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:

FOR %%i IN (D E F G H I J K L M N O P Q R S T U V W X Y Z) DO IF EXIST %%i:\Win10.wim SET _WIMLocation=%%i:

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...

like image 641
RKillcrazy Avatar asked Dec 11 '22 12:12

RKillcrazy


1 Answers

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.

$Drives = "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"

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

foreach ($Drive in $Drives) {

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.

   if (Test-Path "${Drive}:\Win10.wim") {

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

       $WIMLocation = $Drive
   }
}

Here's what it looks like altogether:

$Drives = "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"
foreach ($Drive in $Drives) {
   if (Test-Path "${Drive}:\Win10.wim") {
       $WIMLocation = $Drive
   }
}
like image 103
BenH Avatar answered Dec 21 '22 00:12

BenH