PowerShell

Retrieve host name and SMB share name (UNC Path) using PowerShell

Recently I got a request to retrieve host name and SMB share name using PowerShell. This is not new and indeed there are many ways to do it and I am sharing few I like. Consider the UNC PATH is like shown below

“\\SERVER\DEMO\SMBSHARE”

Our requirement is to retrieve “SERVER” and “SMBSHARE” – Well regex is optional to use and in many cases I avoid just to remove complexity of the code.

$smbshares = @("\\SERVER001\DEMO\SMBSHARE1" , "\\SERVER002\DEMO\SMBSHARE2")
foreach ($smbshare in $smbshares) {
    $result = [pscustomobject]@{
        HostName  = $smbshare -split "\\" | Where-Object {$_ -ne ""} | Select-Object -First 1
        FullPath  = $smbshare
        ShareName = ($smbshare -split "\\")[-1]
    }
    $result
}

Output is illustrated below!

Now, Let’s see how Split-Path helps us in UNC PATH – It’s very simple!

$smbshares = @("\\SERVER001\DEMO\SMBSHARE1" , "\\SERVER002\DEMO\SMBSHARE2")
foreach ($smbshare in $smbshares) {
    [pscustomobject]@{
        HOSTNAME = $smbshare -split "\\" | Where-Object {$_ -ne ""} | Select-Object -First 1
        Leaf     = Split-Path $smbshare -Leaf
    }
}

Know more information using

help Split-Path -Detailed

Here comes, another way to get HOST name from UNC path

(New-Object System.Uri -ArgumentList $smbshare).Host
$smbshares = @("\\SERVER001\DEMO\SMBSHARE1" , "\\SERVER002\DEMO\SMBSHARE2")
foreach ($smbshare in $smbshares) {
    [pscustomobject]@{
        HOST = (New-Object System.Uri -ArgumentList $smbshare).Host
        Leaf = Split-Path $smbshare -Leaf
    }
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *