|
|
|
Grasshopper
      
Group: General Forum Members
Last Login: Thursday, November 08, 2012 7:32 AM
Points: 12,
Visits: 74
|
|
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()
|
|
|
|
|
SSC-Dedicated
           
Group: General Forum Members
Last Login: Yesterday @ 9:57 PM
Points: 32,906,
Visits: 26,790
|
|
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."
For better, quicker answers on T-SQL questions, click on the following... http://www.sqlservercentral.com/articles/Best+Practices/61537/
For better answers on performance questions, click on the following... http://www.sqlservercentral.com/articles/SQLServerCentral/66909/
|
|
|
|
|
Grasshopper
      
Group: General Forum Members
Last Login: Thursday, November 08, 2012 7:32 AM
Points: 12,
Visits: 74
|
|
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
|
|
|
|
|
SSC Veteran
      
Group: General Forum Members
Last Login: Saturday, May 18, 2013 8:47 PM
Points: 237,
Visits: 1,215
|
|
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
# ..
|
|
|
|
|
SSCertifiable
       
Group: General Forum Members
Last Login: Today @ 7:55 AM
Points: 6,711,
Visits: 11,743
|
|
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
Believe you can and you're halfway there. --Theodore Roosevelt
Everything Should Be Made as Simple as Possible, But Not Simpler --Albert Einstein
The significant problems we face cannot be solved at the same level of thinking we were at when we created them. --Albert Einstein
1 apple is not exactly 1/8 of 8 apples. Because there are no absolutely identical apples. --Giordy
|
|
|
|
|
Grasshopper
      
Group: General Forum Members
Last Login: Thursday, November 08, 2012 7:32 AM
Points: 12,
Visits: 74
|
|
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?
|
|
|
|
|
SSC Rookie
      
Group: General Forum Members
Last Login: Tuesday, April 30, 2013 12:43 PM
Points: 46,
Visits: 722
|
|
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 } }
|
|
|
|
|
SSCertifiable
       
Group: General Forum Members
Last Login: Today @ 7:55 AM
Points: 6,711,
Visits: 11,743
|
|
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
Believe you can and you're halfway there. --Theodore Roosevelt
Everything Should Be Made as Simple as Possible, But Not Simpler --Albert Einstein
The significant problems we face cannot be solved at the same level of thinking we were at when we created them. --Albert Einstein
1 apple is not exactly 1/8 of 8 apples. Because there are no absolutely identical apples. --Giordy
|
|
|
|
|
SSC Veteran
      
Group: General Forum Members
Last Login: Saturday, May 18, 2013 8:47 PM
Points: 237,
Visits: 1,215
|
|
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
|
|
|
|
|
Grasshopper
      
Group: General Forum Members
Last Login: Thursday, November 08, 2012 7:32 AM
Points: 12,
Visits: 74
|
|
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.
|
|
|
|