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:
1 2 |
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…
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.
1 2 |
$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.
1 2 |
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.
1 2 |
if (Test-Path "${Drive}:\Win10.wim") { |
Finally you can set a variable to equal to the
$Drive
variable when the if
statement succeeds
1 2 3 4 |
$WIMLocation = $Drive } } |
Here’s what it looks like altogether:
1 2 3 4 5 6 7 |
$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 } } |