#PSTip Check if a folder is shared

Note: This tip requires PowerShell 3.0 or above.

The WMI class Win32_Share gives us the information about all network shares that exist on the local machine. Now, how do we check if a given folder is shared or not?

We can use the Win32_Share WMI class and query for a specific path! I have put this simple logic in a function.

Function IsFolderShared {
    [CmdletBinding()]
        param (
            [Parameter(
                ValueFromPipeLine,
                ValueFromPipelineByPropertyName,
                Mandatory
            )]
            [alias("FullName")]
            [String[]]$Path
        )

    Process {
       foreach ($Folder in $Path) {
           $WMIFolderPath = $Folder -replace '\\','\\'
           [PSCustomObject] @{
               "FolderPath" = $Folder
               "IsShared" = if (Get-CimInstance -Query "SELECT * FROM Win32_Share WHERE Path='$WMIFolderPath'") { $true } else { $false }
           }
       }
   }
}

isshared

About the author: Ravikanth C

Ravikanth is the founder and editor of the PowerShell Magazine. He is also a PowerShell MVP who works at Dell Inc. He blogs at http://www.ravichaganti.com/blog and you can follow him on Twitter @ravikanth.

Related Posts

%d bloggers like this: