Search code examples
powershellpowershell-2.0powershell-3.0powershell-4.0

How to define a format to find UNC path form a text file through PowerShell?


I want to fetch only the UNC path from a text file. The UNC path always ends with a character combined with number like P100, R101, E000, etc.

Sometimes the UNC path ends with some characters or symbols like

\\Localhost\apps\data\logs\P100###

I have tried different ways to fetch string starts with \\ and ends with P100 0R R101 etc. But, unable to achieve this task through PowerShell. Kindly help.

If the UNC path is \\Localhost\apps\data\logs\P100### or \\Localhost\apps\data\logs\P100Target, then I only need \\Localhost\apps\data\logs\P100 through my script. Whatever extra character or symbols must be eliminated.


Solution

  • Use a -replace operation:

    # Sample paths
    $paths = 
      '\\Localhost\apps\data\logs\Q102###',
      '\\App.Abc.test.test\apps\GS\Data\PKG-SCCM\GoogleChrome_19.012.20034_MUI_E100###',
      '\\App.Abc.test.test\apps\GS\Data\PKG-SCCM\Flashplayer_19.012.20034_MUI_R101[Target]'
    
    $paths -replace '(?<=\\[^\\]*[A-Z]\d{3})[^\\]+$'
    

    Note: Use -creplace instead of -replace to make matching case-sensitive, so that only uppercase (English) letters match. PowerShell is generally case-insensitive by default.

    To apply the above to file input (the individual lines from a file), use something like
    (Get-Content file.txt) -replace '...'

    The above yields (note that what comes after Q102, E100 and R101 in the input strings has been removed):

    \\Localhost\apps\data\logs\Q102
    \\App.Abc.test.test\apps\GS\Data\PKG-SCCM\GoogleChrome_19.012.20034_MUI_E100
    \\App.Abc.test.test\apps\GS\Data\PKG-SCCM\Flashplayer_19.012.20034_MUI_R101
    

    The -replace operation considers only the last component of the input paths, and therefore works with any path, as long as the last component is preceded by \.

    For an explanation of the regex passed to -replace and the ability to experiment with it, see this regex101.com page.