Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase 12»»

PowerShell - Get Permissions Expand / Collapse
Author
Message
Posted Friday, May 18, 2012 9:06 AM
Grasshopper

GrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopper

Group: General Forum Members
Last Login: Tuesday, August 19, 2014 8:30 AM
Points: 19, Visits: 108

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()
Post #1302603
Posted Friday, May 18, 2012 5:36 PM


SSC-Dedicated

SSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-Dedicated

Group: General Forum Members
Last Login: Today @ 11:56 AM
Points: 36,959, Visits: 31,470
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."

(play on words) "Just because you CAN do something in T-SQL, doesn't mean you SHOULDN'T." --22 Aug 2013

Helpful Links:
How to post code problems
How to post performance problems
Post #1302915
Posted Monday, May 21, 2012 7:55 AM
Grasshopper

GrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopper

Group: General Forum Members
Last Login: Tuesday, August 19, 2014 8:30 AM
Points: 19, Visits: 108
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
Post #1303386
Posted Monday, May 21, 2012 9:22 AM


SSC Veteran

SSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC Veteran

Group: General Forum Members
Last Login: Monday, August 18, 2014 4:25 PM
Points: 277, Visits: 1,685
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

# ..
Post #1303458
Posted Tuesday, May 22, 2012 10:15 AM


SSCertifiable

SSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiable

Group: General Forum Members
Last Login: Today @ 8:34 AM
Points: 7,097, Visits: 12,601
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
Post #1304286
Posted Thursday, May 24, 2012 7:04 AM
Grasshopper

GrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopper

Group: General Forum Members
Last Login: Tuesday, August 19, 2014 8:30 AM
Points: 19, Visits: 108
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?
Post #1305800
Posted Thursday, May 24, 2012 7:26 AM


Valued Member

Valued MemberValued MemberValued MemberValued MemberValued MemberValued MemberValued MemberValued Member

Group: General Forum Members
Last Login: Yesterday @ 6:08 AM
Points: 60, Visits: 890
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
}
}

Post #1305819
Posted Thursday, May 24, 2012 7:43 AM


SSCertifiable

SSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiable

Group: General Forum Members
Last Login: Today @ 8:34 AM
Points: 7,097, Visits: 12,601
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
Post #1305842
Posted Thursday, May 24, 2012 7:50 AM


SSC Veteran

SSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC Veteran

Group: General Forum Members
Last Login: Monday, August 18, 2014 4:25 PM
Points: 277, Visits: 1,685
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
Post #1305851
Posted Wednesday, June 27, 2012 4:12 AM
Grasshopper

GrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopper

Group: General Forum Members
Last Login: Tuesday, August 19, 2014 8:30 AM
Points: 19, Visits: 108
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.
Post #1321774
« Prev Topic | Next Topic »

Add to briefcase 12»»

Permissions Expand / Collapse