Deano
Deano

Reputation: 155

Powershell - Foreach, IF, Test-Path & Drive Variable

Hello Stackoverflow users,

I am noob at scripting and powershell.

I have the following script that gets all the drive letters on the host into a text file. I need to get the correct drive letter into a variable by performing a test-path. However it is not working. I know I am close but cannot get it to work. Does anyone know how to fix the script?

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 = "$_\Apps\NetprobeNT\"
$PathExists = Test-Path $Path

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

I think the following line is the problem

$Path = "$_\Apps\NetprobeNT\"

Any ideas on how to get this working?

This relates to PowerShell - drive variable for more information.

Thank you in advance.

Upvotes: 0

Views: 1156

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174475

As you point out yourself, this line is problematic:

$Path = "$_\Apps\NetprobeNT"

$_ is not defined in this scope, and so the resulting string just becomes "\Apps\NetprobeNT"

I would use Join-Path inside Where-Object (where $_ will refer to the current item in the pipeline):

To find the drives on which the folder exists, you can use Where-Object:

$CorrectDrive = $DeviceIDs |Where-Object {
    Test-Path $(Join-Path $_ "Apps\NetprobeNT") 
}
if(-not $CorrectDrive)
{
    $CorrectDrive = "C:"
}

That being said, your method for getting the DeviceID's is pretty convoluted - simply use Select-Object -ExpandProperty to grab the DeviceID value(s) and nothing else:

$DeviceIDs = Get-WmiObject Win32_LogicalDisk -Filter "DriveType=3 AND DeviceID!='C:'" |Select-Object -ExpandProperty DeviceID

Upvotes: 1

Related Questions