I once had to do a lot of repetitive type work, including generate SQL scripts for
every table in a database. So I developed a general purpose tool that is good for this type of work. I am including the tool, as is, and a sample run of the tool intended to
produce a series of grant commands for each table, and each category of database user.
My tool runs off of CSV files rather than off of the database directly. I found it fairly easy to generate CSV files and templates for a lot of different tasks. Your mileage may vary. Maybe you can start with this tool and adapt it to your needs.
Here is the tool, and a sample run.
<#
.SYNOPSIS
Generates multiple expansions of a template,
driven by data in a CSV file.
.DESCRIPTION
This function is a table driven template tool.
It generates output from a template and
a driver table. The template file contains plain
text and embedded variables. The driver table
(in a csv file) has one column for each variable,
and one row for each expansion to be generated.
#>
function Expand-csv {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)]
[string] $driver,
[Parameter(Mandatory=$true)]
[string] $template
)
Process
{
$xp = (Get-Content $template) -join "`r`n"
Import-Csv $driver | % {
$_.psobject.properties | % {Set-variable -name $_.name -value $_.value}
$ExecutionContext.InvokeCommand.ExpandString($xp)
}
}
}
# Now do a sample run of Expand-csv
# then display inputs and output
Expand-csv grants.csv grants.tmplt > grants.sql
get-content grants.tmplt
import-csv grants.csv
get-content grants.sql
Here is the result of running the above:
PS> C:\Users\David\Software\Powershell\test\sample.ps1
grant $privs
on $table
to $user;
privs table user
----- ----- ----
ALL Employees DBA
READ Employees Analyst
READ, WRITE Employees Application
ALL Departments DBA
READ Departments Analyst, Application
grant ALL
on Employees
to DBA;
grant READ
on Employees
to Analyst;
grant READ, WRITE
on Employees
to Application;
grant ALL
on Departments
to DBA;
grant READ
on Departments
to Analyst, Application;
PS>
In real life, I have the tool defined in my $profile file, so that it's available whenever I'm in powershell.
I'm not sure how well this applies to your case. This doesn't address the exact situation you describe, but you may be able to adapt the technique.