Techibee.com

Pstip# Get Drive letter from a path

When working with paths it is often required to find out the drive letter of of a path. I generally do this using Dotnet methods, but just realized that PowerShell has a buil-in way to do this.

The Split-Path cmdlet can help you doing this. Look at the before sample code.

function Get-DriveLetterFromPath {            
[cmdletbinding()]            
param(            
[parameter(mandatory=$true)]            
[string]$Path,            
[switch]$Resolve            
)            

Try {            
    if(Split-Path -Path $Path -IsAbsolute) {            
        Split-Path -Path $Path -Qualifier -Resolve:$Resolve -ErrorAction Stop            
    }            

} catch {            
    Write-Host "Failed to get drive letter. Details : $_"            
}            

}

This function has one mandatory parameter name -Path and one optional parameter -Resolve. The -Resolve parameter will resolve the path that you are passing through Path parameter.

Hope you find this useful.

Exit mobile version