SQL Clone
SQLServerCentral is supported by Redgate
 
Log in  ::  Register  ::  Not logged in
 
 
 


PowerShell - Get Permissions


PowerShell - Get Permissions

Author
Message
SQLMan1
SQLMan1
SSC Veteran
SSC Veteran (293 reputation)SSC Veteran (293 reputation)SSC Veteran (293 reputation)SSC Veteran (293 reputation)SSC Veteran (293 reputation)SSC Veteran (293 reputation)SSC Veteran (293 reputation)SSC Veteran (293 reputation)

Group: General Forum Members
Points: 293 Visits: 201
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()
Jeff Moden
Jeff Moden
SSC Guru
SSC Guru (202K reputation)SSC Guru (202K reputation)SSC Guru (202K reputation)SSC Guru (202K reputation)SSC Guru (202K reputation)SSC Guru (202K reputation)SSC Guru (202K reputation)SSC Guru (202K reputation)

Group: General Forum Members
Points: 202775 Visits: 41943
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.
If you think its expensive to hire a professional to do the job, wait until you hire an amateur. -- Red Adair

Helpful Links:
How to post code problems
How to post performance problems
Forum FAQs
SQLMan1
SQLMan1
SSC Veteran
SSC Veteran (293 reputation)SSC Veteran (293 reputation)SSC Veteran (293 reputation)SSC Veteran (293 reputation)SSC Veteran (293 reputation)SSC Veteran (293 reputation)SSC Veteran (293 reputation)SSC Veteran (293 reputation)

Group: General Forum Members
Points: 293 Visits: 201
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
kiril.lazarov.77
kiril.lazarov.77
SSC Eights!
SSC Eights! (838 reputation)SSC Eights! (838 reputation)SSC Eights! (838 reputation)SSC Eights! (838 reputation)SSC Eights! (838 reputation)SSC Eights! (838 reputation)SSC Eights! (838 reputation)SSC Eights! (838 reputation)

Group: General Forum Members
Points: 838 Visits: 2248
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

# ..

Orlando Colamatteo
Orlando Colamatteo
SSC-Dedicated
SSC-Dedicated (36K reputation)SSC-Dedicated (36K reputation)SSC-Dedicated (36K reputation)SSC-Dedicated (36K reputation)SSC-Dedicated (36K reputation)SSC-Dedicated (36K reputation)SSC-Dedicated (36K reputation)SSC-Dedicated (36K reputation)

Group: General Forum Members
Points: 36732 Visits: 14411
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
SQLMan1
SQLMan1
SSC Veteran
SSC Veteran (293 reputation)SSC Veteran (293 reputation)SSC Veteran (293 reputation)SSC Veteran (293 reputation)SSC Veteran (293 reputation)SSC Veteran (293 reputation)SSC Veteran (293 reputation)SSC Veteran (293 reputation)

Group: General Forum Members
Points: 293 Visits: 201
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?
bruce 1565
bruce 1565
SSC-Addicted
SSC-Addicted (479 reputation)SSC-Addicted (479 reputation)SSC-Addicted (479 reputation)SSC-Addicted (479 reputation)SSC-Addicted (479 reputation)SSC-Addicted (479 reputation)SSC-Addicted (479 reputation)SSC-Addicted (479 reputation)

Group: General Forum Members
Points: 479 Visits: 1028
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
}
}


Orlando Colamatteo
Orlando Colamatteo
SSC-Dedicated
SSC-Dedicated (36K reputation)SSC-Dedicated (36K reputation)SSC-Dedicated (36K reputation)SSC-Dedicated (36K reputation)SSC-Dedicated (36K reputation)SSC-Dedicated (36K reputation)SSC-Dedicated (36K reputation)SSC-Dedicated (36K reputation)

Group: General Forum Members
Points: 36732 Visits: 14411
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
kiril.lazarov.77
kiril.lazarov.77
SSC Eights!
SSC Eights! (838 reputation)SSC Eights! (838 reputation)SSC Eights! (838 reputation)SSC Eights! (838 reputation)SSC Eights! (838 reputation)SSC Eights! (838 reputation)SSC Eights! (838 reputation)SSC Eights! (838 reputation)

Group: General Forum Members
Points: 838 Visits: 2248
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
SQLMan1
SQLMan1
SSC Veteran
SSC Veteran (293 reputation)SSC Veteran (293 reputation)SSC Veteran (293 reputation)SSC Veteran (293 reputation)SSC Veteran (293 reputation)SSC Veteran (293 reputation)SSC Veteran (293 reputation)SSC Veteran (293 reputation)

Group: General Forum Members
Points: 293 Visits: 201
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.
Go


Permissions

You can't post new topics.
You can't post topic replies.
You can't post new polls.
You can't post replies to polls.
You can't edit your own topics.
You can't delete your own topics.
You can't edit other topics.
You can't delete other topics.
You can't edit your own posts.
You can't edit other posts.
You can't delete your own posts.
You can't delete other posts.
You can't post events.
You can't edit your own events.
You can't edit other events.
You can't delete your own events.
You can't delete other events.
You can't send private messages.
You can't send emails.
You can read topics.
You can't vote in polls.
You can't upload attachments.
You can download attachments.
You can't post HTML code.
You can't edit HTML code.
You can't post IFCode.
You can't post JavaScript.
You can post emoticons.
You can't post or upload images.

Select a forum

































































































































































SQLServerCentral


Search