Backup all databases fails on external server - sql-server

I have the following script to backup all databases from an SQL instance
This works perfectly from my local PC but when I run it on an external server it fails with the following:
master backup failed.
Exception calling "SqlBackup" with "1" argument(s): "Backup failed for Server 'SERVER2016'."
$SQLInstance = "Localhost"
$BackupFolder = "D:\Backups\"
$timeStamp = Get-Date -Format yyyy_MM_dd_HHmmss
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended") | Out-Null
$srv = New-Object ("Microsoft.SqlServer.Management.Smo.Server") $SQLInstance
$dbs = New-Object Microsoft.SqlServer.Management.Smo.Database
$dbs = $srv.Databases
foreach ($Database in $dbs) {
$Database.Name
$bk = New-Object ("Microsoft.SqlServer.Management.Smo.Backup")
$bk.Action = [Microsoft.SqlServer.Management.Smo.BackupActionType]::Database
$bk.BackupSetName = $Database.Name + "_backup_" + $timeStamp
$bk.Database = $Database.Name
$bk.CompressionOption = 1
$bk.MediaDescription = "Disk"
$bk.Devices.AddDevice($BackupFolder + "\" + $Database.Name + "_" + $timeStamp + ".bak", "File")
try {
$bk.SqlBackup($srv)
} catch {
$Database.Name + " backup failed."
$_.Exception.Message
}
}

Related

Invoke-SqlCmd generates an exception in foreach loop?

I am running 2 different sql query one after the other to get the details from database using Invoke-Sqlcmd but getting an exception.
The WriteObject and WriteError methods cannot be called from outside the overrides of the BeginProcessing, ProcessRecord, and EndProcessing methods, and they can only be called from within the same thread. Validate that the cmdlet makes these calls correctly
Script:
$ok = "true"
$serverName = $env:COMPUTERNAME
$query1 = "SELECT * FROM sys.server_audits WHERE name = 'Login'"
$query2 = "SELECT * FROM sys.dm_server_audit_status WHERE name = 'Login' AND status_desc = 'STARTED'"
try
{
Write-Host "Getting running Sql Server Instance (online)"
$sqlInstances = (Get-Service -Name MSSQL$* | Where-Object { $_.status -eq "Running" }).Name
$sqlInstancesCount = $sqlInstances.Count
Write-Host $eventID "$sqlInstancesCount Sql Server Instance found"
if($sqlInstancesCount)
{
foreach($item in $sqlInstances)
{
$count = 0
$instanceName = $item -replace "MSSQL\$", ""
$sqlInstanceFullname = Join-Path -Path $serverName -ChildPath "\" | Join-Path -ChildPath $instanceName
Write-Host "Sql Server instance fullname - $sqlInstanceFullname"
while($count -lt 3)
{
Write-Host "Clear existing connection."
[System.Data.SqlClient.SqlConnection]::ClearAllPools()
Write-Host "Executing query - $query1"
$result1 = (Invoke-Sqlcmd -Query $query1 -ServerInstance $sqlInstanceFullname)
Start-Sleep -Seconds 30
Write-Host "Clear existing connection."
[System.Data.SqlClient.SqlConnection]::ClearAllPools()
Write-Host "Executing query - $query2"
$result2 = (Invoke-Sqlcmd -Query $query2 -ServerInstance $sqlInstanceFullname)
if($null -eq $result1)
{
$message = "$serverName - The SQL Server [Login] does not exist."
$ok = "false"
$count = $count + 1
}
elseif($null -eq $result2)
{
$message = "$serverName - The SQL Server [Login] is disabled."
$ok = "false"
$count = $count + 1
}
else
{
$message = "SQL Login is enabled and running."
$count = 3
$ok = "true"
}
}
}
}
else
{
$ok = "false"
throw "$serverName - SQL Server Instances might be offline or not exist!"
}
}
catch
{
throw $_
}
I have tried enclosing Invoke-Sqlcmd in brackets but still getting same exception so is there a way to remove existing thread or close the connection before executing another query.

How to avoid system databases using SMO object in powershell?

How I can avoid System databases while taking backups using SMO object in Powershell
I am trying to take the all available databases excluding system databases.
param(
$serverName,
$backupDirectory,
$daysToStoreBackups
)
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoEnum") | Out-Null
$server = New-Object ("Microsoft.SqlServer.Management.Smo.Server") $serverName
$dbs = $server.Databases
foreach ($database in $dbs)
{
$dbName = $database.Name
$timestamp = Get-Date -format yyyy-MM-dd-HHmmss
$targetPath = $backupDirectory + "\" + $dbName + "_" + $timestamp + ".bak"
$smoBackup = New-Object ("Microsoft.SqlServer.Management.Smo.Backup")
$smoBackup.Action = "Database"
$smoBackup.BackupSetDescription = "Full Backup of " + $dbName
$smoBackup.BackupSetName = $dbName + " Backup"
$smoBackup.Database = $dbName
$smoBackup.MediaDescription = "Disk"
$smoBackup.Devices.AddDevice($targetPath, "File")
$smoBackup.SqlBackup($server)
"backed up $dbName ($serverName) to $targetPath"
}
Reference for the script is SMO Object Backup Script Link for PS
Change this
foreach ($database in $dbs)
To
foreach ($database in $dbs | where { $_.IsSystemObject -eq $False })
This should do the trick.

Copy SQL Server database with PowerShell script

I want to copy database within the same server to have a test database using the under code but it works fine the first run and then an error occur .I think that was a problem of the name of the destination database because i change the name of destination it works also .How can I proceed to override the destination database without renaming the destination.
Import-Module SQLPS -DisableNameChecking
#your SQL Server Instance Name
$SQLInstanceName = "DESKTOP-444"
$Server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $SQLInstanceName
#provide your database name which you want to copy
$SourceDBName = "test"
#create SMO handle to your database
$SourceDB = $Server.Databases[$SourceDBName]
#create a database to hold the copy of your source database
$CopyDBName = "$($SourceDBName)_copy"
$CopyDB = New-Object -TypeName Microsoft.SqlServer.Management.SMO.Database -ArgumentList $Server , $CopyDBName
$CopyDB.Create()
#Use SMO Transfer Class by specifying source database
#you can specify properties you want either brought over or excluded, when the copy happens
$ObjTransfer = New-Object -TypeName Microsoft.SqlServer.Management.SMO.Transfer -ArgumentList $SourceDB
$ObjTransfer.CopyAllTables = $true
$ObjTransfer.Options.WithDependencies = $true
$ObjTransfer.Options.ContinueScriptingOnError = $true
$ObjTransfer.DestinationDatabase = $CopyDBName
$ObjTransfer.DestinationServer = $Server.Name
$ObjTransfer.DestinationLoginSecure = $true
$ObjTransfer.CopySchema = $true
#if you wish to just generate the copy script
#just script out the transfer
$ObjTransfer.ScriptTransfer()
#When you are ready to bring the data and schema over,
#you can use the TransferData method
$ObjTransfer.TransferData()
I was able to run your code multiple times without any issues. The following is the slightly cleaned-up version (structural changes):
Import-Module SQLPS -DisableNameChecking
$SQLInstanceName = "(local)"
$SourceDBName = "sandbox"
$CopyDBName = "${SourceDBName}_copy"
$Server = New-Object -TypeName 'Microsoft.SqlServer.Management.Smo.Server' -ArgumentList $SQLInstanceName
$SourceDB = $Server.Databases[$SourceDBName]
$CopyDB = New-Object -TypeName 'Microsoft.SqlServer.Management.SMO.Database' -ArgumentList $Server , $CopyDBName
$CopyDB.Create()
$ObjTransfer = New-Object -TypeName Microsoft.SqlServer.Management.SMO.Transfer -ArgumentList $SourceDB
$ObjTransfer.CopyAllTables = $true
$ObjTransfer.Options.WithDependencies = $true
$ObjTransfer.Options.ContinueScriptingOnError = $true
$ObjTransfer.DestinationDatabase = $CopyDBName
$ObjTransfer.DestinationServer = $Server.Name
$ObjTransfer.DestinationLoginSecure = $true
$ObjTransfer.CopySchema = $true
$ObjTransfer.ScriptTransfer()
$ObjTransfer.TransferData()
What error did you get?
The one thing I noticed. If the cloned database already exists, the script will fail. You should get an exception up around the $CopyDB.Create() statement and probably another one when you go to copy the objects to the cloned database.
I'd either drop the database if it exists, or abort script execution if it exists.
EDIT
I was told to use the module SqlServer instead of the module SQLPS, because the latter had long been deprecated. And immediately after I have made the change, I noticed that it was now possible to create databases from a Microsoft.SqlServer.Management.SMO.Transfer object, which I was not managing before. I don't understand why, and it might even be unrelated and I was just lucky. The SqlServer package can be installed through the following command:
Install-Module -Name SqlServer -AllowClobber
Thus I am updating my answer with the working code, which is more readable, more elegant and more performant than my previous answer (at the bottom of this post).
$SQLInstanceName = $env:servername
$SourceDBName = $env:databasename
$SQLUser = $env:adminlogin
$SQLPassword = $env:adminPassword
Import-Module SqlServer -DisableNameChecking
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null;
Function IsNullOrEmpty([string]$val){
if ($val -eq $null -or $val -eq '') { $true }
else{ $false }
}
If (IsNullOrEmpty($SQLInstanceName)) {
$SQLInstanceName = $args[0]
}
If (IsNullOrEmpty($SourceDBName)) {
$SourceDBName = $args[1]
}
If (IsNullOrEmpty($SQLUser)) {
$SQLUser = $args[2]
}
If (IsNullOrEmpty($SQLPassword)) {
$SQLPassword = $args[3]
}
Try {
$Server = New-Object Microsoft.SqlServer.Management.Smo.Server($SQLInstanceName)
$DestinationDBName = "${SourceDBName}.Staging"
$SQLSecurePassword = ConvertTo-SecureString $SQLPassword -AsPlainText -Force
$Server.ConnectionContext.LoginSecure = $false
$Server.ConnectionContext.set_Login($SQLUser)
$Server.ConnectionContext.set_SecurePassword($SQLSecurePassword)
$SourceDB = $Server.Databases[$SourceDBName]
$ObjTransfer = New-Object Microsoft.SqlServer.Management.SMO.Transfer ($SourceDB)
$CopyDB = New-Object Microsoft.SqlServer.Management.SMO.Database ($Server, $DestinationDBName)
$CopyDB.Create()
# $ObjTransfer.CopyData = $false - Uncomment this line so that data is not copied across
$ObjTransfer.CopySchema = $true
$ObjTransfer.CopyAllTables = $true
$ObjTransfer.CopyAllDatabaseTriggers = $true
$ObjTransfer.Options.WithDependencies = $true
$ObjTransfer.Options.ContinueScriptingOnError = $true
$ObjTransfer.DestinationDatabase = $DestinationDBName
$ObjTransfer.DestinationServer = $SQLInstanceName
$ObjTransfer.DestinationPassword = $SQLPassword
$ObjTransfer.DestinationLogin = $SQLUser
$ObjTransfer.DestinationLoginSecure = $false
$ObjTransfer.TransferData()
}
Catch [System.Exception] {
# $_ is set to the ErrorRecord of the exception
if ($_.Exception.InnerException) {
Write-Error $_.Exception.InnerException.Message
} else {
Write-Error $_.Exception.Message
}
if($Server.Databases.Name -like $DestinationDBName) {
Write-Host "Dropping cloned database..."
# Call drop-db.ps1 to delete the stagingDB
Invoke-Command { .\drop-db.ps1 $SQLInstanceName $DestinationDBName $SQLUser $SQLPassword }
}
}
Finally {
if($Server) {
$Server.ConnectionContext.Disconnect()
}
}
I was having a similar error implementing this. Tried literally everything, it just wouldn't work. What did work for me, was generating a script through the ScriptTransfer method, create the new database and then apply the script to the new database through Invoke-SqlCmd. The code I am sharing can be invoked locally, by passing 4 arguments to the script in the following order:
Server Name
Database Name
Login
Password
And it can also be used on a pipeline. I am using it on Azure DevOps by setting those 4 arguments through a group variable.
I am appending .Staging to the source database name, and that's the name I give to the new database. If something fails along the way, I delete the new database, in case it has already been created.
$SQLInstanceName = $env:servername
$SourceDBName = $env:databasename
$SQLUser = $env:adminlogin
$SQLPassword = $env:adminPassword
Import-Module SQLPS -DisableNameChecking
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null;
Function IsNullOrEmpty([string]$val){
if ($val -eq $null -or $val -eq '') { $true }
else{ $false }
}
If (IsNullOrEmpty($SQLInstanceName)) {
$SQLInstanceName = $args[0]
}
If (IsNullOrEmpty($SourceDBName)) {
$SourceDBName = $args[1]
}
If (IsNullOrEmpty($SQLUser)) {
$SQLUser = $args[2]
}
If (IsNullOrEmpty($SQLPassword)) {
$SQLPassword = $args[3]
}
Try {
$Server = New-Object Microsoft.SqlServer.Management.Smo.Server($SQLInstanceName)
}
Catch [System.Exception] {
# $_ is set to the ErrorRecord of the exception
if ($_.Exception.InnerException) {
Write-Error $_.Exception.InnerException.Message
} else {
Write-Error $_.Exception.Message
}
}
Finally {
Try {
$StagingDBName = "${SourceDBName}.Staging"
$SQLSecurePassword = ConvertTo-SecureString $SQLPassword -AsPlainText -Force
$Server.ConnectionContext.LoginSecure = $false
$Server.ConnectionContext.set_Login($SQLUser)
$Server.ConnectionContext.set_SecurePassword($SQLSecurePassword)
$CreationScriptOptions = New-Object Microsoft.SqlServer.Management.SMO.ScriptingOptions
$CreationScriptOptions.ExtendedProperties= $true
$CreationScriptOptions.DRIAll= $true
$CreationScriptOptions.Indexes= $true
$CreationScriptOptions.Triggers= $true $CreationScriptOptions.ScriptBatchTerminator = $true
$CreationScriptOptions.IncludeHeaders = $true;
$CreationScriptOptions.ToFileOnly = $true
$CreationScriptOptions.IncludeIfNotExists = $true
$SourceDB = $Server.Databases[$SourceDBName]
$ObjTransfer = New-Object Microsoft.SqlServer.Management.SMO.Transfer ($SourceDB)
$ObjTransfer.options=$CreationScriptOptions # tell the transfer object of our preferences
$FilePath = Join-Path $PSScriptRoot "$($StagingDBName).sql"
$ObjTransfer.Options.Filename = $FilePath;
$ObjTransfer.ScriptTransfer()
$CopyDB = New-Object Microsoft.SqlServer.Management.SMO.Database ($Server, $StagingDBName)
$CopyDB.Create()
$auth=#{UserName=$SQLUser;Password=$SQLPassword}
Invoke-SqlCmd -InputFile $FilePath -ServerInstance $Server -Database $StagingDBName #Auth -Verbose
}
Catch [System.Exception] {
# $_ is set to the ErrorRecord of the exception
if ($_.Exception.InnerException) {
Write-Error $_.Exception.InnerException.Message
} else {
Write-Error $_.Exception.Message
}
if($Server.Databases.Name -like $StagingDBName) {
Write-Host "Dropping staging database..."
$auth=#{UserName=$SQLUser;Password=$SQLPassword}
Invoke-SqlCmd -ServerInstance $Server #Auth `
-Query "IF EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name ='$($StagingDBName)') `
BEGIN `
ALTER DATABASE [$($StagingDBName)] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; `
DROP DATABASE [$($StagingDBName)]; `
END;" `
-Verbose
}
}
Finally {
$Server.ConnectionContext.Disconnect()
}
}

Powershell backup script not making weekly backups

So i have the following code that should backup every database daily, weekly and monthly. The daily backup works fine but it doesnt seem to create a weekly or a monthly backup.
The database connection part of the script looks like:
$serverName = "."
$backupDirectory = "\\SERVER\BACKUP"
$daysToStoreDailyBackups = 7
$daysToStoreWeeklyBackups = 28
$monthsToStoreMonthlyBackups = 3
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoEnum") | Out-Null
$mySrvConn = new-object Microsoft.SqlServer.Management.Common.ServerConnection
$mySrvConn.ServerInstance=$serverName
$mySrvConn.LoginSecure = $false
$mySrvConn.Login = "sa"
$mySrvConn.Password = "myPAssword"
$server = new-object Microsoft.SqlServer.Management.SMO.Server($mySrvConn)
$dbs = $server.Databases
$startDate = (Get-Date)
"$startDate"
The daily and weekly part of the script looks like:
foreach ($database in $dbs | where {$_.IsSystemObject -eq $False})
{
$dbName = $database.Name
if ($dbName -ne "ReportServer" -and $dbName -ne "ReportServerTempDB")
{
$timestamp = Get-Date -format yyyy-MM-dd-HHmmss
$targetPath = $backupDirectory + "\" + $dbName + "_" + $timestamp + "_daily.bak"
$smoBackup = New-Object ("Microsoft.SqlServer.Management.Smo.Backup")
$smoBackup.Action = "Database"
$smoBackup.BackupSetDescription = "Full Backup of " + $dbName
$smoBackup.BackupSetName = $dbName + " Backup"
$smoBackup.Database = $dbName
$smoBackup.MediaDescription = "Disk"
$smoBackup.Devices.AddDevice($targetPath, "File")
$smoBackup.SqlBackup($server)
"backed up $dbName ($serverName) to $targetPath"
}
else
{
"$dbName backup skipped"
}
}
if([Int] (Get-Date).DayOfWeek -eq 0)
{
Get-ChildItem "$backupDirectory\*_weekly.bak" |? { $_.lastwritetime -le (Get-Date).AddDays(-$daysToStoreWeeklyBackups)} |% {Remove-Item $_ -force }
"removed all previous daily backups older than $daysToStoreWeeklyBackups days"
foreach ($database in $dbs | where { $_.IsSystemObject -eq $False})
{
if ($dbName -ne "ReportServer" -and $dbName -ne "ReportServerTempDB")
{
$dbName = $database.Name
$timestamp = Get-Date -format yyyy-MM-dd-HHmmss
$targetPath = $backupDirectory + "\" + $dbName + "_" + $timestamp + "_weekly.bak"
$smoBackup = New-Object ("Microsoft.SqlServer.Management.Smo.Backup")
$smoBackup.Action = "Database"
$smoBackup.BackupSetDescription = "Full Backup of " + $dbName
$smoBackup.BackupSetName = $dbName + " Backup"
$smoBackup.Database = $dbName
$smoBackup.MediaDescription = "Disk"
$smoBackup.Devices.AddDevice($targetPath, "File")
$smoBackup.SqlBackup($server)
"backed up $dbName ($serverName) to $targetPath"
}
else
{
"$dbName backup skipped"
}
}
}
I assumed it would create the weekly backup on Sunday, but that didn't happen.
In the daily block you have
$dbName = $database.Name
if ($dbName -ne "ReportServer" -and $dbName -ne "ReportServerTempDB")
{
but in the weekly block, you have
if ($dbName -ne "ReportServer" -and $dbName -ne "ReportServerTempDB")
{
$dbName = $database.Name
dbName is checked before it is set. If it fails the check, it's never set for any database.
If your code comes out of the daily block value left as "ReportServerTempDB", it will never pass the if test in the weekly block, and dbName will not change, so nothing will be backed up.
a) Move the $dbName = $database.Name assignment above the if
b) Or use $database.Name directly
c) Or don't have big chunks of copy-paste code which have to be the same, but can somehow end up different. Instead move that duplicate chunk to one function and call it from both places.

