windowspowershellserveracl

PS - Get All SMB shares with permissions


I'm trying to get all smb shares on my windows server with all user permissions on them for inventory check.

This is what i have:

$Shares = Get-SmbShare

foreach($Share in $Shares)
{
    Get-SmbShareAccess -Name $Share.Name | Where-Object {$_.AccountName -Match "DOMAINNAME"} 
}

Which gets me all domain users with their shares and which access they have.

But it only shows name of folder. I would like its gonna show full path on the server (Not UNC)

And it would be exportable in csv format.

When i do:

$Shares = Get-SmbShare

foreach($Share in $Shares)
{
    Get-SmbShareAccess -Name $Share.Name | Where-Object {$_.AccountName -Match "PRAGUELOFTS"} | Export-Csv -Path C:\perms.csv
}

It only exports the last user.


Solution

  • You can define your output columns very precisely when you pass to Select-Object an array of hashes in this format: @{name="xyz"; expr={ calculated value }}.

    This way you can unify values from multiple sources, such as "share" and "share access", and manually calculated values, into one custom result.

    Get-SmbShare | Where-Object Special -eq $false | ForEach-Object {
        $share = $_
        $share | Get-SmbShareAccess | Where-Object AccountName -Match "DOMAINNAME" | Select-Object @(
            @{name="UncPath";   expr={ "\\" + $env:COMPUTERNAME + "\" + $share.Name }}
            @{name="LocalPath"; expr={ $share.Path }}
            @{name="Account";   expr={ $_.AccountName }}
            @{name="Type";      expr={ $_.AccessControlType }}
            @{name="Right";     expr={ $_.AccessRight }}
        )
    }
    

    You can then go on and pipe this into Export-Csv -Path C:\perms.csv.


    As for your second question - this

    foreach ($Share in $Shares)
    {
        Get-SmbShareAccess -Name $Share.Name | Export-Csv -Path C:\perms.csv
    }
    

    only gives you the last result in the CSV file because it literally says "for each share, write a CSV file". You keep overwriting the same file in every loop iteration.

    Collect all the results into a variable first

    $results = foreach ($Share in $Shares) {
        # ...
    }
    

    and then create the output file

    $results | Export-Csv -Path C:\perms.csv