regexpowershell

How to find string that occurs between 3rd and 4th instances of a character


What I think I'm needing is an expression to exclude anything outside of the 3rd and 4th instances of a character, backlashes in this case. Does that sound right?

The problem I'm trying to solve is how to get the ShareName from a given UNC path in PowerShell.

Find: "Share01" in example source string:

\\FQDN\Share01\Directories\...\...\...\...

PowerShell's Split-Path is proving to be a bit limitied in this regard, and RegEx is ...hard!


Solution

  • Hm I'm really late to this party, but I will suggest an alternative: Use the [Uri] type:

    $unc = '\\FQDN\Share01\Directories\...\...\...\...'
    $upath = [Uri]$unc
    

    Testing if the path really is a UNC path:

    $upath.IsUnc
    

    Getting the Share

    $upath.Segments[1]            # Returns Share01/
    $upath.Segments[1].Trim('/')  # Trims the trailing /
    

    Or a one liner with no escaping or trimming:

    [System.IO.Path]::GetPathRoot($unc).Split('\')[-1]