run query against multiple databases on different server

I'm working on a PowerShell script to run a query against multiple servers and databases were the idea is to dynamically add server and databases to an array and execute them.
Currently I'm stuck at the last part where everything is combined. I can add the servers but not the databases.
What I am trying to achieve: PowerShell script with MFP GUI to run a query against multiple MSSQL servers which all contain identical database (with different data) but the databases have different names like Sql_Data-Node1, SqlData-Node2, etc.
Problem I encounter: I managed to add the servers dynamically to an array and when I run a query I get the proper response. In this case I used the master database an I made it static (-database 'master'). When I try to do the same with the databases (add them to an array) I get an error:
Invoke-Sqlcmd : Cannot validate argument on parameter 'Database'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At C:\Users\master\Documents\MULTSCRIPT\MultiQueryV0.6.ps1:368 char:109
+ ... ame -Password $PassWord -ServerInstance $_[0] -Database $_[1] -Query ...
+ ~~~~~
+ CategoryInfo : InvalidData: (:) [Invoke-Sqlcmd], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand
My code:
#Create EMPTY ARRAY for Databases
$script:DBSet = New-Object System.Collections.ArrayList
#==========================================================================
$window.Master.add_Checked({
$script:Master = 'master' #Add IP to Variable
$script:DBSet.Add("$script:Master") #Add Variable to Array
[System.Object]$sender = $args[0]
[System.Windows.RoutedEventArgs]$e = $args[1]
})
$window.Master.add_Unchecked({
$script:Master = $null
$script:DBSet.Remove("$script:Master")
[System.Object]$sender = $args[0]
[System.Windows.RoutedEventArgs]$e = $args[1]
})
#==========================================================================
$window.DataNodes.add_Checked({
$script:DB01 = 'Database01'
$script:DBSet.Add("$script:DB01")
[System.Object]$sender = $args[0]
[System.Windows.RoutedEventArgs]$e = $args[1]
})
$window.DataNodes.add_Unchecked({
$script:DB01 = $null
$script:DBSet.Remove("$script:DB01")
[System.Object]$sender = $args[0]
[System.Windows.RoutedEventArgs]$e = $args[1]
})
#Create EMPTY ARRAY For Servers
$script:ServerAddress = New-Object System.Collections.ArrayList
#Add action to Checkbox====================================================
$window.DB00.add_Checked({
$script:SRV00 = '190.168.1.8' #Add IP to Variable
$script:ServerAddress.Add("$script:SRV00") #Add Variable to Array
[System.Object]$sender = $args[0]
[System.Windows.RoutedEventArgs]$e = $args[1]
})
$window.DB00.add_Unchecked({
$script:SRV00 = $null
$script:ServerAddress.Remove("$script:SRV00") #Remove Variable to Array
[System.Object]$sender = $args[0]
[System.Windows.RoutedEventArgs]$e = $args[1]
})
#==========================================================================
$window.DB01.add_Checked({
$script:SRV01 = '192.168.1.9'
$script:ServerAddress.Add("$script:SRV01")
[System.Object]$sender = $args[0]
[System.Windows.RoutedEventArgs]$e = $args[1]
})
$window.DB01.add_Unchecked({
$script:SRV01 = $null
$script:ServerAddress.Remove("$script:SRV01")
[System.Object]$sender = $args[0]
[System.Windows.RoutedEventArgs]$e = $args[1]
})
#Collect Credentials#======================================================
$credential = Get-Credential
$UserName = $credential.UserName.Replace('\','')
$PassWord = $credential.GetNetworkCredential().password
#Collect From Input Fields#================================================
$window.Button.add_Click({
$SQLQuery = $window.Query.Text.ToString()
$Server = $script:ServerAddress
$DatabaseSet = $script:DBSet
$instances = #( #($Server, $DatabaseSet) )
$instances | ForEach{
Invoke-Sqlcmd -AbortOnError `
-Username $UserName`
-Password $PassWord`
-ServerInstance $_[0]`
-Database $_[1]`
-Query $SQLQuery`
-QueryTimeout 30 |
Out-GridView -Title $_[0]
}
[System.Object]$sender = $args[0]
[System.Windows.RoutedEventArgs]$e = $args[1]
})
It seems that the following solution works.
Credit goes to:Mutiple Variables in Foreach Loop [Powershell]
$window.Button.add_Click(
{ $DataBase = $window.DataBase.Text.ToString()
$SQLQuery = $window.Query.Text.ToString()
$Server = $ServerAddress.getenumerator()
$Database = $DBSet.getenumerator()
while($Server.MoveNext() -and $Database.MoveNext()){
Invoke-Sqlcmd -AbortOnError -Username $UserName -Password $PassWord -ServerInstance $Server.Current -Database $Database.Current -Query $SQLQuery -QueryTimeout 30 | Out-GridView -Title $Server.Current}

Resources