Deano
Deano

Reputation: 155

PowerShell - Test-path

I have a script that gets the drives on the host and outputs to a text file. The text file will contain something like the below -

D:
E:
F:
G:

I need to test each drive for a path and, if true, assign it to a variable.

I have the following so far, but it is not working.

Get-WmiObject win32_logicaldisk -Filter "DriveType=3 AND DeviceID!='C:'" | Select DeviceID | Format-Table -HideTableHeaders > c:\DeviceID.txt -Force
$DeviceID = Get-Content C:\DeviceID.txt
$DeviceID | ForEach {$_.TrimEnd()} | ? {$_.trim() -ne '' } > c:\DeviceID.txt

$DeviceID = Get-Content C:\DeviceID.txt
$Path = "$DeviceID\Apps\NetprobeNT\"
$PathExists = Test-Path $Path

ForEach-Object ($DeviceID in $DeviceID)
{
    If ($PathExists -eq $True)
    {
        $DeviceDrive = $DeviceID}
    Else
    {
        $DeviceDrive = "C:"
    }
}

I have come across another method that works:

$Folder = "Apps\NetprobeNT"
Get-PSDrive | Where-Object {
    $_.root -match "[C-Z]:\\" -and (Test-Path $(Join-Path $_.root $Folder))
}

What is the best method to use?

Upvotes: 0

Views: 1114

Answers (2)

Djarid
Djarid

Reputation: 504

Wow, you are really doing it the hard way...

$drives = (Get-WmiObject Win32_Logicaldisk -Filter "DriveType=3 AND DeviceID!='C:'" | Select -ExpandProperty DeviceID).TrimEnd()

$deviceDrive = "C:"
foreach ($drive in $drives) {
    if (test-path "$drive\Apps\NetprobeNT\") {
        $deviceDrive = $drive
    }
}

For PowerShell V2:

$drives = Get-WmiObject Win32_Logicaldisk -Filter "DriveType=3 AND DeviceID!='C:'"

$deviceDrive = "C:"
foreach ($driveEntry in $drives) {
    $drive = $driveEntry.DeviceId
    if (test-path "$drive\Apps\NetprobeNT\") {
        $deviceDrive = $drive
    }
}

Upvotes: 1

Frode F.
Frode F.

Reputation: 54821

You're saving the result of Test-Path to the $PathExists-variable outside the loop, before $DeviceID exists. The result will always be false. The variable never changes so it will be false every time inside the loop. You need to run Test-Path inside the loop.

Also, you should avoid saving and reading the wmi-output to a file. Try:

$DeviceDrive = "C:"

Get-WmiObject win32_logicaldisk -Filter "DriveType=3 AND DeviceID!='C:'" |
Where-Object { Test-Path "$($_.DeviceID)\Apps\NetprobeNT\" } |
Foreach-Object {
    $DeviceDrive = $_.DeviceID
}

Upvotes: 2

Related Questions