PowerShell - Get Permissions

  • Hello,

    I am new to Powershell and I have been asked to get the SQL Server Database data path and insert this veriable into a script to gather permissions from the folders and inserts them into a csv file. I have insert my code so far below

    Any help would be much appriciated.

    Param (

    [STRING] $SQLSERVER = "Server, port"

    )

    $permsLogFile = "C:\Users\Output.txt"

    Write-Output "Start of the script" > $permsLogFile

    $SqlConnection = New-Object System.Data.SqlClient.SqlConnection

    $SqlConnection.ConnectionString = "Server=$SQLSERVER;Database=master;Integrated Security=True"

    $SqlCmd = New-Object System.Data.SqlClient.SqlCommand

    $SqlCmd.CommandText = "SELECT SUBSTRING(filename,1,CHARINDEX('A\master.',filename)) from master..sysdatabases WHERE name = 'master'"

    $SqlCmd.Connection = $SqlConnection

    $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter

    $SqlAdapter.SelectCommand = $SqlCmd

    $DataSet = New-Object System.Data.DataSet

    $SqlAdapter.Fill($DataSet)

    $networkPath = $DataSet.Tables[0]

    $subFolders = Get-ChildItem -Name $networkPath

    foreach ($Folder in $subFolders){

    $cmd = "cacls $networkPath\$Folder"

    Write-Output "Running Commamnd:" $networkPath >> $permsLogFile

    Invoke-Expression $cmd | Write-Output >> $permsLogFile}

    $SqlConnection.Close()

  • tomeaton12 (5/18/2012)


    Hello,

    I am new to Powershell and I have been asked to get the SQL Server Database data path and insert this veriable into a script to gather permissions from the folders and inserts them into a csv file. I have insert my code so far below

    Any help would be much appriciated.

    Param (

    [STRING] $SQLSERVER = "Server, port"

    )

    $permsLogFile = "C:\Users\Output.txt"

    Write-Output "Start of the script" > $permsLogFile

    $SqlConnection = New-Object System.Data.SqlClient.SqlConnection

    $SqlConnection.ConnectionString = "Server=$SQLSERVER;Database=master;Integrated Security=True"

    $SqlCmd = New-Object System.Data.SqlClient.SqlCommand

    $SqlCmd.CommandText = "SELECT SUBSTRING(filename,1,CHARINDEX('A\master.',filename)) from master..sysdatabases WHERE name = 'master'"

    $SqlCmd.Connection = $SqlConnection

    $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter

    $SqlAdapter.SelectCommand = $SqlCmd

    $DataSet = New-Object System.Data.DataSet

    $SqlAdapter.Fill($DataSet)

    $networkPath = $DataSet.Tables[0]

    $subFolders = Get-ChildItem -Name $networkPath

    foreach ($Folder in $subFolders){

    $cmd = "cacls $networkPath\$Folder"

    Write-Output "Running Commamnd:" $networkPath >> $permsLogFile

    Invoke-Expression $cmd | Write-Output >> $permsLogFile}

    $SqlConnection.Close()

    So does it work or is it giving errors??? If it's giving errors, what are they???

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

  • Hello,

    Thanks for the reply. This is the error I get once I execute the script in powershell:

    Get-ChildItem : Cannot find path 'C:\Users\System.Data.DataRow' because it does not exist.

    At C:\Users\Get-Permissions.ps1:18 char:28

    + $subFolders = Get-ChildItem <<<< -Name $networkPath

  • Wouldn't this do the same?

    $sName = "mysvr"

    $dbName = "mydb"

    $server = New-Object Microsoft.SqlServer.Management.Smo.Server($sName)

    $db = $server.Databases[$dbName]

    Get-ChildItem $db.PrimaryFilePath -Recurse | Where-Object{($_.psiscontainer)} | Get-Acl

    # ..

  • A solution using PrimaryFilePath will only account for the location of the primary data file for the database specified. If that database has multiple data files and one of those files is not located in the same path the solution, or if another database on the instance has files in a different location, then the script will not report all the required details.

    To be more complete I think you will want to iterate over the databases collection. Then for each database iterate over the filegroups collections. Within that iterate over the files collection and capture the database name and directory. Do the same for log files collection of database object.

    Once you have a complete list of where all data or log files reside per your instance you can use Get-ACL on each one and deliver the results.

    There are no special teachers of virtue, because virtue is taught by the whole community.
    --Plato

  • Thanks for the responses. I am unsure how to loop through each database to get the data file location. Any help on this would be appriciated.

    I would like to incorperate this into the code. The output from this is exactly what I need:

    $subFolders = Get-ChildItem -Name $networkPath

    foreach ($Folder in $subFolders){

    $cmd = "cacls $networkPath\$Folder"

    Write-Output "Running Commamnd: $cmd" >> $permsLogFile

    Invoke-Expression $cmd | Write-Output >> $permsLogFile}

    I need help with getting the database file path location for each database and run the path through the code above. Can anyone help?

  • You'll have to modify the output formating to fit your needs but this is a very verbose way to list files for all filegroups and databases.

    $sName = 'mysrr'

    $server = new-object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $sName

    foreach ($db in $server.Databases) {

    $db.name

    $fg = $db.FileGroups

    foreach ($group in $fg) {

    $group.Name

    foreach ($file in $group.Files) {

    $file.FileName

    }

    }

    foreach ($log in $db.LogFiles) {

    $log.FileName

    }

    }

  • What bruce provided is exactly what I described. You can use the Split-Path cmdlet to get the directory names as you move thorugh the collection of data and log files. Like this:

    Add-Type -AssemblyName Microsoft.SqlServer.Smo

    $instanceName = '.\STANDARD2008R2'

    $filePaths = @()

    $server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $instanceName

    foreach ($db in $server.Databases) {

    #$db.name

    $fg = $db.FileGroups

    foreach ($group in $fg) {

    #$group.Name

    foreach ($file in $group.Files) {

    $filePaths += (Split-Path -Path $file.FileName -Parent)

    }

    }

    foreach ($log in $db.LogFiles) {

    $filePaths += (Split-Path -Path $log.FileName -Parent)

    }

    }

    $filePaths = $filePaths | Select-Object -Unique

    # array now contains unique list of paths where data or log files exist

    $filePaths

    You can now tack your code onto the end of this script inputting the $filePaths array into your foreach loop to call cacls on each path.

    There are no special teachers of virtue, because virtue is taught by the whole community.
    --Plato

  • opc.three is correct the PrimaryFilePath won't help much here, apologies.

    However doing something like this

    $server = "svr"

    $sqlserver = new-object “Microsoft.SqlServer.Management.Smo.Server” $server

    Invoke-Sqlcmd -Query "SELECT a.name ,

    b.filename

    FROM sys.sysdatabases a

    INNER JOIN sys.sysaltfiles b ON a.dbid = b.dbid

    WHERE fileid <> 2

    ORDER BY name ;" -ServerInstance $sqlserver

    should be closer to get the data file paths..just don't forget to add the snapins required.

    And I also suggest using the Get-acl cmdlet.

    edit: typo

  • Hello,

    Sorry for the (very) late response I have been away. I have gone down a different road and I am currently stuck with this at the moment:

    [String] $inventoryinstance="Server\Instance"

    [String] $inventorydatabase="Database"

    $smoAssembly = [reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")

    if (!($smoVersion))

    { Set-Variable -name SmoVersion -value $smoAssembly.GetName().Version.Major -Scope Global -Option Constant

    -Description "SQLPSX variable" }

    [reflection.assembly]::LoadWithPartialName('Microsoft.SqlServer.SMOExtended') > $null

    #Get-DataFilePath

    function Get-DataFilePathList

    {

    $instance = New-Object ('Microsoft.SQLServer.Management.SMO.Server') $inventoryinstance

    $database = $instance.Databases[$inventorydatabase]

    #Param ($database)

    $result=$database.ExecuteWithResults("SELECT InstanceName, DBName, DataFilePath from

    dbo.tblDatabases")

    $result.Tables | foreach {$_.Rows}

    }

    Get-DataFilePathList | foreach {$_.DataFilePath | Write-Output}

    The output from this is the data file directories:

    D:\MSSQL10.DEV806MSSQL\MSSQL\DATA\master.mdf

    D:\MSSQL10.DEV806MSSQL\MSSQL\DATA\tempdb.mdf

    D:\MSSQL10.DEV806MSSQL\MSSQL\DATA\model.mdf

    D:\MSSQL10.DEV806MSSQL\MSSQL\DATA\MSDBData.mdf

    D:\MSSQL10.DEV806MSSQL\MSSQL\Data\DBA_Maint.mdf

    What's the best way to feed the output from this; $_.DataFilePath into a Foreach loop to get the permissions. (cacls/Get-Acl)

    Thanks in advance for the response.

  • Can anyone help with my previous comment?

    I need to be able to loop around each of the directories above to get the folder permissions. (cacls)

  • I didn't feel like learning your code because I provided a solution to get you to a list of directories. Picking up where my code left off you could do something like this:

    foreach($filePath in $filePaths)

    {

    }

    There are no special teachers of virtue, because virtue is taught by the whole community.
    --Plato

Viewing 12 posts - 1 through 11 (of 11 total)

You must be logged in to reply to this topic. Login to reply