Execution Flow
The backup path must end with
\User-Db — this is enforced to prevent accidental writes to incorrect directories. If -CheckPreferredReplica is set and the instance is not the preferred AG backup node, the entire job aborts immediately with Status=AbortedNotPreferredReplica and no databases are backed up.Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| -SqlInstance | String | Optional | Target SQL Server instance. Default: $env:COMPUTERNAME. |
| -SqlCredential | PSCredential | Optional | SQL authentication credentials. |
| -Database | String[] | Optional | Specific database names. Ignored when -All is set. |
| -All | Switch | Optional | Back up all accessible user databases. |
| -BackupPath | String | Optional | Override backup directory. Must end with \User-Db. Defaults to server's BackupDirectory property. |
| -UseExcludeTable | Switch | Optional | Read master.dbo.sqm_BackupExclude and skip databases where IsActive=1 and IsOrphaned=0. |
| -CheckPreferredReplica | Switch | Optional | Abort if this instance is not the preferred AG backup replica (fn_hadr_backup_is_preferred_replica). |
| -MailTo | String | Optional | Email address for the backup report via Database Mail. Sent on failure by default. |
| -MailProfile | String | Optional | Database Mail profile name. Default: Default. |
| -MailOnSuccess | Switch | Optional | Also send mail on full success (not only on errors). |
| -EnableException | Switch | Optional | Throw exceptions immediately. |
Return Value
Returns PSCustomObject[] — one entry per database: SqlInstance, DatabaseName, BackupFile, Status (Success / Failed / WhatIfSkipped / AbortedNotPreferredReplica / NoDatabasesFound), Message.
Examples
Example 1 — All user databases, local instance
Invoke-sqmUserDatabaseBackup -All
Example 2 — Specific databases on remote server
Invoke-sqmUserDatabaseBackup -SqlInstance "SQL01" -Database "SalesDB", "InventoryDB"
Example 3 — AG-aware backup with exclude table and mail report
Invoke-sqmUserDatabaseBackup -SqlInstance "SQL01" -All -UseExcludeTable `
-CheckPreferredReplica -MailTo "dba@example.com" -MailOnSuccess
Example 4 — Custom path
Invoke-sqmUserDatabaseBackup -All -BackupPath "D:\Backup\User-Db"