[ { "Tags": [ "AG", "HA" ], "CommandName": "Add-DbaAgDatabase", "Name": "Add-DbaAgDatabase", "Author": "Chrissy LeMaire (@cl), netnerds.net | Andreas Jordan (@JordanOrdix), ordix.de", "Syntax": "Add-DbaAgDatabase [-SqlInstance] \u003cDbaInstanceParameter\u003e [-SqlCredential \u003cPSCredential\u003e] -AvailabilityGroup \u003cString\u003e -Database \u003cString[]\u003e [-Secondary \u003cDbaInstanceParameter[]\u003e] [-SecondarySqlCredential \u003cPSCredential\u003e] [-SeedingMode \u003cString\u003e] [-SharedPath \u003cString\u003e] [-UseLastBackup] [-AdvancedBackupParams \u003cHashtable\u003e] [-NoWait] [-SkipReuseSourceFolderStructure] [-MasterKeySecurePassword \u003cSecureString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nAdd-DbaAgDatabase [-AvailabilityGroup] \u003cString\u003e [-Secondary \u003cDbaInstanceParameter[]\u003e] [-SecondarySqlCredential \u003cPSCredential\u003e] -InputObject \u003cDatabase[]\u003e [-SeedingMode \u003cString\u003e] [-SharedPath \u003cString\u003e] [-UseLastBackup] [-AdvancedBackupParams \u003cHashtable\u003e] [-NoWait] [-SkipReuseSourceFolderStructure] [-MasterKeySecurePassword \u003cSecureString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.AvailabilityDatabase\nReturns one AvailabilityDatabase object per replica where the database was added. For example, adding one database to an AG with two replicas returns two objects - one for the primary and one for \r\neach secondary.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- AvailabilityGroup: Name of the availability group\r\n- LocalReplicaRole: Role of this replica (Primary or Secondary)\r\n- Name: Database name\r\n- SynchronizationState: Current synchronization state (NotSynchronizing, Synchronizing, Synchronized, Reverting, Initializing)\r\n- IsFailoverReady: Boolean indicating if the database is ready for failover\r\n- IsJoined: Boolean indicating if the database has joined the availability group\r\n- IsSuspended: Boolean indicating if data movement is suspended\nAdditional properties available (from SMO AvailabilityDatabase object):\r\n- DatabaseGuid: Unique identifier for the database\r\n- EstimatedDataLoss: Estimated data loss in seconds\r\n- EstimatedRecoveryTime: Estimated recovery time in seconds\r\n- FileStreamSendRate: Rate of FILESTREAM data being sent (bytes/sec)\r\n- GroupDatabaseId: Unique identifier for the database within the AG\r\n- ID: Internal object ID\r\n- IsAvailabilityDatabaseSuspended: Boolean indicating suspension state\r\n- IsDatabaseDiskHealthy: Boolean indicating if database disk health is good\r\n- IsDatabaseJoined: Boolean indicating database join state\r\n- IsInstanceDiskHealthy: Boolean indicating if instance disk health is good\r\n- IsInstanceHealthy: Boolean indicating overall instance health\r\n- IsPendingSecondarySuspend: Boolean indicating if secondary suspend is pending\r\n- LastCommitLsn: Last commit log sequence number\r\n- LastCommitTime: Timestamp of last committed transaction\r\n- LastHardenedLsn: Last hardened log sequence number\r\n- LastHardenedTime: Timestamp when last LSN was hardened\r\n- LastReceivedLsn: Last received log sequence number\r\n- LastReceivedTime: Timestamp when last LSN was received\r\n- LastRedoneLsn: Last redone log sequence number\r\n- LastRedoneTime: Timestamp when last LSN was redone\r\n- LastSentLsn: Last sent log sequence number\r\n- LastSentTime: Timestamp when last LSN was sent\r\n- LogSendQueue: Size of log send queue in KB\r\n- LogSendRate: Rate of log sending (bytes/sec)\r\n- LowWaterMarkForGhostCleanup: Low water mark LSN for ghost cleanup\r\n- Parent: Reference to parent AvailabilityGroup SMO object\r\n- RecoveryLsn: Recovery log sequence number\r\n- RedoQueue: Size of redo queue in KB\r\n- RedoRate: Rate of redo operations (bytes/sec)\r\n- SecondaryLagSeconds: Lag in seconds for secondary replica\r\n- State: SMO object state (Existing, Creating, Pending, etc.)\r\n- SuspendReason: Reason for suspension if database is suspended\r\n- Urn: Uniform Resource Name for the SMO object\r\n- UserAccess: User access state\nAll properties from the base SMO object are accessible even though only default properties are displayed without using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eAdd-DbaAgDatabase -SqlInstance sql2017a -AvailabilityGroup ag1 -Database db1, db2 -Confirm\nAdds db1 and db2 to ag1 on sql2017a. Prompts for confirmation.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2017a | Out-GridView -Passthru | Add-DbaAgDatabase -AvailabilityGroup ag1\nAdds selected databases from sql2017a to ag1\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbSharePoint -SqlInstance sqlcluster | Add-DbaAgDatabase -AvailabilityGroup SharePoint\nAdds SharePoint databases as found in SharePoint_Config on sqlcluster to ag1 on sqlcluster\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbSharePoint -SqlInstance sqlcluster -ConfigDatabase SharePoint_Config_2019 | Add-DbaAgDatabase -AvailabilityGroup SharePoint\nAdds SharePoint databases as found in SharePoint_Config_2019 on sqlcluster to ag1 on sqlcluster\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$adv_param = @{\n\u003e\u003e CompressBackup = $true\r\n\u003e\u003e FileCount = 3\r\n\u003e\u003e }\r\nPS C:\\\u003e $splat = @{\r\n\u003e\u003e SqlInstance = \u0027sql2017a\u0027\r\n\u003e\u003e AvailabilityGroup = \u0027ag1\u0027\r\n\u003e\u003e Database = \u0027db1\u0027\r\n\u003e\u003e Secondary = \u0027sql2017b\u0027\r\n\u003e\u003e SeedingMode = \u0027Manual\u0027\r\n\u003e\u003e SharedPath = \u0027\\\\FS\\Backup\u0027\r\n\u003e\u003e }\r\nPS C:\\\u003e Add-DbaAgDatabase @splat -AdvancedBackupParams $adv_param\nAdds db1 to ag1 on sql2017a and sql2017b. Uses compression and three files while taking the backups.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eAdd-DbaAgDatabase -SqlInstance sql2017a -AvailabilityGroup ag1 -Database db1 -NoWait\nAdds db1 to ag1 on sql2017a and returns immediately without waiting for seeding to complete on secondary replicas. Seeding will continue in the background.", "Description": "Adds databases to an Availability Group and handles the complete process from backup through synchronization. This command eliminates the manual steps typically required when expanding Availability Groups with new databases, automatically managing seeding modes, backup/restore operations, and replica synchronization.\n\nThe command executes a comprehensive five-step process for each database:\n* Step 1: Setting seeding mode if needed.\n - If -SeedingMode is used and the current seeding mode of the replica is not in the desired mode, the seeding mode of the replica is changed.\n - The seeding mode will not be changed back but stay in this mode.\n - If the seeding mode is changed to Automatic, the necessary rights to create databases will be granted.\n* Step 2: Running backup and restore if needed.\n - Action is only taken for replicas with a desired seeding mode of Manual and where the database does not yet exist.\n - If -UseLastBackup is used, the restore will be performed based on the backup history of the database.\n - Otherwise a full and log backup will be taken at the primary and those will be restored at the replica using the same folder structure.\n* Step 3: Add the database to the Availability Group on the primary replica.\n - This step is skipped, if the database is already part of the Availability Group.\n* Step 4: Add the database to the Availability Group on the secondary replicas.\n - This step is skipped for those replicas, where the database is already joined to the Availability Group.\n* Step 5: Wait for the database to finish joining the Availability Group on the secondary replicas.\n\nUse Test-DbaAvailabilityGroup with -AddDatabase to test if all prerequisites are met before running this command.\n\nFor custom backup and restore requirements, perform those operations with Backup-DbaDatabase and Restore-DbaDatabase in advance, ensuring the last log backup has been restored before running Add-DbaAgDatabase.", "Links": "https://dbatools.io/Add-DbaAgDatabase", "Synopsis": "Adds databases to an Availability Group with automated backup, restore, and synchronization handling.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The primary replica of the Availability Group. Server version must be SQL Server version 2012 or higher.", "", true, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "AvailabilityGroup", "Specifies the target Availability Group name where databases will be added. The AG must already exist and be configured.\r\nUse this to identify which existing Availability Group should receive the new database members.", "", true, "false", "", "" ], [ "Database", "Specifies which databases to add to the Availability Group. Accepts single database names, arrays, or wildcard patterns.\r\nUse this when you need to add specific databases rather than piping database objects from Get-DbaDatabase.", "", true, "false", "", "" ], [ "Secondary", "Specifies secondary replica instances to target for database addition. Auto-discovered if not specified.\r\nUse this when replicas use non-standard ports or when you want to limit the operation to specific secondary replicas rather than all replicas in the AG.", "", false, "false", "", "" ], [ "SecondarySqlCredential", "Authentication credentials for connecting to secondary replica instances when they require different credentials than the primary.\r\nUse this when secondary replicas are in different domains, use SQL authentication, or require service accounts with specific permissions for backup/restore operations.", "", false, "false", "", "" ], [ "InputObject", "Accepts database objects from pipeline input, typically from Get-DbaDatabase or Get-DbaDbSharePoint.\r\nUse this for workflow scenarios where you want to filter databases first, then pipe the results directly into the AG addition process.", "", true, "true (ByValue)", "", "" ], [ "SeedingMode", "Controls how database data is transferred to secondary replicas during AG addition. Valid values are \u0027Automatic\u0027 or \u0027Manual\u0027.\r\nAutomatic seeding transfers data directly over the network without requiring backup/restore operations, but needs sufficient network bandwidth and proper endpoint configuration.\r\nManual seeding uses traditional backup/restore through shared storage, giving you more control over timing and storage location but requiring accessible file shares.", "", false, "false", "", "Automatic,Manual" ], [ "SharedPath", "Specifies the UNC network path where backups are stored during manual seeding operations. Required when using Manual seeding mode.\r\nAll SQL Server service accounts from primary and secondary replicas must have read/write access to this location. Backup files remain on the share after completion for potential reuse or cleanup.", "", false, "false", "", "" ], [ "UseLastBackup", "Uses existing backup history instead of creating new backups for manual seeding. The most recent log backup must be newer than the most recent full backup.\r\nUse this when you have recent backups available and want to avoid taking additional backups, reducing backup storage requirements and time.", "", false, "false", "False", "" ], [ "AdvancedBackupParams", "Passes additional parameters to Backup-DbaDatabase as a hashtable when creating backups during manual seeding.\r\nUse this to control backup compression, file count, or other backup-specific settings like @{CompressBackup=$true; FileCount=4} for faster backup operations.", "", false, "false", "", "" ], [ "NoWait", "Skips waiting for the database seeding and synchronization to complete on secondary replicas (Step 5).\r\nThe underlying SQL command ALTER AVAILABILITY GROUP ... ADD DATABASE is immediate and does not wait for seeding to finish.\r\nUse this when you want the command to return immediately after adding the database to the AG, allowing seeding to continue in the background.\r\nThis is particularly useful in deployments where seeding can take a long time and you want to start using the environment before synchronization completes.", "", false, "false", "False", "" ], [ "SkipReuseSourceFolderStructure", "Prevents restores from using the source server\u0027s folder structure when restoring databases to secondary replicas.\r\nWhen enabled, Restore-DbaDatabase uses the replica\u0027s default data and log directories instead of attempting to replicate the primary\u0027s folder structure.\r\nThis is automatically set to true when the primary and replica servers run on different operating system platforms (e.g., Windows primary with Linux replica).", "", false, "false", "False", "" ], [ "MasterKeySecurePassword", "Password for creating or opening the database master key on secondary replicas when adding TDE-encrypted databases.\r\nWhen a database is protected by Transparent Data Encryption (TDE), the certificate used to protect the Database Encryption Key must exist on every secondary replica.\r\nProviding this parameter together with SharedPath allows the command to automatically copy the TDE certificate from the primary to each secondary replica.\r\nIf the secondary already has a master key, this password is used to create one if it is missing.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "Shows what would happen if the command were to run. No actions are actually performed.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before executing any changing operations within the command.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "AG", "HA" ], "CommandName": "Add-DbaAgListener", "Name": "Add-DbaAgListener", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Add-DbaAgListener [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-AvailabilityGroup] \u003cString[]\u003e] [[-Name] \u003cString\u003e] [[-IPAddress] \u003cIPAddress[]\u003e] [[-SubnetIP] \u003cIPAddress[]\u003e] [[-SubnetMask] \u003cIPAddress[]\u003e] [[-Port] \u003cInt32\u003e] [-Dhcp] [-Passthru] [[-InputObject] \u003cAvailabilityGroup[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.AvailabilityGroupListener\nReturns the created or configured Availability Group listener. By default, the listener object is returned after creation. When using -Passthru, the listener object is returned before creation for \r\nadditional configuration.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance hosting the Availability Group\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- AvailabilityGroup: Name of the Availability Group that owns this listener\r\n- Name: Network name of the listener that clients use for connections\r\n- PortNumber: TCP port number for client connections (default 1433)\r\n- ClusterIPConfiguration: WSFC cluster IP resource configuration details\nAdditional properties available (from SMO AvailabilityGroupListener object):\r\n- AvailabilityGroupListenerIPAddresses: Collection of IP address configurations for this listener (one per subnet in multi-subnet scenarios)\r\n- Urn: Unique resource name for programmatic identification\r\n- State: SMO object state (Existing, Creating, Pending, etc.)\r\n- Properties: Collection of object properties and their values\nAll properties from the base SMO AvailabilityGroupListener object are accessible via Select-Object * even though only default properties are displayed by default.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eAdd-DbaAgListener -SqlInstance sql2017 -AvailabilityGroup SharePoint -IPAddress 10.0.20.20\nCreates a listener on 10.0.20.20 port 1433 for the SharePoint availability group on sql2017.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sql2017 -AvailabilityGroup availabilitygroup1 | Add-DbaAgListener -Dhcp\nCreates a listener on port 1433 with a dynamic IP for the group1 availability group on sql2017.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eAdd-DbaAgListener -SqlInstance sql2017 -AvailabilityGroup SharePoint -IPAddress 10.0.20.20,10.1.77.77 -SubnetMask 255.255.252.0\nCreates a multi-subnet listener with 10.0.20.20 and 10.1.77.77, on two /22 subnets, on port 1433 for the SharePoint availability group on sql2017.", "Description": "Creates a network listener endpoint that provides a virtual network name and IP address for clients to connect to an Availability Group. The listener automatically routes client connections to the current primary replica, eliminating the need for applications to track which server is currently hosting the primary database.\n\nThis function supports both single-subnet and multi-subnet Availability Group configurations. You can specify static IP addresses for each subnet or use DHCP for automatic IP assignment. For multi-subnet deployments, specify multiple IP addresses and subnet masks to handle failover across geographically dispersed replicas.\n\nUse this when setting up new Availability Groups or when adding listeners to existing groups that don\u0027t have client connectivity configured yet. Without a listener, applications must connect directly to replica server names, which breaks during failover scenarios.", "Links": "https://dbatools.io/Add-DbaAgListener", "Synopsis": "Creates a network listener endpoint for an Availability Group to provide client connectivity", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.", "", false, "false", "", "" ], [ "SqlCredential", "Login to the SqlInstance instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)", "", false, "false", "", "" ], [ "AvailabilityGroup", "Specifies the name of the Availability Group that will receive the listener. Use this when connecting directly to a SQL Server instance rather than piping from Get-DbaAvailabilityGroup.\r\nRequired when using the SqlInstance parameter to identify which AG on the server needs client connectivity.", "", false, "false", "", "" ], [ "Name", "Specifies a custom network name for the listener that clients will use to connect. Defaults to the Availability Group name if not specified.\r\nUse this when you need a different DNS name than your AG name, such as for application connection strings that can\u0027t be changed.\r\nCannot be used when processing multiple Availability Groups in a single operation.", "", false, "false", "", "" ], [ "IPAddress", "Specifies one or more static IP addresses for the listener to use across different subnets. Each IP should correspond to a subnet where AG replicas are located.\r\nUse this for multi-subnet deployments or when DHCP is not available in your network environment.\r\nCannot be combined with the Dhcp parameter.", "", false, "false", "", "" ], [ "SubnetIP", "Specifies the network subnet addresses where the listener IPs will be configured. Auto-calculated from IPAddress and SubnetMask if not provided.\r\nUse this when you need explicit control over subnet configuration or when auto-calculation produces incorrect results.\r\nMust match the number of IP addresses specified, or provide a single subnet to apply to all IPs.", "", false, "false", "", "" ], [ "SubnetMask", "Defines the subnet mask for each listener IP address, controlling the network range. Defaults to 255.255.255.0 (/24).\r\nUse this when your network uses non-standard subnet sizes or when configuring multi-subnet listeners with different mask requirements.\r\nMust match the number of IP addresses, or provide a single mask to apply to all IPs.", "", false, "false", "255.255.255.0", "" ], [ "Port", "Specifies the TCP port number that clients will use to connect to the listener. Defaults to 1433.\r\nChange this when your environment requires non-standard SQL Server ports due to security policies or port conflicts with other services.", "", false, "false", "1433", "" ], [ "Dhcp", "Configures the listener to obtain IP addresses automatically from DHCP rather than using static IPs. Simplifies network configuration when DHCP reservations are managed centrally.\r\nCannot be used with IPAddress parameter and requires single-subnet AG configurations only.", "", false, "false", "False", "" ], [ "Passthru", "Returns the listener object without creating it on the server, allowing for additional configuration before calling Create().\r\nUse this when you need to set advanced properties not exposed by this function\u0027s parameters before committing the listener to SQL Server.", "", false, "false", "False", "" ], [ "InputObject", "Accepts Availability Group objects from Get-DbaAvailabilityGroup through the pipeline, eliminating the need to specify SqlInstance and AvailabilityGroup parameters.\r\nUse this approach when working with multiple AGs or when you need to filter AGs before creating listeners.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "Shows what would happen if the command were to run. No actions are actually performed.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before executing any changing operations within the command.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "AG", "HA" ], "CommandName": "Add-DbaAgReplica", "Name": "Add-DbaAgReplica", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Add-DbaAgReplica [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Name] \u003cString\u003e] [[-ClusterType] \u003cString\u003e] [[-AvailabilityMode] \u003cString\u003e] [[-FailoverMode] \u003cString\u003e] [[-BackupPriority] \u003cInt32\u003e] [[-ConnectionModeInPrimaryRole] \u003cString\u003e] [[-ConnectionModeInSecondaryRole] \u003cString\u003e] [[-SeedingMode] \u003cString\u003e] [[-Endpoint] \u003cString\u003e] [[-EndpointUrl] \u003cString[]\u003e] [-Passthru] [[-ReadOnlyRoutingList] \u003cString[]\u003e] [[-ReadonlyRoutingConnectionUrl] \u003cString\u003e] [[-Certificate] \u003cString\u003e] [-ConfigureXESession] [[-SessionTimeout] \u003cInt32\u003e] [-InputObject] \u003cAvailabilityGroup\u003e \r\n[-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.AvailabilityReplica\nReturns one AvailabilityReplica object for each replica added to the availability group.\nWhen -Passthru is specified, the replica object is returned before being added to the availability group, allowing for additional customization.\nWhen -Passthru is not specified, the replica is added to the availability group and the returned object includes added properties for display and context.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- AvailabilityGroup: Name of the availability group that contains this replica\r\n- Name: The name/display name of the availability replica\r\n- Role: Current role of the replica (Primary or Secondary)\r\n- RollupSynchronizationState: Synchronization state (NotSynchronizing, Synchronizing, Synchronized, Reverting, Initializing)\r\n- AvailabilityMode: Commit mode (SynchronousCommit or AsynchronousCommit)\r\n- BackupPriority: Backup preference priority (0-100)\r\n- EndpointUrl: Database mirroring endpoint URL for replica communication\r\n- SessionTimeout: Session timeout in seconds for failure detection\r\n- FailoverMode: Failover mode (Automatic or Manual)\r\n- ReadonlyRoutingList: Priority-ordered list of replicas for read-only routing\nAdditional properties available (from SMO AvailabilityReplica object):\r\n- ConnectionModeInPrimaryRole: Connection mode when this replica is primary (AllowAllConnections or AllowReadWriteConnections)\r\n- ConnectionModeInSecondaryRole: Connection mode when this replica is secondary (AllowNoConnections, AllowReadIntentConnectionsOnly, or AllowAllConnections)\r\n- ReadonlyRoutingConnectionUrl: Connection URL for read-only routing operations\r\n- SeedingMode: Database seeding mode (Automatic or Manual) - SQL Server 2016+\r\n- Parent: Reference to the parent AvailabilityGroup object\r\n- State: The state of the SMO object (Existing, Creating, Pending, etc.)\r\n- Urn: Uniform resource name of the replica\nAll properties from the base SMO AvailabilityReplica object are accessible even though only default properties are displayed without using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sql2017a -AvailabilityGroup SharePoint | Add-DbaAgReplica -SqlInstance sql2017b\nAdds sql2017b to the SharePoint availability group on sql2017a\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sql2017a -AvailabilityGroup SharePoint | Add-DbaAgReplica -SqlInstance sql2017b -FailoverMode Manual\nAdds sql2017b to the SharePoint availability group on sql2017a with a manual failover mode.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sql2017a -AvailabilityGroup SharePoint | Add-DbaAgReplica -SqlInstance sql2017b -EndpointUrl \u0027TCP://sql2017b.specialnet.local:5022\u0027\nAdds sql2017b to the SharePoint availability group on sql2017a with a custom endpoint URL.", "Description": "Adds a replica to an availability group on one or more SQL Server instances.\n\nAutomatically creates database mirroring endpoints if required.", "Links": "https://dbatools.io/Add-DbaAgReplica", "Synopsis": "Adds a replica to an availability group on one or more SQL Server instances.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.", "", true, "false", "", "" ], [ "SqlCredential", "Login to the target instances using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Name", "Sets the display name for the availability group replica being added. Defaults to the SQL Server instance\u0027s domain instance name.\r\nUse this when you need a custom replica name that differs from the server name, such as for clarity in multi-subnet scenarios.\r\nThis parameter is only supported when adding a replica to a single instance.", "", false, "false", "", "" ], [ "ClusterType", "Specifies the underlying clustering technology for the availability group. Only supported in SQL Server 2017 and above.\r\nUse \u0027Wsfc\u0027 for traditional Windows Server Failover Cluster setups, \u0027External\u0027 for Linux Pacemaker clusters, or \u0027None\u0027 for read-scale availability groups.\r\nDefaults to \u0027Wsfc\u0027 which handles most Windows-based high availability scenarios.\nThe default can be changed with:\r\nSet-DbatoolsConfig -FullName \u0027AvailabilityGroups.Default.ClusterType\u0027 -Value \u0027...\u0027 -Passthru | Register-DbatoolsConfig", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027AvailabilityGroups.Default.ClusterType\u0027 -Fallback \u0027Wsfc\u0027)", "Wsfc,External,None" ], [ "AvailabilityMode", "Controls how the replica commits transactions relative to the primary replica. SynchronousCommit waits for secondary confirmation before committing, ensuring zero data loss but higher latency.\r\nAsynchronousCommit commits immediately on primary without waiting for secondary confirmation, providing better performance but potential data loss during failover.\r\nDefaults to SynchronousCommit for maximum data protection.", "", false, "false", "SynchronousCommit", "AsynchronousCommit,SynchronousCommit" ], [ "FailoverMode", "Determines whether the replica can automatically fail over when the primary becomes unavailable. Automatic failover requires SynchronousCommit availability mode and provides seamless high \r\navailability.\r\nManual failover requires DBA intervention but works with both synchronous and asynchronous commit modes.\r\nDefaults to Automatic for immediate failover capabilities.", "", false, "false", "Automatic", "Automatic,Manual,External" ], [ "BackupPriority", "Sets the replica\u0027s preference for hosting backups within the availability group, ranging from 0-100 where higher values indicate higher priority.\r\nUse this to designate specific replicas for backup operations, such as setting secondary replicas to higher values to offload backup workloads from the primary.\r\nDefaults to 50, giving all replicas equal backup preference.", "", false, "false", "50", "" ], [ "ConnectionModeInPrimaryRole", "Controls which client connections are allowed when this replica is the primary. AllowAllConnections permits both read-write and read-only connections.\r\nAllowReadWriteConnections restricts access to connections that specify read-write intent, blocking read-only connection attempts.\r\nDefaults to AllowAllConnections for maximum compatibility with existing applications.", "", false, "false", "AllowAllConnections", "AllowAllConnections,AllowReadWriteConnections" ], [ "ConnectionModeInSecondaryRole", "Controls client access to secondary replicas for read operations. AllowNoConnections blocks all client connections to the secondary.\r\nAllowReadIntentConnectionsOnly permits only connections that specify ApplicationIntent=ReadOnly, ideal for reporting workloads.\r\nAllowAllConnections allows any client connection regardless of intent. Defaults to AllowNoConnections for security and performance.\nThe default can be changed with:\r\nSet-DbatoolsConfig -FullName \u0027AvailabilityGroups.Default.ConnectionModeInSecondaryRole\u0027 -Value \u0027...\u0027 -Passthru | Register-DbatoolsConfig", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027AvailabilityGroups.Default.ConnectionModeInSecondaryRole\u0027 -Fallback \u0027AllowNoConnections\u0027)", "AllowNoConnections,AllowReadIntentConnectionsOnly,AllowAllConnections,No,Read-intent only,Yes" ], [ "SeedingMode", "Controls how databases are initially synchronized on the secondary replica. Requires SQL Server 2016 or later.\r\nAutomatic seeding transfers data directly over the network without manual backup/restore operations, ideal for large databases or automated deployments.\r\nManual seeding requires you to manually backup databases on the primary and restore them on the secondary, providing more control over the timing and process.", "", false, "false", "", "Automatic,Manual" ], [ "Endpoint", "Specifies the name of the database mirroring endpoint to use for availability group communication. Automatically locates existing endpoints or creates one if needed.\r\nUse this when you need a custom endpoint name instead of the default \"hadr_endpoint\" that gets created automatically.\r\nEach SQL Server instance requires a database mirroring endpoint for Always On availability group replication.", "", false, "false", "", "" ], [ "EndpointUrl", "Overrides the default endpoint URL with custom network addresses for availability group communication. Defaults to the FQDN from the existing endpoint.\r\nRequired for special network configurations like multi-subnet deployments, NAT environments, or when replicas need specific IP addresses for cross-network communication.\r\nMust be in format \u0027TCP://system-address:port\u0027 with one entry per instance. When creating new endpoints, IPv4 addresses in the URL will be used for endpoint configuration.", "", false, "false", "", "" ], [ "Passthru", "Returns the replica object without actually creating it in the availability group, allowing for additional customization before final creation.\r\nUse this when you need to modify replica properties that aren\u0027t exposed as direct parameters before adding it to the availability group.", "", false, "false", "False", "" ], [ "ReadOnlyRoutingList", "Defines the priority order of replica server names for routing read-only connections when this replica serves as the primary. Requires SQL Server 2016 or later.\r\nUse this to direct reporting queries to specific secondary replicas, creating an ordered list like @(\u0027Server2\u0027, \u0027Server3\u0027) to balance read-only workloads.\r\nThis parameter is only supported when adding a replica to a single instance.", "", false, "false", "", "" ], [ "ReadonlyRoutingConnectionUrl", "Specifies the connection URL that clients use when connecting to this replica for read-only operations via read-only routing. Requires SQL Server 2016 or later.\r\nMust be in format \u0027TCP://system-address:port\u0027 and typically differs from the regular endpoint URL when using custom network configurations for read workloads.\r\nThis parameter is only supported when adding a replica to a single instance.", "", false, "false", "", "" ], [ "Certificate", "Configures certificate-based authentication for the database mirroring endpoint instead of Windows authentication. Requires the certificate name to exist on the SQL Server instance.\r\nUse this in environments where SQL Server instances run under different domain accounts or in workgroup configurations where Windows authentication isn\u0027t feasible.\r\nThe remote replica must have a matching certificate with the corresponding public key for secure communication.", "", false, "false", "", "" ], [ "ConfigureXESession", "Automatically configures the AlwaysOn_health extended events session to start with SQL Server, matching the behavior of the SSMS availability group wizard.\r\nUse this to enable automatic collection of availability group health data for monitoring and troubleshooting replica connectivity, failover events, and performance issues.\r\nThe session captures critical Always On events and is essential for proactive availability group management.", "", false, "false", "False", "" ], [ "SessionTimeout", "Sets the timeout period in seconds for detecting replica connectivity failures. The replica waits this long for ping responses before marking a connection as failed.\r\nLower values provide faster failure detection but may cause false failures under network stress. Higher values prevent false failures but delay failover detection.\r\nMicrosoft recommends keeping this at 10 seconds or higher for stable operations.", "", false, "false", "0", "" ], [ "InputObject", "Accepts availability group objects from Get-DbaAvailabilityGroup for pipeline operations. This is the target availability group where the replica will be added.\r\nUse pipeline scenarios like \u0027Get-DbaAvailabilityGroup -AvailabilityGroup \"AG1\" | Add-DbaAgReplica -SqlInstance server2\u0027 for streamlined replica management.", "", true, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "Shows what would happen if the command were to run. No actions are actually performed.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before executing any changing operations within the command.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Certificate", "Security" ], "CommandName": "Add-DbaComputerCertificate", "Name": "Add-DbaComputerCertificate", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Add-DbaComputerCertificate [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-SecurePassword] \u003cSecureString\u003e] [[-Certificate] \u003cX509Certificate2[]\u003e] [[-Path] \u003cString\u003e] [[-Store] \u003cString\u003e] [[-Folder] \u003cString\u003e] [[-Flag] \u003cString[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.Security.Cryptography.X509Certificates.X509Certificate2\nReturns one certificate object per imported certificate. When importing a PFX file containing a certificate chain, returns multiple objects - one for each certificate in the chain (root, \r\nintermediate, and leaf certificates).\nDefault display properties (via Select-DefaultView):\r\n- FriendlyName: The friendly name of the certificate (as configured in the certificate store)\r\n- DnsNameList: Collection of DNS names the certificate is valid for (Subject Alternative Names)\r\n- Thumbprint: The SHA-1 hash of the certificate, used as a unique identifier\r\n- NotBefore: DateTime when the certificate becomes valid\r\n- NotAfter: DateTime when the certificate expires\r\n- Subject: The distinguished name of the certificate subject (organization, common name, etc.)\r\n- Issuer: The distinguished name of the certificate issuer (certification authority)\nAdditional properties available on the X509Certificate2 object:\r\n- Archived: Boolean indicating if the certificate is marked as archived in the store\r\n- Extensions: Collection of X.509 extensions (key usage, extended key usage, etc.)\r\n- HasPrivateKey: Boolean indicating if the private key is available\r\n- IssuerName: X500DistinguishedName object for the issuer\r\n- PrivateKey: Cryptographic private key object (if HasPrivateKey is true)\r\n- PublicKey: Cryptographic public key object\r\n- SerialNumber: Serial number of the certificate\r\n- SignatureAlgorithm: Algorithm used to sign the certificate\r\n- SubjectName: X500DistinguishedName object for the subject\r\n- Version: X.509 version number\nUse Select-Object * to access all properties of the imported certificate objects.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eAdd-DbaComputerCertificate -ComputerName Server1 -Path C:\\temp\\cert.cer\nAdds the local C:\\temp\\cert.cer to the remote server Server1 in LocalMachine\\My (Personal).\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eAdd-DbaComputerCertificate -Path C:\\temp\\cert.cer\nAdds the local C:\\temp\\cert.cer to the local computer\u0027s LocalMachine\\My (Personal) certificate store.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eAdd-DbaComputerCertificate -Path C:\\temp\\cert.cer\nAdds the local C:\\temp\\cert.cer to the local computer\u0027s LocalMachine\\My (Personal) certificate store.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eAdd-DbaComputerCertificate -ComputerName sql01 -Path C:\\temp\\sql01.pfx -Confirm:$false -Flag NonExportable\nAdds the local C:\\temp\\sql01.pfx to sql01\u0027s LocalMachine\\My (Personal) certificate store and marks the private key as non-exportable. Skips confirmation prompt.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$password = Read-Host \"Enter the SSL Certificate Password\" -AsSecureString\nPS C:\\\u003e Add-DbaComputerCertificate -ComputerName sql01 -Path C:\\cert\\fullchain.pfx -SecurePassword $password\r\nPS C:\\\u003e Get-DbaComputerCertificate -ComputerName sql01 | Where-Object Subject -match \"letsencrypt\" | Set-DbaNetworkCertificate -SqlInstance sql01\nImports a Let\u0027s Encrypt certificate with the full chain (including intermediate certificates) from a PFX file, then configures SQL Server to use it. The full chain import ensures that \r\nSet-DbaNetworkCertificate can properly set permissions on the certificate.", "Description": "Imports X.509 certificates (including password-protected .pfx files with private keys) into the specified Windows certificate store on one or more computers. This function is essential for SQL Server TLS/SSL encryption setup, Availability Group certificate requirements, and Service Broker security configurations.\n\nWhen importing PFX files, the function imports the entire certificate chain, including intermediate certificates. This ensures proper certificate validation and prevents issues when using certificates with Set-DbaNetworkCertificate or other certificate-dependent operations.\n\nThe function handles both certificate files from disk and certificate objects from the pipeline, supports remote installation via PowerShell remoting, and allows you to control import behavior through various flags like exportable/non-exportable private keys. By default, certificates are installed to the LocalMachine\\My (Personal) store with exportable and persistent private keys, which is the standard location for SQL Server service certificates.", "Links": "https://dbatools.io/Add-DbaComputerCertificate", "Synopsis": "Imports X.509 certificates into the Windows certificate store on local or remote computers.", "Availability": "Windows only", "Params": [ [ "ComputerName", "The target computer or computers where certificates will be installed. Accepts server names, FQDNs, or IP addresses.\r\nUse this when installing certificates on remote SQL Server hosts or cluster nodes. Defaults to localhost when not specified.", "", false, "false", "$env:COMPUTERNAME", "" ], [ "Credential", "Allows you to login to $ComputerName using alternative credentials.", "", false, "false", "", "" ], [ "SecurePassword", "The password for encrypted certificate files (.pfx files with private keys). Required when importing password-protected certificates.\r\nUse this when installing SSL certificates or Service Broker certificates that were exported with password protection.", "Password", false, "false", "", "" ], [ "Certificate", "A certificate object from the pipeline or PowerShell variable. Accepts X509Certificate2 objects from Get-ChildItem Cert:\\ or other certificate commands.\r\nUse this when you already have certificate objects loaded in memory rather than reading from disk files.", "", false, "true (ByValue)", "", "" ], [ "Path", "The local file path to the certificate file (.cer, .crt, .pfx, .p12). The file must be accessible from the machine running the command.\r\nSpecify this when installing certificates from files on disk, commonly used for SSL certificates or custom CA certificates.", "", false, "false", "", "" ], [ "Store", "The certificate store location where certificates will be installed. Options are LocalMachine (system-wide) or CurrentUser (user-specific).\r\nUse LocalMachine for SQL Server service certificates and system certificates that need to be available to services. Defaults to LocalMachine.", "", false, "false", "LocalMachine", "" ], [ "Folder", "The certificate store folder within the specified store. Common folders include My (Personal), Root (Trusted Root), and CA (Intermediate).\r\nUse My for SQL Server SSL certificates and Service Broker certificates. Defaults to My which is the Personal certificate store.", "", false, "false", "My", "" ], [ "Flag", "Controls how certificate private keys are stored and accessed in the Windows certificate store. Determines security and accessibility characteristics.\r\nUse NonExportable for production SQL Server certificates to prevent private key extraction. Use Exportable when you need to back up or migrate certificates.\nDefaults to: Exportable, PersistKeySet\n EphemeralKeySet\r\n The key associated with a PFX file is created in memory and not persisted on disk when importing a certificate.\n Exportable\r\n Imported keys are marked as exportable.\n NonExportable\r\n Explicitly mark keys as nonexportable.\n PersistKeySet\r\n The key associated with a PFX file is persisted when importing a certificate.\n UserProtected\r\n Notify the user through a dialog box or other method that the key is accessed. The Cryptographic Service Provider (CSP) in use defines the precise behavior. NOTE: This can only be used when you \r\nadd a certificate to localhost, as it causes a prompt to appear.", "", false, "false", "@(\"Exportable\", \"PersistKeySet\")", "EphemeralKeySet,Exportable,PersistKeySet,UserProtected,NonExportable" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Storage", "Data", "File", "FileGroup" ], "CommandName": "Add-DbaDbFile", "Name": "Add-DbaDbFile", "Author": "the dbatools team + Claude", "Syntax": "Add-DbaDbFile [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-FileGroup] \u003cString\u003e] [[-FileName] \u003cString\u003e] [[-Path] \u003cString\u003e] [[-Size] \u003cInt32\u003e] [[-Growth] \u003cInt32\u003e] [[-MaxSize] \u003cInt32\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.DataFile\nReturns one DataFile object for each file successfully added to the specified filegroup. When adding files to multiple databases, one DataFile object is returned per database.\nCommon properties:\r\n- Name: The logical name of the data file as specified in the FileName parameter\r\n- FileName: The physical path to the file on disk\r\n- Size: The initial size of the file in kilobytes (KB) - set based on the Size parameter multiplied by 1024. Not set for memory-optimized filegroups.\r\n- Growth: The file growth increment in kilobytes (KB) - set based on the Growth parameter multiplied by 1024. Not set for memory-optimized filegroups.\r\n- GrowthType: The type of growth (KB or Percent). Set to \"KB\" for standard data files. Not set for memory-optimized filegroups.\r\n- MaxSize: The maximum size the file can grow to in kilobytes (KB) - set to -1 (unlimited) by default, or based on the MaxSize parameter multiplied by 1024. Not set for memory-optimized filegroups.\r\n- Parent: The FileGroup object that contains this file\r\n- IsPrimaryFile: Boolean indicating if this is the primary data file for the database\r\n- IsReadOnly: Boolean indicating if the file is marked as read-only\r\n- IsOffline: Boolean indicating if the file is offline\nAdditional properties available from SMO DataFile object:\r\n- ID: Unique identifier for the file\r\n- AvailableSpace: Available space in the file in bytes\r\n- UsedSpace: Space currently used by data in the file in bytes\r\n- BytesReadFromDisk: Total bytes read from the file since SQL Server started\r\n- BytesWrittenToDisk: Total bytes written to the file since SQL Server started\r\n- NumberOfDiskReads: Total number of read operations on the file\r\n- NumberOfDiskWrites: Total number of write operations on the file\r\n- VolumeFreeSpace: Free space available on the volume containing the file in bytes\r\n- IsReadOnlyMedia: Boolean indicating if the file\u0027s media is read-only\r\n- IsSparse: Boolean indicating if the file is a sparse file\r\n- State: The current state of the SMO object (Existing, Creating, Pending, etc.)\nAll properties are accessible via Select-Object * or by referencing the property directly on the returned object.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eAdd-DbaDbFile -SqlInstance sql2016 -Database TestDb -FileGroup HRFG1 -FileName \"HRFG1_data1\"\nAdds a new data file named HRFG1_data1 to the HRFG1 filegroup in the TestDb database using default size and growth settings.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eAdd-DbaDbFile -SqlInstance sql2016 -Database TestDb -FileGroup dbatools_inmem -FileName \"inmem_container\" -Path \"C:\\Data\\inmem\"\nAdds a memory-optimized container to the dbatools_inmem MemoryOptimizedDataFileGroup. For memory-optimized filegroups, the Path should be a directory.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eAdd-DbaDbFile -SqlInstance sql2016 -Database TestDb -FileGroup Secondary -FileName \"Secondary_data2\" -Size 512 -Growth 128 -MaxSize 10240\nAdds a new 512MB data file with 128MB growth increments and a maximum size of 10GB to the Secondary filegroup.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2016 -Database TestDb | Add-DbaDbFile -FileGroup HRFG1 -FileName \"HRFG1_data1\"\nPipes the TestDb database and adds a new file to the HRFG1 filegroup using pipeline input.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eAdd-DbaDbFile -SqlInstance sql2016 -Database TestDb -FileGroup HRFG1 -FileName \"HRFG1_data1\" -Path \"E:\\SQLData\\TestDb_HRFG1_data1.ndf\"\nAdds a new data file with a custom path and filename to the HRFG1 filegroup.", "Description": "Adds new data files (.mdf or .ndf) to existing filegroups in SQL Server databases. This is essential after creating new filegroups (especially MemoryOptimizedDataFileGroup for In-Memory OLTP) because filegroups cannot store data until they contain at least one file. The function supports all filegroup types including standard row data, FileStream, and memory-optimized storage, with automatic path resolution to SQL Server default data directories when no explicit path is specified.", "Links": "https://dbatools.io/Add-DbaDbFile", "Synopsis": "Adds data files to existing filegroups in SQL Server databases.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function\r\nto be executed against multiple SQL Server instances.", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies the database(s) containing the filegroup where the file will be added. Supports multiple database names for bulk operations.\r\nUse this when you need to add files to the same filegroup across multiple databases for consistency.", "", false, "false", "", "" ], [ "FileGroup", "Specifies the name of the filegroup where the new file will be added. The filegroup must already exist in the database.\r\nThis is typically used after creating a new filegroup with New-DbaDbFileGroup, especially for MemoryOptimizedDataFileGroup which requires files before use.", "", false, "false", "", "" ], [ "FileName", "Sets the logical name for the new file being created. This name is used within SQL Server to reference the file.\r\nIf not specified, a name will be auto-generated based on the database and filegroup names to ensure uniqueness.", "", false, "false", "", "" ], [ "Path", "Specifies the full physical path where the file will be created on disk, including the filename and extension (.ndf for data files).\r\nIf not specified, the file will be placed in the SQL Server default data directory with an auto-generated filename.\r\nFor MemoryOptimizedDataFileGroup, the path should point to a directory (not a file) where the container will be created.", "", false, "false", "", "" ], [ "Size", "Sets the initial size of the file in megabytes (MB). Defaults to 128MB if not specified.\r\nUse larger values for high-volume databases or smaller values for development/test databases to optimize storage allocation.\r\nFor MemoryOptimizedDataFileGroup, this parameter is ignored as memory-optimized filegroups manage their own sizing.", "", false, "false", "128", "" ], [ "Growth", "Specifies the file growth increment in megabytes (MB). Defaults to 64MB if not specified.\r\nThis controls how much the file expands when it runs out of space, with fixed-size growth preferred over percentage-based for predictable space management.\r\nFor MemoryOptimizedDataFileGroup, this parameter is ignored as memory-optimized filegroups do not use auto-growth settings.", "", false, "false", "64", "" ], [ "MaxSize", "Sets the maximum size the file can grow to in megabytes (MB). Defaults to unlimited (-1) if not specified.\r\nUse this to prevent runaway file growth and protect disk space, particularly important on shared storage or systems with limited capacity.\r\nFor MemoryOptimizedDataFileGroup, this parameter is ignored.", "", false, "false", "-1", "" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase for pipeline operations. This enables you to filter databases first, then add files to the selected ones.\r\nUseful when working with multiple databases that match specific criteria rather than specifying database names directly.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "Shows what would happen if the command were to run. No actions are actually performed.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before executing any changing operations within the command.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Mirroring", "Mirror", "HA" ], "CommandName": "Add-DbaDbMirrorMonitor", "Name": "Add-DbaDbMirrorMonitor", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Add-DbaDbMirrorMonitor [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance where the mirroring monitor was successfully added.\nProperties:\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- MonitorStatus: Status of the operation - displays \"Added\" when the mirror monitoring job is successfully created", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eAdd-DbaDbMirrorMonitor -SqlInstance sql2008, sql2012\nCreates a database mirroring monitor job that periodically updates the mirroring status for every mirrored database on sql2008 and sql2012.", "Description": "Creates a database mirroring monitor job that periodically updates the mirroring status for every mirrored database on the server instance.\n\nBasically executes sp_dbmmonitoraddmonitoring.", "Links": "https://dbatools.io/Add-DbaDbMirrorMonitor", "Synopsis": "Creates a database mirroring monitor job that periodically updates the mirroring status for every mirrored database on the server instance.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "Shows what would happen if the command were to run. No actions are actually performed.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before executing any changing operations within the command.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Role", "User" ], "CommandName": "Add-DbaDbRoleMember", "Name": "Add-DbaDbRoleMember", "Author": "Ben Miller (@DBAduck)", "Syntax": "Add-DbaDbRoleMember [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-Role] \u003cString[]\u003e] [-Member] \u003cString[]\u003e [[-InputObject] \u003cObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "None\nThis function does not return any output objects. It performs the action of adding database users or roles as members to database roles on the target SQL Server instances.\nWhen -WhatIf is specified, the command will display what changes would be made without performing them.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eAdd-DbaDbRoleMember -SqlInstance localhost -Database mydb -Role db_owner -Member user1\nAdds user1 to the role db_owner in the database mydb on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eAdd-DbaDbRoleMember -SqlInstance localhost, sql2016 -Role SqlAgentOperatorRole -Member user1 -Database msdb\nAdds user1 in servers localhost and sql2016 in the msdb database to the SqlAgentOperatorRole\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$servers = Get-Content C:\\servers.txt\nPS C:\\\u003e $servers | Add-DbaDbRoleMember -Role SqlAgentOperatorRole -Member user1 -Database msdb\nAdds user1 to the SqlAgentOperatorRole in the msdb database in every server in C:\\servers.txt\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eAdd-DbaDbRoleMember -SqlInstance localhost -Role \"db_datareader\",\"db_datawriter\" -Member user1 -Database DEMODB\nAdds user1 in the database DEMODB on the server localhost to the roles db_datareader and db_datawriter\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$roles = Get-DbaDbRole -SqlInstance localhost -Role \"db_datareader\",\"db_datawriter\" -Database DEMODB\nPS C:\\\u003e $roles | Add-DbaDbRoleMember -Member user1\nAdds user1 in the database DEMODB on the server localhost to the roles db_datareader and db_datawriter", "Description": "Manages database security by adding users or roles as members to database roles, automating what would otherwise require manual T-SQL commands or SQL Server Management Studio clicks. This function handles membership validation to ensure the user or role exists in the database before attempting to add them, and checks existing membership to prevent duplicate assignments. You can add multiple users to multiple roles across multiple databases and instances in a single operation, making it ideal for bulk security configuration or automated permission management workflows.", "Links": "https://dbatools.io/Add-DbaDbRoleMember", "Synopsis": "Adds database users or roles as members to database roles across SQL Server instances", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.", "", false, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to process for role membership changes. Accepts multiple database names and supports wildcards.\r\nWhen omitted, the function processes all databases on the target instances, making it useful for organization-wide security standardization.", "", false, "false", "", "" ], [ "Role", "Specifies the database role(s) to add members to. Accepts multiple role names including built-in roles like db_datareader, db_datawriter, db_owner, or custom database roles.\r\nUse this when you need to grant specific database permissions by adding users or roles to appropriate database roles.", "", false, "false", "", "" ], [ "Member", "Specifies the database user(s) or role(s) to add as members to the target roles. Can be individual users, Windows groups, or other database roles.\r\nThe function validates that each member exists in the database before attempting to add them, preventing errors from typos or missing objects.", "User", true, "false", "", "" ], [ "InputObject", "Accepts piped input from Get-DbaDbRole, Get-DbaDatabase, or SQL Server instances for streamlined workflows.\r\nUse this when chaining commands together, such as filtering specific roles first then adding members to those filtered results.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "Shows what would happen if the command were to run. No actions are actually performed.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before executing any changing operations within the command.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "General", "ExtendedProperty" ], "CommandName": "Add-DbaExtendedProperty", "Name": "Add-DbaExtendedProperty", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Add-DbaExtendedProperty [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [-Name] \u003cString\u003e [-Value] \u003cString\u003e [[-InputObject] \u003cPSObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.ExtendedProperty\nReturns one ExtendedProperty object for each extended property successfully created on the target object(s).\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- ParentName: The name of the SQL Server object to which the extended property was added (database, table, procedure, etc.)\r\n- Type: The SMO object type name of the parent object (Database, Table, StoredProcedure, View, etc.)\r\n- Name: The name identifier of the extended property being created\r\n- Value: The string value assigned to the extended property\nAdditional properties available (from SMO ExtendedProperty object):\r\n- ID: Numeric identifier of the extended property\r\n- Urn: Unique Resource Name identifying the extended property in the object hierarchy\r\n- State: SMO object state (Existing, Creating, Pending, etc.)\nAll properties from the base SMO object are accessible even though only default properties are displayed without using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eAdd-DbaExtendedProperty -SqlInstance Server1 -Database db1 -Name version -Value \"1.0.0\"\nSets the version extended property for the db1 database to 1.0.0\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbStoredProcedure -SqlInstance localhost -Database tempdb | Add-DbaExtendedProperty -Name SPVersion -Value 10.2\nCreates an extended property for all stored procedures in the tempdb database named SPVersion with a value of 10.2\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbTable -SqlInstance localhost -Database mydb -Table mytable | Add-DbaExtendedProperty -Name MyExtendedProperty -Value \"This is a test\"\nCreates an extended property named MyExtendedProperty for the mytable table in the mydb, with a value of \"This is a test\"", "Description": "Creates custom metadata properties on SQL Server objects to store documentation, version information, business context, or compliance tags. Extended properties are stored in the database system catalogs and don\u0027t affect object performance but provide valuable context for DBAs managing complex environments.\n\nThis command accepts piped input from any dbatools Get-Dba* command, making it easy to bulk-apply properties across multiple objects. You can add extended properties to databases directly or target specific object types, including:\n\nAggregate\nAssembly\nColumn\nConstraint\nContract\nDatabase\nEvent Notification\nFilegroup\nFunction\nIndex\nLogical File Name\nMessage Type\nParameter\nPartition Function\nPartition Scheme\nProcedure\nQueue\nRemote Service Binding\nRoute\nRule\nSchema\nService\nSynonym\nTable\nTrigger\nType\nView\nXml Schema Collection", "Links": "https://dbatools.io/Add-DbaExtendedProperty", "Synopsis": "Adds extended properties to SQL Server objects for metadata storage and documentation", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to target when adding extended properties directly to database objects. Accepts wildcards for pattern matching.\r\nUse this when you want to add metadata to entire databases rather than piping specific objects from Get-Dba* commands.", "", false, "false", "", "" ], [ "Name", "Sets the name identifier for the extended property being created. Must be unique per object.\r\nCommon examples include \"Version\", \"Owner\", \"Purpose\", \"DataClassification\", or \"LastModified\" for documentation and compliance tracking.", "Property", true, "false", "", "" ], [ "Value", "Defines the content stored in the extended property as a string value. Can contain any text including version numbers, descriptions, dates, or JSON data.\r\nKeep values concise as they\u0027re stored in system catalogs and are visible in SQL Server Management Studio object properties.", "", true, "false", "", "" ], [ "InputObject", "Accepts SQL Server objects from any Get-Dba* command that supports extended properties. Works with tables, views, procedures, functions, and many other object types.\r\nThis is the primary method for bulk-applying extended properties across multiple objects in your database environment.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "Shows what would happen if the command were to run. No actions are actually performed.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before executing any changing operations within the command.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "TabCompletion", "Autocomplete" ], "CommandName": "Add-DbaInstanceList", "Name": "Add-DbaInstanceList", "Author": "the dbatools team + Claude", "Syntax": "Add-DbaInstanceList [-SqlInstance] \u003cString[]\u003e [-Register] [[-Scope] {UserDefault | UserMandatory | SystemDefault | SystemMandatory | FileUserLocal | FileUserShared | FileSystem}] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "None\nThis command updates the autocomplete cache but does not output any objects to the\r\npipeline. Use Get-DbaInstanceList to retrieve the configured instance names.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eAdd-DbaInstanceList -SqlInstance \"sql01\", \"sql02\\dev\"\nAdds sql01 and sql02\\dev to the autocomplete instance list for the current session.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eAdd-DbaInstanceList -SqlInstance \"sql01\" -Register\nAdds sql01 to the autocomplete instance list and persists it across PowerShell sessions.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e\"sql01\", \"sql02\" | Add-DbaInstanceList -Register\nAdds two instances to the list via pipeline and persists them across sessions.", "Description": "Adds SQL Server instance names to a persistent list that pre-populates the tab completion\ncache for the -SqlInstance parameter across all dbatools commands. This allows users to\nhave their frequently used instances available for autocomplete in their PowerShell\nterminal without needing to connect to them first.\n\nThe instance list is stored using the dbatools configuration system. Use -Register to\npersist the list across PowerShell sessions.\n\nInstances can also be pre-loaded at module import time by setting the\n$env:DBATOOLS_KNOWN_INSTANCES environment variable to a comma-separated list of instance\nnames in your PowerShell profile.", "Links": "https://dbatools.io/Add-DbaInstanceList", "Synopsis": "Adds one or more SQL Server instances to the user-maintained autocomplete list.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The SQL Server instance name or names to add to the autocomplete list.\r\nAccepts pipeline input.", "", true, "true (ByValue, ByPropertyName)", "", "" ], [ "Register", "Persists the instance list to disk so it is available in future PowerShell sessions.\r\nWithout this switch, the list only exists for the current session.", "", false, "false", "False", "" ], [ "Scope", "Determines where the persistent configuration is stored when using -Register.\r\nUserDefault stores the setting for the current user only.", "", false, "false", "UserDefault", "" ] ] }, { "Tags": "PerfMon", "CommandName": "Add-DbaPfDataCollectorCounter", "Name": "Add-DbaPfDataCollectorCounter", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Add-DbaPfDataCollectorCounter [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-CollectorSet] \u003cString[]\u003e] [[-Collector] \u003cString[]\u003e] [-Counter] \u003cObject[]\u003e [[-InputObject] \u003cObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per counter added to the Data Collector Set.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The name of the computer where the Data Collector Set is configured\r\n- DataCollectorSet: The name of the parent Data Collector Set containing the collector\r\n- DataCollector: The name of the specific Data Collector within the Collector Set\r\n- Name: The full path of the performance counter that was added\r\n- FileName: The output file name where performance counter data will be stored\nAdditional properties available:\r\n- DataCollectorSetXml: The XML configuration of the Data Collector Set (typically excluded from default view)\r\n- Credential: The credentials used to connect to the target computer (typically excluded from default view)\r\n- CounterObject: Internal flag indicating this is a counter object (typically excluded from default view)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eAdd-DbaPfDataCollectorCounter -ComputerName sql2017 -CollectorSet \u0027System Correlation\u0027 -Collector DataCollector01 -Counter \u0027\\LogicalDisk(*)\\Avg. Disk Queue Length\u0027\nAdds the \u0027\\LogicalDisk(*)\\Avg. Disk Queue Length\u0027 counter within the DataCollector01 collector within the System Correlation collector set on sql2017.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollector | Out-GridView -PassThru | Add-DbaPfDataCollectorCounter -Counter \u0027\\LogicalDisk(*)\\Avg. Disk Queue Length\u0027 -Confirm\nAllows you to select which Data Collector you\u0027d like to add the counter \u0027\\LogicalDisk(*)\\Avg. Disk Queue Length\u0027 on localhost and prompts for confirmation.", "Description": "Adds specific performance counters to existing Data Collector Sets within Windows Performance Monitor. This allows DBAs to customize their performance monitoring by adding SQL Server-specific counters like disk queue length, processor time, or SQL Server object counters to existing collection sets. The function modifies the Data Collector Set configuration and immediately applies the changes, so you can start collecting the additional performance metrics without recreating your monitoring setup.", "Links": "https://dbatools.io/Add-DbaPfDataCollectorCounter", "Synopsis": "Adds performance counters to existing Windows Performance Monitor Data Collector Sets for SQL Server monitoring.", "Availability": "Windows only", "Params": [ [ "ComputerName", "Specifies the target computer where the Data Collector Set is located. Use this when adding counters to performance monitoring on remote SQL Server instances.\r\nDefaults to localhost if not specified.", "", false, "false", "$env:COMPUTERNAME", "" ], [ "Credential", "Allows you to login to $ComputerName using alternative credentials. To use:\n$cred = Get-Credential, then pass $cred object to the -Credential parameter.", "", false, "false", "", "" ], [ "CollectorSet", "Specifies the name of the Windows Performance Monitor Data Collector Set that contains the collector you want to modify.\r\nThis is the parent container that organizes related performance data collectors for your monitoring scenario.", "DataCollectorSet", false, "false", "", "" ], [ "Collector", "Specifies the name of the individual Data Collector within the CollectorSet where the new counter will be added.\r\nEach collector can contain multiple performance counters and defines how the data is gathered and stored.", "DataCollector", false, "false", "", "" ], [ "Counter", "Specifies the performance counter path to add to the Data Collector. Must use the full counter path format like \u0027\\Processor(_Total)\\% Processor Time\u0027 or \u0027\\SQLServer:Buffer Manager\\Page life \r\nexpectancy\u0027.\r\nUse Get-DbaPfAvailableCounter to find available SQL Server and system counters with their exact paths.", "Name", true, "true (ByPropertyName)", "", "" ], [ "InputObject", "Accepts Data Collector objects from Get-DbaPfDataCollector via the pipeline. This allows you to target specific collectors for counter addition.\r\nAlso accepts counter objects from Get-DbaPfAvailableCounter to add available counters directly.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "RegisteredServer", "CMS" ], "CommandName": "Add-DbaRegServer", "Name": "Add-DbaRegServer", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Add-DbaRegServer [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-ServerName] \u003cString\u003e] [[-Name] \u003cString\u003e] [[-Description] \u003cString\u003e] [[-Group] \u003cObject\u003e] [[-ActiveDirectoryTenant] \u003cString\u003e] [[-ActiveDirectoryUserId] \u003cString\u003e] [[-ConnectionString] \u003cString\u003e] [[-OtherParams] \u003cString\u003e] [[-InputObject] \u003cServerGroup[]\u003e] [[-ServerObject] \u003cServer[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.RegisteredServers.RegisteredServer\nReturns one RegisteredServer object for each server registered. Multiple servers can be returned when registering to different server groups or Central Management Server instances.\nDefault display properties (via Select-DefaultView):\r\n- Name: Display name of the registered server as it appears in SSMS Registered Servers pane\r\n- ServerName: The actual SQL Server connection string or instance name\r\n- Group: The server group hierarchy path where the server is registered (null if in root)\r\n- Description: User-provided description of the registered server\r\n- Source: Origin of the registration (Central Management Servers, Local Server Groups, or Azure Data Studio)\nAdditional properties available (from SMO RegisteredServer object):\r\n- ComputerName: The computer name of the CMS or local registration location\r\n- InstanceName: The instance name of the CMS or local registration location\r\n- SqlInstance: The full SQL instance identifier of the CMS (computer\\instance)\r\n- ParentServer: Reference to the parent server store object\r\n- Id: Unique identifier of the registered server within its store\r\n- ConnectionString: The connection string used to connect to the server\r\n- SecureConnectionString: Encrypted version of the connection string\r\n- ActiveDirectoryTenant: Azure AD tenant ID if using Azure AD authentication\r\n- ActiveDirectoryUserId: Azure AD user principal name if using Azure AD authentication\r\n- OtherParams: Additional connection string parameters\r\n- CredentialPersistenceType: How credentials are stored (PersistLoginNameAndPassword, etc.)\r\n- ServerType: Type of server (DatabaseEngine, AnalysisServices, etc.)\r\n- FQDN: Fully qualified domain name (populated when -ResolveNetworkName is used on Get-DbaRegServer)\r\n- IPAddress: IP address of the server (populated when -ResolveNetworkName is used on Get-DbaRegServer)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eAdd-DbaRegServer -SqlInstance sql2008 -ServerName sql01\nCreates a registered server on sql2008\u0027s CMS which points to the SQL Server, sql01. When scrolling in CMS, the name \"sql01\" will be visible.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eAdd-DbaRegServer -ServerName sql01\nCreates a registered server in Local Server Groups which points to the SQL Server, sql01. When scrolling in Registered Servers, the name \"sql01\" will be visible.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eAdd-DbaRegServer -SqlInstance sql2008 -ServerName sql01 -Name \"The 2008 Clustered Instance\" -Description \"HR\u0027s Dedicated SharePoint instance\"\nCreates a registered server on sql2008\u0027s CMS which points to the SQL Server, sql01. When scrolling in CMS, \"The 2008 Clustered Instance\" will be visible.\r\nClearly this is hard to explain ;)\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eAdd-DbaRegServer -SqlInstance sql2008 -ServerName sql01 -Group hr\\Seattle\nCreates a registered server on sql2008\u0027s CMS which points to the SQL Server, sql01. When scrolling in CMS, the name \"sql01\" will be visible within the Seattle group which is in the hr group.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eConnect-DbaInstance -SqlInstance dockersql1 -SqlCredential sqladmin | Add-DbaRegServer -ServerName mydockerjam\nCreates a registered server called \"mydockerjam\" in Local Server Groups that uses SQL authentication and points to the server dockersql1.", "Description": "Registers SQL Server instances as managed servers within SSMS, either to a Central Management Server (CMS) for enterprise-wide management or to Local Server Groups for personal organization. This allows DBAs to centrally organize and quickly connect to multiple SQL Server instances from SSMS without manually typing connection details each time. The function automatically creates server groups if they don\u0027t exist and supports various authentication methods including SQL Server, Windows, and Azure Active Directory. For importing existing registered servers from other sources, use Import-DbaRegServer instead.", "Links": "https://dbatools.io/Add-DbaRegServer", "Synopsis": "Registers SQL Server instances to Central Management Server or Local Server Groups in SSMS", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance if a CMS is used", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "ServerName", "Specifies the actual SQL Server instance name or network address that will be used to connect to the server.\r\nThis is the technical identifier that SSMS uses for the physical connection (e.g., \"sql01.domain.com,1433\" or \"sql01\\INSTANCE\").", "", false, "false", "", "" ], [ "Name", "Sets the display name that appears in the SSMS Registered Servers tree or CMS interface.\r\nUse this to give servers meaningful, recognizable names like \"Production HR Database\" instead of cryptic server names. Defaults to ServerName if not specified.", "", false, "false", "$ServerName", "" ], [ "Description", "Provides additional details about the registered server that appear in SSMS properties.\r\nUse this to document the server\u0027s purpose, environment, or important notes like \"Primary OLTP for HR applications\" or \"Read-only replica for reporting\".", "", false, "false", "", "" ], [ "Group", "Places the registered server into a specific organizational folder within CMS or Local Server Groups.\r\nCreates nested groups using backslash notation like \"Production\\OLTP\" or \"Dev\\Testing\". The group structure will be created automatically if it doesn\u0027t exist.", "", false, "false", "", "" ], [ "ActiveDirectoryTenant", "Specifies the Azure Active Directory tenant ID when registering servers that use Azure AD authentication.\r\nRequired when connecting to Azure SQL Database or SQL Managed Instance with AAD credentials.", "", false, "false", "", "" ], [ "ActiveDirectoryUserId", "Sets the Azure Active Directory user principal name for AAD authentication scenarios.\r\nUse this when you want the registered server to authenticate with a specific AAD account instead of integrated authentication.", "", false, "false", "", "" ], [ "ConnectionString", "Provides a complete SQL Server connection string with all authentication and connection parameters.\r\nUse this when you need specific connection properties like encryption settings, timeout values, or custom authentication methods not covered by other parameters.", "", false, "false", "", "" ], [ "OtherParams", "Appends additional connection string parameters to the base connection.\r\nUseful for adding specific connection properties like \"MultipleActiveResultSets=True\" or \"TrustServerCertificate=True\" without rebuilding the entire connection string.", "", false, "false", "", "" ], [ "InputObject", "Accepts a server group object from Get-DbaRegServerGroup to specify where the server should be registered.\r\nUse this when you want to programmatically target a specific group or when piping group objects from other dbatools commands.", "", false, "true (ByValue)", "", "" ], [ "ServerObject", "Accepts an existing SMO Server object from Connect-DbaInstance to register that connection.\r\nThis preserves all connection settings and authentication from the original connection, making it ideal for registering servers you\u0027ve already successfully connected to.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "Shows what would happen if the command were to run. No actions are actually performed.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before executing any changing operations within the command.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "RegisteredServer", "CMS" ], "CommandName": "Add-DbaRegServerGroup", "Name": "Add-DbaRegServerGroup", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Add-DbaRegServerGroup [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [-Name] \u003cString\u003e [[-Description] \u003cString\u003e] [[-Group] \u003cString\u003e] [[-InputObject] \u003cServerGroup[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.RegisteredServers.ServerGroup\nReturns one ServerGroup object for each newly created server group (or for each parent group in the hierarchy if multiple nested groups were created with backslash notation).\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance hosting the Central Management Server\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Name: The name of the server group\r\n- DisplayName: The display name of the server group\r\n- Description: Description of the server group (if provided)\r\n- ServerGroups: Collection of subgroups within this group\r\n- RegisteredServers: Collection of registered servers in this group\nAdditional properties available from the SMO ServerGroup object:\r\n- Id: Unique identifier for the group within the CMS\r\n- Parent: The parent ServerGroup object\r\n- Urn: Uniform Resource Name identifying the group in the SMO object hierarchy\r\n- State: SMO object state (Existing, Creating, Pending, etc.)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eAdd-DbaRegServerGroup -SqlInstance sql2012 -Name HR\nCreates a registered server group called HR, in the root of sql2012\u0027s CMS\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eAdd-DbaRegServerGroup -SqlInstance sql2012, sql2014 -Name sub-folder -Group HR\nCreates a registered server group on sql2012 and sql2014 called sub-folder within the HR group\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaRegServerGroup -SqlInstance sql2012, sql2014 -Group HR | Add-DbaRegServerGroup -Name sub-folder\nCreates a registered server group on sql2012 and sql2014 called sub-folder within the HR group of each server", "Description": "Creates new server groups in SQL Server Central Management Server to organize registered servers into logical hierarchies. This allows DBAs to group servers by environment, application, location, or any other classification system for easier management at scale. Supports nested group structures using backslash notation (Group\\SubGroup) and automatically creates parent groups if they don\u0027t exist. If you need to import existing groups and servers from other sources, use Import-DbaRegServer instead.", "Links": "https://dbatools.io/Add-DbaRegServerGroup", "Synopsis": "Creates organizational server groups within SQL Server Central Management Server (CMS)", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Name", "Specifies the name for the new server group within Central Management Server. Use descriptive names that reflect your organizational structure like \u0027Production\u0027, \u0027Development\u0027, or \u0027HR-Databases\u0027.\r\nGroup names can include backslashes to create nested hierarchies (e.g., \u0027Production\\WebServers\u0027 creates a WebServers subgroup under Production).", "", true, "false", "", "" ], [ "Description", "Provides additional details about the server group\u0027s purpose or contents. Use this to document the group\u0027s role, maintenance schedules, or contact information.\r\nHelpful for team environments where multiple DBAs need to understand each group\u0027s function.", "", false, "false", "", "" ], [ "Group", "Specifies the parent group where the new server group will be created. If omitted, creates the group at the root level of Central Management Server.\r\nUse backslash notation to specify nested paths like \u0027Production\\WebServers\u0027 - this automatically creates any missing parent groups in the hierarchy.", "", false, "false", "", "" ], [ "InputObject", "Accepts server group objects from Get-DbaRegServerGroup through the pipeline. Use this when you need to create subgroups within existing groups from multiple CMS instances.\r\nEnables bulk operations where you can pipe existing groups and create new subgroups within each one simultaneously.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "Shows what would happen if the command were to run. No actions are actually performed.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before executing any changing operations within the command.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "repl", "Replication" ], "CommandName": "Add-DbaReplArticle", "Name": "Add-DbaReplArticle", "Author": "Jess Pomfret (@jpomfret), jesspomfret.com", "Syntax": "Add-DbaReplArticle [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Database] \u003cString\u003e [-Publication] \u003cString\u003e [[-Schema] \u003cString\u003e] [-Name] \u003cString\u003e [[-Filter] \u003cString\u003e] [[-CreationScriptOptions] \u003cPSObject\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Replication.TransArticle or Microsoft.SqlServer.Replication.MergeArticle\nReturns one article object for each successfully added article. For transactional and snapshot replication, a TransArticle object is returned. For merge replication, a MergeArticle object is returned.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The name of the computer where the SQL Server instance is running\r\n- InstanceName: The name of the SQL Server instance\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- DatabaseName: The name of the database containing the article\r\n- PublicationName: The name of the publication containing the article\r\n- Name: The name of the article as it appears in the publication\r\n- Type: The type of article (table, view, stored procedure, etc.)\r\n- VerticalPartition: Boolean indicating if the article uses vertical partitioning (column filtering)\r\n- SourceObjectOwner: The schema of the source object (typically \u0027dbo\u0027)\r\n- SourceObjectName: The name of the source object being replicated\nAdditional properties available (from SMO Article object):\r\n- BusinessLogicHandlerName: Name of the business logic handler (merge replication only)\r\n- ColumnTrackingLevel: Column tracking level for merge replication\r\n- CreationScript: Script containing the CREATE TABLE statement for the article\r\n- DestinationObjectName: Optional different object name on the subscriber\r\n- DestinationObjectOwner: Optional different schema name on the subscriber\r\n- FilterClause: WHERE clause used for horizontal partitioning (row filtering)\r\n- HorizontalPartition: Boolean indicating if the article uses horizontal partitioning\r\n- IdentityRange: Range for identity column values (transactional replication only)\r\n- IdentityRangeManagementOption: How identity ranges are managed\r\n- IdentitySeed: Starting value for identity column replication\r\n- PreCreatedObject: Boolean indicating if the object already exists on the subscriber\r\n- PublicationName: Name of the publication containing the article\r\n- SchemaOption: Defines which schema elements are included in the replication\nAll properties from the SMO Article object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eAdd-DbaReplArticle -SqlInstance mssql1 -Database Northwind -Publication PubFromPosh -Name TableToRepl\nAdds the TableToRepl table to the PubFromPosh publication from mssql1.Northwind\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$article = @{\n\u003e\u003e SqlInstance = \"mssql1\"\r\n\u003e\u003e Database = \"pubs\"\r\n\u003e\u003e Publication = \"testPub\"\r\n\u003e\u003e Name = \"publishers\"\r\n\u003e\u003e Filter = \"city = \u0027seattle\u0027\"\r\n\u003e\u003e }\r\nPS C:\\\u003e Add-DbaReplArticle @article -EnableException\nAdds the publishers table to the TestPub publication from mssql1.Pubs with a horizontal filter of only rows where city = \u0027seattle.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$cso = New-DbaReplCreationScriptOptions -Options NonClusteredIndexes, Statistics\nPS C:\\\u003e $article = @{\r\n\u003e\u003e SqlInstance = \u0027mssql1\u0027\r\n\u003e\u003e Database = \u0027pubs\u0027\r\n\u003e\u003e Publication = \u0027testPub\u0027\r\n\u003e\u003e Name = \u0027stores\u0027\r\n\u003e\u003e CreationScriptOptions = $cso\r\n\u003e\u003e }\r\nPS C:\\\u003e Add-DbaReplArticle @article -EnableException\nAdds the stores table to the testPub publication from mssql1.pubs with the NonClusteredIndexes and Statistics options set\r\nincludes default options.", "Description": "Adds a database object (typically a table) as an article to an existing SQL Server replication publication. Articles define which tables and data get replicated to subscribers. This function supports both transactional and merge replication publications, allowing you to expand replication topology without using SQL Server Management Studio. You can apply horizontal filters to replicate only specific rows, and customize schema options like indexes and statistics that get created on subscriber databases.", "Links": "https://dbatools.io/Add-DbaReplArticle", "Synopsis": "Adds a table or other database object as an article to an existing replication publication.", "Availability": "Windows only", "Params": [ [ "SqlInstance", "The SQL Server instance(s) for the publication.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies the database containing both the publication and the object you want to add as an article.\r\nThis must be the same database where your replication publication was created.", "", true, "false", "", "" ], [ "Publication", "Specifies the name of the existing replication publication to add the article to.\r\nThe publication must already exist and be configured for the type of replication you want (transactional, snapshot, or merge).", "", true, "false", "", "" ], [ "Schema", "Specifies the schema name of the object you want to add as an article.\r\nUse this when your table or object exists in a schema other than dbo. Defaults to dbo if not specified.", "", false, "false", "dbo", "" ], [ "Name", "Specifies the name of the database object (typically a table) to add as an article to the publication.\r\nThis object will be replicated to all subscribers of the publication.", "", true, "false", "", "" ], [ "Filter", "Applies a WHERE clause condition to filter which rows get replicated from the article (horizontal filtering).\r\nUse this when you only want to replicate specific rows, such as \"City = \u0027Seattle\u0027\" or \"Status = \u0027Active\u0027\". Do not include the word \u0027WHERE\u0027 in your filter expression.", "", false, "false", "", "" ], [ "CreationScriptOptions", "Controls which schema elements get created on the subscriber database when the article is replicated.\r\nUse this to specify whether indexes, constraints, triggers, and other objects should be created on subscribers. Create this object using New-DbaReplCreationScriptOptions.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Role", "Login" ], "CommandName": "Add-DbaServerRoleMember", "Name": "Add-DbaServerRoleMember", "Author": "Shawn Melton (@wsmelton)", "Syntax": "Add-DbaServerRoleMember [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-ServerRole] \u003cString[]\u003e] [[-Login] \u003cString[]\u003e] [[-Role] \u003cString[]\u003e] [[-InputObject] \u003cObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "None\nThis command does not return any objects. It performs administrative actions to add logins or roles to server-level roles and returns control to the caller. Use the -Verbose switch to see detailed \r\ninformation about the actions being performed, or the -WhatIf switch to preview what would be changed without making modifications.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eAdd-DbaServerRoleMember -SqlInstance server1 -ServerRole dbcreator -Login login1\nAdds login1 to the dbcreator fixed server-level role on the instance server1.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eAdd-DbaServerRoleMember -SqlInstance server1, sql2016 -ServerRole customrole -Login login1\nAdds login1 in customrole custom server-level role on the instance server1 and sql2016.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eAdd-DbaServerRoleMember -SqlInstance server1 -ServerRole customrole -Role dbcreator\nAdds customrole custom server-level role to dbcreator fixed server-level role.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$servers = Get-Content C:\\servers.txt\nPS C:\\\u003e $servers | Add-DbaServerRoleMember -ServerRole sysadmin -Login login1\nAdds login1 to the sysadmin fixed server-level role in every server in C:\\servers.txt.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eAdd-DbaServerRoleMember -SqlInstance localhost -ServerRole bulkadmin, dbcreator -Login login1\nAdds login1 on the server localhost to the bulkadmin and dbcreator fixed server-level roles.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e$roles = Get-DbaServerRole -SqlInstance localhost -ServerRole bulkadmin, dbcreator\nPS C:\\\u003e $roles | Add-DbaServerRoleMember -Login login1\nAdds login1 on the server localhost to the bulkadmin and dbcreator fixed server-level roles.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003ePS C:\\ $logins = Get-Content C:\\logins.txt\nPS C:\\ $srvLogins = Get-DbaLogin -SqlInstance server1 -Login $logins\r\nPS C:\\ New-DbaServerRole -SqlInstance server1 -ServerRole mycustomrole -Owner sa | Add-DbaServerRoleMember -Login $logins\nAdds all the logins found in C:\\logins.txt to the newly created server-level role mycustomrole on server1.", "Description": "Grants server-level role membership to SQL logins or nests server roles within other server roles. Use this command when setting up security permissions, implementing role-based access control, or managing server-level privileges across multiple SQL Server instances. Supports both built-in roles (sysadmin, dbcreator, etc.) and custom server roles, so you don\u0027t have to manually assign permissions through SSMS or T-SQL scripts.", "Links": "https://dbatools.io/Add-DbaServerRoleMember", "Synopsis": "Adds logins or server roles to server-level roles for SQL Server security administration.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.", "", false, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "ServerRole", "Specifies the server-level role(s) that will receive new members. Accepts both built-in roles (sysadmin, dbcreator, securityadmin, etc.) and custom server roles.\r\nUse this when you need to grant server-level permissions by adding logins or nesting roles within these target roles.", "", false, "true (ByValue)", "", "" ], [ "Login", "Specifies the SQL Server login(s) to be granted membership in the target server roles. Accepts Windows accounts, SQL logins, and Active Directory accounts.\r\nUse this when you need to give specific users or service accounts server-level permissions rather than nesting entire roles.", "", false, "false", "", "" ], [ "Role", "Specifies existing server-level role(s) to be nested as members within the target ServerRole(s). Creates a role hierarchy where one role inherits permissions from another.\r\nUse this when implementing role-based security designs where you want to group permissions through role membership rather than individual login assignments.", "", false, "false", "", "" ], [ "InputObject", "Accepts server role objects piped from Get-DbaServerRole or New-DbaServerRole commands. Allows you to chain commands together for workflow automation.\r\nUse this when you want to operate on roles retrieved by other dbatools commands rather than specifying role names as strings.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "Shows what would happen if the command were to run. No actions are actually performed.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before executing any changing operations within the command.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "CertBackup", "Certificate", "Backup" ], "CommandName": "Backup-DbaComputerCertificate", "Name": "Backup-DbaComputerCertificate", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Backup-DbaComputerCertificate [[-SecurePassword] \u003cSecureString\u003e] [-InputObject] \u003cObject[]\u003e [[-Path] \u003cString\u003e] [[-FilePath] \u003cString\u003e] [[-Type] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.IO.FileInfo\nReturns one FileInfo object per certificate that was successfully exported. This represents the certificate file created on disk.\nProperties:\r\n- Name: The filename of the exported certificate (e.g., ComputerName-Thumbprint.cer)\r\n- FullName: The complete path to the exported certificate file\r\n- DirectoryName: The directory where the certificate file is stored\r\n- Directory: The DirectoryInfo object of the parent directory\r\n- Extension: The file extension (.cer, .pfx, etc., based on Type parameter)\r\n- Length: The size of the exported certificate file in bytes\r\n- CreationTime: When the certificate file was created\r\n- LastWriteTime: When the certificate file was last written\r\n- Attributes: File attributes (Archive, Normal, etc.)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaComputerCertificate | Backup-DbaComputerCertificate -Path C:\\temp\nBacks up all certs to C:\\temp. Auto-names the files.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaComputerCertificate -Thumbprint 29C469578D6C6211076A09CEE5C5797EEA0C2713 | Backup-DbaComputerCertificate -FilePath C:\\temp\\29C469578D6C6211076A09CEE5C5797EEA0C2713.cer\nBacks up certificate with the thumbprint 29C469578D6C6211076A09CEE5C5797EEA0C2713 to the temp directory.", "Description": "Exports computer certificates from the local or remote certificate store to files on disk. This is essential for backing up certificates used for SQL Server network encryption before server migrations, certificate renewals, or disaster recovery scenarios. The function works with certificate objects from Get-DbaComputerCertificate and supports multiple export formats including standard .cer files and password-protected .pfx files for complete private key backup.", "Links": "https://dbatools.io/Backup-DbaComputerCertificate", "Synopsis": "Exports computer certificates to disk for SQL Server network encryption backup and disaster recovery.", "Availability": "Windows only", "Params": [ [ "SecurePassword", "Provides password protection for certificate exports, required when exporting private keys with Pfx format.\r\nEssential for securing certificate backups that contain private keys used for SQL Server TLS encryption.", "Password", false, "false", "", "" ], [ "InputObject", "The certificate objects to export, typically from Get-DbaComputerCertificate pipeline output.\r\nUse this to specify which certificates to backup for SQL Server network encryption recovery scenarios.", "", true, "true (ByValue)", "", "" ], [ "Path", "Specifies the target directory where certificate files will be saved with auto-generated filenames.\r\nFiles are named using the pattern: ComputerName-Thumbprint.cer for easy identification during recovery.", "", false, "false", "$pwd", "" ], [ "FilePath", "Specifies the exact file path and name for the exported certificate.\r\nUse this when you need to control the output filename or when backing up a single certificate to a specific location.", "", false, "false", "", "" ], [ "Type", "Determines the certificate export format for different backup and deployment scenarios.\r\nUse \u0027Cert\u0027 for public key only backups, \u0027Pfx\u0027 for complete certificate with private key backup, or other formats based on your security requirements.", "", false, "false", "Cert", "Authenticode,Cert,Pfx,Pkcs12,Pkcs7,SerializedCert" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "DisasterRecovery", "Backup", "Restore" ], "CommandName": "Backup-DbaDatabase", "Name": "Backup-DbaDatabase", "Author": "Stuart Moore (@napalmgram), stuart-moore.com", "Syntax": "Backup-DbaDatabase [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-Path \u003cString[]\u003e] [-FilePath \u003cString\u003e] [-IncrementPrefix] [-ReplaceInName] [-NoAppendDbNameInPath] [-CopyOnly] [-Type \u003cString\u003e] [-CreateFolder] [-FileCount \u003cInt32\u003e] [-CompressBackup] [-Checksum] [-Verify] [-MaxTransferSize \u003cInt32\u003e] [-BlockSize \u003cInt32\u003e] [-BufferCount \u003cInt32\u003e] [-StorageBaseUrl \u003cString[]\u003e] [-StorageCredential \u003cString\u003e] [-StorageRegion \u003cString\u003e] [-NoRecovery] [-BuildPath] [-WithFormat] [-Initialize] [-SkipTapeHeader] [-TimeStampFormat \u003cString\u003e] [-IgnoreFileChecks] \r\n[-OutputScriptOnly] [-EncryptionAlgorithm \u003cString\u003e] [-EncryptionCertificate \u003cString\u003e] [-Description \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nBackup-DbaDatabase -SqlInstance \u003cDbaInstanceParameter\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-Path \u003cString[]\u003e] [-FilePath \u003cString\u003e] [-IncrementPrefix] [-ReplaceInName] [-NoAppendDbNameInPath] [-CopyOnly] [-Type \u003cString\u003e] [-CreateFolder] [-FileCount \u003cInt32\u003e] [-CompressBackup] [-Checksum] [-Verify] [-MaxTransferSize \u003cInt32\u003e] [-BlockSize \u003cInt32\u003e] [-BufferCount \u003cInt32\u003e] [-StorageBaseUrl \u003cString[]\u003e] [-StorageCredential \u003cString\u003e] [-StorageRegion \u003cString\u003e] [-NoRecovery] [-BuildPath] [-WithFormat] [-Initialize] [-SkipTapeHeader] [-TimeStampFormat \r\n\u003cString\u003e] [-IgnoreFileChecks] [-OutputScriptOnly] [-EncryptionAlgorithm \u003cString\u003e] [-EncryptionCertificate \u003cString\u003e] [-Description \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nBackup-DbaDatabase [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-Path \u003cString[]\u003e] [-FilePath \u003cString\u003e] [-IncrementPrefix] [-ReplaceInName] [-NoAppendDbNameInPath] [-CopyOnly] [-Type \u003cString\u003e] -InputObject \u003cObject[]\u003e [-CreateFolder] [-FileCount \u003cInt32\u003e] [-CompressBackup] [-Checksum] [-Verify] [-MaxTransferSize \u003cInt32\u003e] [-BlockSize \u003cInt32\u003e] [-BufferCount \u003cInt32\u003e] [-StorageBaseUrl \u003cString[]\u003e] [-StorageCredential \u003cString\u003e] [-StorageRegion \u003cString\u003e] [-NoRecovery] [-BuildPath] [-WithFormat] [-Initialize] [-SkipTapeHeader] [-TimeStampFormat \u003cString\u003e] \r\n[-IgnoreFileChecks] [-OutputScriptOnly] [-EncryptionAlgorithm \u003cString\u003e] [-EncryptionCertificate \u003cString\u003e] [-Description \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Dataplat.Dbatools.Database.BackupHistory\nReturns one backup history object per database backed up. When -OutputScriptOnly is specified, returns the T-SQL BACKUP command string(s) instead.\nDefault display properties (via Select-DefaultView):\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: Database name\r\n- Type: Backup type (Full, Differential, or Log)\r\n- TotalSize: Total backup size in bytes\r\n- DeviceType: Backup destination device type (Disk, Tape, URL, Virtual Device, etc.)\r\n- Duration: Time span of the backup operation\nAdditional properties available on all BackupHistory objects:\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- DatabaseId: System object ID of the database\r\n- UserName: SQL login that performed the backup\r\n- Start: DateTime when backup started\r\n- End: DateTime when backup completed\r\n- Path: Array of physical file paths where backup files were written\r\n- CompressedBackupSize: Size of compressed backup in bytes (if compression was used)\r\n- CompressionRatio: Ratio of uncompressed to compressed size\r\n- BackupSetId: Unique identifier for the backup set\r\n- MediaSetId: Unique identifier for the media set\r\n- Position: Backup set position on the media\r\n- FirstLsn: First Log Sequence Number in the backup\r\n- DatabaseBackupLsn: Database backup LSN\r\n- CheckpointLsn: Checkpoint LSN\r\n- LastLsn: Last Log Sequence Number in the backup\r\n- SoftwareVersionMajor: SQL Server major version that created the backup\r\n- Software: Software name and version (e.g., \"Microsoft SQL Server 2019\")\r\n- IsCopyOnly: Boolean indicating if this is a copy-only backup\r\n- LastRecoveryForkGuid: GUID of the recovery fork at backup time\r\n- RecoveryModel: Database recovery model at backup time (Simple, Full, or BulkLogged)\r\n- EncryptorType: Type of encryption used (ServerCertificate, ServerAsymmetricKey, or None)\r\n- EncryptorThumbprint: Certificate or key thumbprint if encrypted\r\n- KeyAlgorithm: Encryption algorithm used (AES128, AES192, AES256, or TRIPLEDES)\r\n- BackupComplete: Boolean indicating if the backup operation completed successfully\r\n- BackupFile: The filename(s) of the backup file(s) created\r\n- BackupFilesCount: Number of striped backup files created\r\n- BackupFolder: Parent directory path where backup files were created\r\n- BackupPath: Full path(s) to the backup file(s) created\r\n- Script: T-SQL BACKUP command that was executed\r\n- FileList: Array of data and log files that were backed up (only when Verify is used)\r\n- Verified: Boolean indicating if backup verification passed (only when Verify is used)\r\n- Notes: Warning or error messages from the backup operation\nWhen -OutputScriptOnly is specified, the command returns a System.String containing the T-SQL BACKUP statement without performing the backup operation.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eBackup-DbaDatabase -SqlInstance Server1 -Database HR, Finance\nThis will perform a full database backup on the databases HR and Finance on SQL Server Instance Server1 to Server1 default backup directory.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eBackup-DbaDatabase -SqlInstance sql2016 -Path C:\\temp -Database AdventureWorks2014 -Type Full\nBacks up AdventureWorks2014 to sql2016 C:\\temp folder.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eBackup-DbaDatabase -SqlInstance sql2016 -StorageBaseUrl https://dbatoolsaz.blob.core.windows.net/azbackups/ -StorageCredential dbatoolscred -Type Full -CreateFolder\nPerforms a full backup of all databases on the sql2016 instance to their own containers under the https://dbatoolsaz.blob.core.windows.net/azbackups/ container on Azure blob storage using the sql \r\ncredential \"dbatoolscred\" registered on the sql2016 instance.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eBackup-DbaDatabase -SqlInstance sql2016 -AzureBaseUrl https://dbatoolsaz.blob.core.windows.net/azbackups/ -Type Full\nPerforms a full backup of all databases on the sql2016 instance to the https://dbatoolsaz.blob.core.windows.net/azbackups/ container on Azure blob storage using the Shared Access Signature sql \r\ncredential \"https://dbatoolsaz.blob.core.windows.net/azbackups\" registered on the sql2016 instance.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eBackup-DbaDatabase -SqlInstance Server1\\Prod -Database db1 -Path \\\\filestore\\backups\\servername\\instancename\\dbname\\backuptype -Type Full -ReplaceInName\nPerforms a full backup of db1 into the folder \\\\filestore\\backups\\server1\\prod\\db1\\Full\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eBackup-DbaDatabase -SqlInstance Server1\\Prod -Path \\\\filestore\\backups\\servername\\instancename\\dbname\\backuptype -FilePath dbname-backuptype-timestamp.trn -Type Log -ReplaceInName\nPerforms a log backup for every database. For the database db1 this would results in backup files in \\\\filestore\\backups\\server1\\prod\\db1\\Log\\db1-log-31102018.trn\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eBackup-DbaDatabase -SqlInstance Sql2017 -Database master -FilePath NUL\nPerforms a backup of master, but sends the output to the NUL device (ie; throws it away)\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eBackup-DbaDatabase -SqlInstance Sql2016 -Database stripetest -AzureBaseUrl https://az.blob.core.windows.net/sql,https://dbatools.blob.core.windows.net/sql\nPerforms a backup of the database stripetest, striping it across the 2 Azure blob containers at https://az.blob.core.windows.net/sql and https://dbatools.blob.core.windows.net/sql, assuming that \r\nShared Access Signature credentials for both containers exist on the source instance\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003eBackup-DbaDatabase -SqlInstance Sql2017 -Database master -EncryptionAlgorithm AES256 -EncryptionCertificate BackupCert\nBacks up the master database using the BackupCert certificate and the AES256 algorithm.\n-------------------------- EXAMPLE 10 --------------------------\nPS C:\\\u003eBackup-DbaDatabase -SqlInstance sql2022 -Database AdventureWorks -StorageBaseUrl \"s3://mybucket.s3.us-west-2.amazonaws.com/backups\" -Type Full -CompressBackup\nPerforms a full compressed backup of the AdventureWorks database to an S3-compatible storage bucket. Requires SQL Server 2022 or later and a credential matching the S3 URL created with \r\nNew-DbaCredential using Identity \u0027S3 Access Key\u0027.\n-------------------------- EXAMPLE 11 --------------------------\nPS C:\\\u003eBackup-DbaDatabase -SqlInstance sql2022 -Database AdventureWorks -S3BaseUrl \"s3://minio.local:9000/sqlbackups\" -Type Full\nPerforms a full backup to a MinIO S3-compatible storage server using the S3BaseUrl alias. The credential must be created to match the S3 URL path.\n-------------------------- EXAMPLE 12 --------------------------\nPS C:\\\u003eBackup-DbaDatabase -SqlInstance sql2022 -Database AdventureWorks -StorageBaseUrl \"s3://mybucket.s3.amazonaws.com/backups\" -StorageRegion \"us-west-2\" -MaxTransferSize 10485760 -Type Full\nPerforms a full backup to S3 with explicit region specification and a 10MB transfer size. The StorageRegion parameter adds BACKUP_OPTIONS to the backup command for cross-region scenarios.", "Description": "Creates full, differential, or transaction log backups for SQL Server databases with support for local file systems, Azure blob storage, and advanced backup features like compression, encryption, and striping. Handles backup validation, automatic path creation, and flexible file naming conventions to support both automated and manual backup workflows. Integrates with SQL Server\u0027s native backup infrastructure while providing PowerShell-friendly output for backup monitoring and compliance reporting. Replaces manual T-SQL backup commands with a single cmdlet that manages backup destinations, validates paths, and returns detailed backup metadata.", "Links": "https://dbatools.io/Backup-DbaDatabase", "Synopsis": "Creates database backups with flexible destination options and enterprise backup features.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The SQL Server instance hosting the databases to be backed up.", "", true, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to include in the backup operation. Accepts database names, wildcards, or arrays.\r\nWhen omitted, all user databases are backed up (tempdb is automatically excluded).\r\nUse this to target specific databases instead of backing up the entire instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies which databases to exclude from the backup operation. Accepts database names, wildcards, or arrays.\r\nUseful when you want to backup most databases but skip specific ones like test or temporary databases.\r\nCombined with Database parameter, exclusions are applied after inclusions.", "", false, "false", "", "" ], [ "Path", "Sets the directory path where backup files will be created. Defaults to the instance\u0027s default backup location.\r\nMultiple paths enable striping for improved performance and overrides FileCount parameter.\r\nSQL Server creates missing directories automatically if it has permissions. Striped files are numbered x-of-y for set identification.", "BackupDirectory", false, "false", "", "" ], [ "FilePath", "Specifies the complete backup file name including extension. Only valid for single database backups.\r\nWhen omitted, files are auto-named as DatabaseName_yyyyMMddHHmm with appropriate extensions (.bak, .trn, .dif).\r\nRepeated use appends to the same file at incrementing positions. Use \u0027NUL\u0027 to discard backup output for testing.\r\nAll paths are relative to the SQL Server instance, not the local machine running the command.", "BackupFileName", false, "false", "", "" ], [ "IncrementPrefix", "Prefixes backup files with incremental numbers (1-, 2-, etc.) when striping across multiple files.\r\nPrimarily used for Azure SQL Database platforms where this naming convention may improve restore performance.\r\nOnly applies when FileCount is greater than 1 or multiple paths are specified.", "", false, "false", "False", "" ], [ "ReplaceInName", "Enables dynamic token replacement in file paths and names for flexible backup naming schemes.\r\nReplaces: instancename, servername, dbname, timestamp, backuptype with actual values.\r\nEssential for standardized backup naming across environments and automated backup scripts with consistent file organization.", "", false, "false", "False", "" ], [ "NoAppendDbNameInPath", "Prevents automatic database name folder creation when using CreateFolder parameter.\r\nBy default, CreateFolder adds a database-specific subdirectory for organization.\r\nUse this when you want files directly in the specified path without database name folders.", "", false, "false", "False", "" ], [ "CopyOnly", "Creates copy-only backups that don\u0027t break the restore chain or affect log backup sequences.\r\nEssential for ad-hoc backups during maintenance, before major changes, or for moving databases to other environments.\r\nCopy-only backups don\u0027t reset differential bases or interfere with scheduled backup strategies.", "", false, "false", "False", "" ], [ "Type", "Specifies the backup type to perform: Full, Log, Differential, or Database (same as Full).\r\nLog backups require full recovery model and prior full backup. Differential backups require prior full backup.\r\nChoose based on your recovery objectives and backup strategy requirements.", "", false, "false", "Database", "Full,Log,Differential,Diff,Database" ], [ "InputObject", "Accepts database objects from pipeline for backup operations.\r\nAllows piping databases from Get-DbaDatabase or other dbatools commands.\r\nInternal parameter primarily used for pipeline processing and automation scenarios.", "", true, "true (ByValue)", "", "" ], [ "CreateFolder", "Creates a separate subdirectory for each database within the backup path for better organization.\r\nResults in paths like \u0027BackupPath\\DatabaseName\\BackupFile.bak\u0027 instead of all files in one directory.\r\nParticularly useful for multi-database backups and maintaining organized backup directory structures.", "", false, "false", "False", "" ], [ "FileCount", "Specifies the number of files to stripe the backup across for improved performance.\r\nHigher values increase backup speed but require more disk space and coordination during restores.\r\nAutomatically overridden when multiple Path values are provided. Typically use 2-4 files for optimal performance.\r\nWhen using a single StorageBaseUrl (S3/Azure), an explicit FileCount allows striping multiple backup files into the same bucket/container.\r\nMultiple StorageBaseUrl values determine the stripe count.", "", false, "false", "0", "" ], [ "CompressBackup", "Forces backup compression when supported by SQL Server edition and version (Enterprise/Standard 2008+).\r\nReduces backup file size by 50-80% but increases CPU usage during backup operations.\r\nWhen omitted, uses server default compression setting. Explicitly false disables compression entirely.", "", false, "false", "False", "" ], [ "Checksum", "Enables backup checksum calculation to detect backup corruption during creation and restore.\r\nAdds minimal overhead but provides important data integrity verification for critical backups.\r\nRecommended for production environments to ensure backup reliability and early corruption detection.", "", false, "false", "False", "" ], [ "Verify", "Performs RESTORE VERIFYONLY after backup completion to confirm backup integrity and restorability.\r\nAdds time to backup operations but ensures backups are usable before considering the job complete.\r\nCritical for validating backups in automated processes and compliance requirements.", "", false, "false", "False", "" ], [ "MaxTransferSize", "Controls the size of each data transfer unit during backup operations. Must be a multiple of 64KB.\r\nFor disk and Azure backups: Maximum value is 4MB.\r\nFor S3 backups: Value must be between 5MB and 20MB (required for S3-compatible storage).\r\nLarger values can improve performance for fast storage but may cause memory pressure.\r\nAutomatically set to 128KB for TDE-encrypted databases with compression to avoid conflicts.", "", false, "false", "0", "" ], [ "BlockSize", "Sets the physical block size for backup devices. Must be 0.5KB, 1KB, 2KB, 4KB, 8KB, 16KB, 32KB, or 64KB.\r\nAffects backup file structure and restore performance. Larger blocks may improve performance for fast storage.\r\nCannot be used with Azure page blob backups (when StorageCredential is specified).", "", false, "false", "0", "" ], [ "BufferCount", "Specifies the number of I/O buffers allocated for the backup operation.\r\nMore buffers can improve performance on fast storage but consume additional memory.\r\nSQL Server calculates optimal values automatically, so specify only when performance tuning specific scenarios.", "", false, "false", "0", "" ], [ "StorageBaseUrl", "Specifies cloud storage URLs for backup destinations, supporting Azure Blob Storage and S3-compatible object storage.\r\nFor Azure: Use https:// URLs like \u0027https://account.blob.core.windows.net/container\u0027. Single URL required for page blobs (with StorageCredential), multiple URLs supported for block blobs with SAS.\r\nFor S3: Use s3:// URLs like \u0027s3://bucket.s3.region.amazonaws.com/folder\u0027. Requires SQL Server 2022 or later. Supports AWS S3, MinIO, and other S3-compatible providers.\r\nRequires corresponding SQL Server credentials for authentication. Essential for backing up to cloud storage for cloud-native or hybrid SQL Server deployments.", "AzureBaseUrl,S3BaseUrl", false, "false", "", "" ], [ "StorageCredential", "Specifies the SQL Server credential name for cloud storage authentication.\r\nFor Azure: The credential for storage access key authentication. Creates page blob backups with automatic single-file restriction and ignores BlockSize/MaxTransferSize.\r\nFor S3: The credential containing the S3 Access Key ID and Secret Key ID. The credential name should match the S3 URL path.\r\nFor SAS authentication, use credentials named to match the StorageBaseUrl.", "AzureCredential,S3Credential", false, "false", "", "" ], [ "StorageRegion", "Specifies the AWS region for S3 backups using the BACKUP_OPTIONS JSON parameter. Only applies to S3-compatible storage.\r\nUse this when your S3 bucket is in a specific region that differs from the default, or when required by your S3-compatible provider.\r\nExample regions: us-east-1, us-west-2, eu-west-1, ap-southeast-1.\r\nWhen specified, adds BACKUP_OPTIONS = \u0027{\"s3\": {\"region\":\"\u003cregion\u003e\"}}\u0027 to the backup command.", "S3Region", false, "false", "", "" ], [ "NoRecovery", "Performs transaction log backup without truncating the log, leaving database in restoring state.\r\nEssential for tail-log backups during disaster recovery or before restoring to a point in time.\r\nOnly applicable to log backups and prevents normal database operations until recovery is completed.", "", false, "false", "False", "" ], [ "BuildPath", "Enables automatic creation of missing directory paths when SQL Server has permissions.\r\nBy default, the function expects backup paths to exist and will fail if they don\u0027t.\r\nUseful for automated backup scripts where destination folders might not exist yet.", "", false, "false", "False", "" ], [ "WithFormat", "Formats the backup media before writing, destroying any existing backup sets on the device.\r\nAutomatically enables Initialize and SkipTapeHeader options for complete media initialization.\r\nUse when starting fresh backup sets or when media corruption requires reformatting.", "", false, "false", "False", "" ], [ "Initialize", "Overwrites existing backup sets on the media to start a new backup set.\r\nDestroys all previous backups on the target files/devices but preserves media formatting.\r\nUse when you want to replace old backups without formatting the entire media.", "", false, "false", "False", "" ], [ "SkipTapeHeader", "Skips tape header information during backup operations, primarily for compatibility.\r\nMainly relevant for tape devices and legacy backup scenarios.\r\nAutomatically enabled with WithFormat parameter for proper media initialization.", "", false, "false", "False", "" ], [ "TimeStampFormat", "Customizes the timestamp format used in auto-generated backup file names. Defaults to yyyyMMddHHmm.\r\nMust use valid Get-Date format strings (e.g., \u0027yyyy-MM-dd_HH-mm-ss\u0027 for readable timestamps).\r\nApplied when FilePath is not specified and ReplaceInName contains \u0027timestamp\u0027 placeholder.", "", false, "false", "", "" ], [ "IgnoreFileChecks", "Skips path validation checks before backup operations, useful when SQL Server has limited filesystem access.\r\nBypasses safety checks that normally prevent backup failures due to permissions or missing paths.\r\nUse with caution as it may result in backup failures that could have been prevented.", "", false, "false", "False", "" ], [ "OutputScriptOnly", "Generates and returns the T-SQL BACKUP commands without executing them.\r\nUseful for reviewing backup commands, incorporating into scripts, or troubleshooting backup parameter combinations.\r\nNo actual backup operations occur and no paths are created when using this option.", "", false, "false", "False", "" ], [ "EncryptionAlgorithm", "Specifies the encryption algorithm for backup encryption: AES128, AES192, AES256, or TRIPLEDES.\r\nRequires either EncryptionCertificate or EncryptionKey for the encryption process.\r\nAES256 recommended for maximum security, though it may impact backup performance on older hardware.", "", false, "false", "", "AES128,AES192,AES256,TRIPLEDES" ], [ "EncryptionCertificate", "Specifies the certificate name in the master database for backup encryption.\r\nCertificate existence is validated before backup begins to prevent failures mid-operation.\r\nMutually exclusive with EncryptionKey. Essential for protecting sensitive data in backup files.", "", false, "false", "", "" ], [ "Description", "Adds a description to the backup set metadata for documentation and identification purposes.\r\nLimited to 255 characters and stored in MSDB backup history for backup set identification.\r\nUseful for tracking backup purposes, change sets, or special circumstances around the backup timing.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "CertBackup", "Certificate", "Backup" ], "CommandName": "Backup-DbaDbCertificate", "Name": "Backup-DbaDbCertificate", "Author": "Jess Pomfret (@jpomfret)", "Syntax": "Backup-DbaDbCertificate [-SqlCredential \u003cPSCredential\u003e] [-EncryptionPassword \u003cSecureString\u003e] [-DecryptionPassword \u003cSecureString\u003e] [-Path \u003cFileInfo\u003e] [-Suffix \u003cString\u003e] [-FileBaseName \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nBackup-DbaDbCertificate -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Certificate \u003cObject[]\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-EncryptionPassword \u003cSecureString\u003e] [-DecryptionPassword \u003cSecureString\u003e] [-Path \u003cFileInfo\u003e] [-Suffix \u003cString\u003e] [-FileBaseName \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nBackup-DbaDbCertificate [-SqlCredential \u003cPSCredential\u003e] [-EncryptionPassword \u003cSecureString\u003e] [-DecryptionPassword \u003cSecureString\u003e] [-Path \u003cFileInfo\u003e] [-Suffix \u003cString\u003e] [-FileBaseName \u003cString\u003e] [-InputObject \u003cCertificate[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per certificate that was successfully exported.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The name of the computer hosting the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: The name of the database containing the certificate\r\n- DatabaseID: The unique identifier of the database\r\n- Certificate: The name of the certificate that was backed up\r\n- Path: The file path where the certificate (.cer file) was saved\r\n- Key: The file path where the private key (.pvk file) was saved, or a message if not exported\r\n- Status: Result status of the export operation (Success or error message)\nAdditional properties available:\r\n- ExportPath: Same as Path property\r\n- ExportKey: Same as Key property\r\n- exportPathCert: Internal property - same as Path\r\n- exportPathKey: Internal property - same as Key", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eBackup-DbaDbCertificate -SqlInstance Server1\nExports all the certificates on the specified SQL Server to the default data path for the instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Backup-DbaDbCertificate -SqlInstance Server1 -SqlCredential $cred\nConnects using sqladmin credential and exports all the certificates on the specified SQL Server to the default data path for the instance.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eBackup-DbaDbCertificate -SqlInstance Server1 -Certificate Certificate1\nExports only the certificate named Certificate1 on the specified SQL Server to the default data path for the instance.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eBackup-DbaDbCertificate -SqlInstance Server1 -Database AdventureWorks\nExports only the certificates for AdventureWorks on the specified SQL Server to the default data path for the instance.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eBackup-DbaDbCertificate -SqlInstance Server1 -ExcludeDatabase AdventureWorks\nExports all certificates except those for AdventureWorks on the specified SQL Server to the default data path for the instance.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eBackup-DbaDbCertificate -SqlInstance Server1 -Path \\\\Server1\\Certificates -EncryptionPassword (Get-Credential NoUsernameNeeded).Password\nExports all the certificates and private keys on the specified SQL Server.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003e$EncryptionPassword = (Get-Credential NoUsernameNeeded).Password\nPS C:\\\u003e $DecryptionPassword = (Get-Credential NoUsernameNeeded).Password\r\nPS C:\\\u003e Backup-DbaDbCertificate -SqlInstance Server1 -EncryptionPassword $EncryptionPassword -DecryptionPassword $DecryptionPassword\nExports all the certificates on the specified SQL Server using the supplied DecryptionPassword, since an EncryptionPassword is specified private keys are also exported.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eBackup-DbaDbCertificate -SqlInstance Server1 -Path \\\\Server1\\Certificates\nExports all certificates on the specified SQL Server to the specified path.\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003eBackup-DbaDbCertificate -SqlInstance Server1 -Suffix DbaTools\nExports all certificates on the specified SQL Server to the specified path, appends DbaTools to the end of the filenames.\n-------------------------- EXAMPLE 10 --------------------------\nPS C:\\\u003eGet-DbaDbCertificate -SqlInstance sql2016 | Backup-DbaDbCertificate\nExports all certificates found on sql2016 to the default data directory.", "Description": "Backs up database certificates by exporting them to .cer (certificate) and .pvk (private key) files on the SQL Server file system. This is essential for disaster recovery scenarios where you need to restore encrypted databases or migrate certificates to another instance. Without backing up certificates, you cannot decrypt TDE-enabled databases or access data encrypted with certificate-based encryption. Files are saved to the instance\u0027s default backup directory unless a custom path is specified.", "Links": "https://dbatools.io/Backup-DbaDbCertificate", "Synopsis": "Exports database certificates and private keys to physical backup files on SQL Server instances.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.", "", true, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Certificate", "Specifies the names of specific certificates to export instead of backing up all certificates on the instance.\r\nUse this when you only need to backup certain certificates, such as TDE certificates or specific application certificates.", "", false, "false", "", "" ], [ "Database", "Limits the backup operation to certificates associated with specific databases only.\r\nUse this when you need to backup certificates for particular databases, especially before database migrations or when creating targeted disaster recovery plans.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies databases whose certificates should be excluded from the backup operation.\r\nUse this to skip system databases or test databases when performing bulk certificate exports across the instance.", "", false, "false", "", "" ], [ "EncryptionPassword", "Secure password used to encrypt the private key (.pvk) file during export, enabling backup of both certificate and private key components.\r\nRequired when you need to backup the private key for disaster recovery scenarios where the certificate must be restored with the ability to decrypt data.", "", false, "false", "", "" ], [ "DecryptionPassword", "Password required to decrypt the certificate\u0027s existing private key before it can be re-encrypted for backup.\r\nUse this when the certificate was created with a password or imported from another source that had password protection.", "", false, "false", "", "" ], [ "Path", "Directory path on the SQL Server where certificate backup files will be saved, specified from the SQL Server\u0027s perspective.\r\nDefaults to the instance\u0027s backup directory if not specified. Use UNC paths for network storage or local paths accessible by the SQL Server service account.", "", false, "false", "", "" ], [ "Suffix", "Text appended to the end of backup file names to help organize or identify different backup sets.\r\nUse this to distinguish between different backup runs or environments, such as \"Prod\" or \"DR-Test\".", "", false, "false", "", "" ], [ "FileBaseName", "Custom base name for the backup files instead of the default \"instance-database-certificate\" naming format.\r\nUse this when exporting a single certificate and you want specific file names for easier identification or scripted restore processes.", "", false, "false", "", "" ], [ "InputObject", "Certificate objects piped from Get-DbaDbCertificate for processing specific certificates found by that command.\r\nUse this parameter when you need to filter or validate certificates before backing them up.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "CertBackup", "Certificate", "Backup" ], "CommandName": "Backup-DbaDbMasterKey", "Name": "Backup-DbaDbMasterKey", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Backup-DbaDbMasterKey [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-ExcludeDatabase] \u003cString[]\u003e] [[-SecurePassword] \u003cSecureString\u003e] [[-Path] \u003cString\u003e] [[-FileBaseName] \u003cString\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.MasterKey\nReturns one MasterKey object per database that was successfully backed up. Each object is enhanced with additional properties describing the backup operation result.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: Name of the database containing the master key\r\n- Path: The full file path where the master key backup was saved\r\n- Status: Result of the backup operation (\"Success\" or \"Failure\")\nAdditional properties available (added by this function):\r\n- DatabaseID: The ID (GUID) of the database containing the master key\r\n- Filename: The complete file path where the master key backup was exported\nAll properties from the base SMO MasterKey object are also accessible:\r\n- CreateDate: DateTime when the master key was created\r\n- DateLastModified: DateTime when the master key was last modified\r\n- IsEncryptedByServer: Boolean indicating if the master key is encrypted by the server master key", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eBackup-DbaDbMasterKey -SqlInstance server1\\sql2016\n\u003e\u003e ComputerName : SERVER1\r\n\u003e\u003e InstanceName : SQL2016\r\n\u003e\u003e SqlInstance : SERVER1\\SQL2016\r\n\u003e\u003e Filename : E:\\MSSQL13.SQL2016\\MSSQL\\Backup\\server1$sql2016-SMK-20170614162311.key\r\n\u003e\u003e Status : Success\nPrompts for export password, then logs into server1\\sql2016 with Windows credentials then backs up all database keys to the default backup directory.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eBackup-DbaDbMasterKey -SqlInstance Server1 -Database db1 -Path \\\\nas\\sqlbackups\\keys\nLogs into sql2016 with Windows credentials then backs up db1\u0027s keys to the \\\\nas\\sqlbackups\\keys directory.", "Description": "Creates encrypted backup files of database master keys from one or more SQL Server databases. Database master keys are essential for Transparent Data Encryption (TDE), column-level encryption, and other SQL Server encryption features.\n\nThis function is critical for disaster recovery planning since losing a database master key makes encrypted data permanently inaccessible. The exported keys are password-protected and can be restored using Restore-DbaDbMasterKey or T-SQL commands.\n\nWorks with databases that contain master keys and saves backup files to the server\u0027s default backup directory or a specified path. Each backup file uses a unique naming convention to prevent overwrites during multiple exports.", "Links": "https://dbatools.io/Backup-DbaDbMasterKey", "Synopsis": "Exports database master keys to encrypted backup files for disaster recovery and compliance.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Credential", "Pass a credential object for the password", "", false, "false", "", "" ], [ "Database", "Specifies which databases to export master keys from. Only databases containing master keys will be processed.\r\nUse this when you need to backup encryption keys from specific databases rather than all databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific databases from master key backup operations. Auto-completes with available database names.\r\nUseful when backing up master keys from most databases but skipping test, development, or non-encrypted databases.", "", false, "false", "", "" ], [ "SecurePassword", "Password used to encrypt the exported master key backup files. Must be provided as a SecureString object.\r\nThis password will be required when restoring the master keys, so store it securely with your backup documentation.\r\nIf not specified, you\u0027ll be prompted to enter the password interactively for each database.", "Password", false, "false", "", "" ], [ "Path", "Directory path where master key backup files will be saved. Accepts local paths or UNC network shares.\r\nDefaults to the SQL Server instance\u0027s configured backup directory if not specified.\r\nThe SQL Server service account must have write permissions to the specified location.", "", false, "false", "", "" ], [ "FileBaseName", "Overrides the default file naming convention with a custom base name for the backup file.\r\nUseful when exporting a single database\u0027s master key and you want a specific filename for documentation or automation.\r\nThe \".key\" extension is automatically appended to whatever name you specify.", "", false, "false", "", "" ], [ "InputObject", "Accepts database objects piped from Get-DbaDatabase or other dbatools database commands.\r\nAllows you to filter databases using Get-DbaDatabase parameters before piping to this function for master key backup.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "Shows what would happen if the command were to run. No actions are actually performed.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before executing any changing operations within the command.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "CertBackup", "Certificate", "Backup" ], "CommandName": "Backup-DbaServiceMasterKey", "Name": "Backup-DbaServiceMasterKey", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Backup-DbaServiceMasterKey [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-KeyCredential] \u003cPSCredential\u003e] [[-SecurePassword] \u003cSecureString\u003e] [[-Path] \u003cString\u003e] [[-FileBaseName] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.ServiceMasterKey\nReturns one ServiceMasterKey object per instance provided as input. The object includes added properties tracking the backup operation results.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Path: The full file path where the Service Master Key backup was exported\r\n- Status: Result of the backup operation (Success or Failure)\nAdditional properties available from the base SMO ServiceMasterKey object and added NoteProperties:\r\n- Filename: Alias for Path - the full file path where the Service Master Key backup was exported\r\nAll other properties from the SMO ServiceMasterKey object are accessible via Select-Object *", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eBackup-DbaServiceMasterKey -SqlInstance server1\\sql2016\n\u003e\u003e ComputerName : SERVER1\r\n\u003e\u003e InstanceName : SQL2016\r\n\u003e\u003e SqlInstance : SERVER1\\SQL2016\r\n\u003e\u003e Filename : E:\\MSSQL13.SQL2016\\MSSQL\\Backup\\server1$sql2016-SMK-20170614162311.key\r\n\u003e\u003e Status : Success\nPrompts for export password, then logs into server1\\sql2016 with Windows credentials then backs up the service master key to the default backup directory.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eBackup-DbaServiceMasterKey -SqlInstance Server1 -Path \\\\nas\\sqlbackups\\keys\nLogs into sql2016 with Windows credentials then backs up the service master key to the \\\\nas\\sqlbackups\\keys directory.", "Description": "Creates an encrypted backup of the SQL Server Service Master Key (SMK), which sits at the top of SQL Server\u0027s encryption hierarchy. The Service Master Key encrypts Database Master Keys and certificates, making its backup critical for disaster recovery scenarios where encrypted databases need to be restored or moved between servers. The backup file is password-protected and can be stored in the default backup directory or a custom location. This prevents the need to manually recreate encryption keys and certificates when rebuilding servers or migrating encrypted databases.", "Links": "https://dbatools.io/Backup-DbaServiceMasterKey", "Synopsis": "Exports SQL Server Service Master Key to an encrypted backup file for disaster recovery.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "KeyCredential", "Provides an alternative way to pass the encryption password using a PowerShell credential object.\r\nUse this when you need to automate the backup process without interactive password prompts or when integrating with credential management systems.", "", false, "false", "", "" ], [ "SecurePassword", "Sets the password used to encrypt the Service Master Key backup file. Must be provided as a SecureString object for security.\r\nIf not specified, you\u0027ll be prompted to enter the password interactively. Store this password securely as it\u0027s required to restore the Service Master Key during disaster recovery.", "Password", false, "false", "", "" ], [ "Path", "Specifies the directory where the Service Master Key backup file will be created. Defaults to the SQL Server instance\u0027s configured backup directory if not specified.\r\nUse this when you need to store the backup in a specific location for compliance, network storage, or organizational requirements.", "", false, "false", "", "" ], [ "FileBaseName", "Overrides the default naming convention to use a custom base name for the backup file. The system automatically appends \".key\" to whatever name you provide.\r\nUse this when you need predictable file names for automation scripts or when following specific naming standards in your environment.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "Shows what would happen if the command were to run. No actions are actually performed.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before executing any changing operations within the command.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Diagnostic", "Connection" ], "CommandName": "Clear-DbaConnectionPool", "Name": "Clear-DbaConnectionPool", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Clear-DbaConnectionPool [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "None\nThis command does not return any output. It performs an action to clear connection pools on the specified computer(s) and completes silently on success.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eClear-DbaConnectionPool\nClears all local connection pools.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eClear-DbaConnectionPool -ComputerName workstation27\nClears all connection pools on workstation27.", "Description": "Clears all SQL Server connection pools managed by the .NET SqlClient on the target computer. This forces any pooled connections to be discarded and recreated on the next connection attempt.\n\nConnection pools can sometimes retain stale or problematic connections that cause intermittent connectivity issues, authentication failures, or performance problems. This command helps resolve these issues by forcing a clean slate for all SQL Server connections from that computer.\n\nActive connections are marked for disposal and will be discarded when closed, rather than returned to the pool. New connections will be created fresh from the pool after clearing.\n\nRef: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.clearallpools(v=vs.110).aspx", "Links": "https://dbatools.io/Clear-DbaConnectionPool", "Synopsis": "Clears all SQL Server connection pools on the specified computer to resolve connection issues.", "Availability": "Windows only", "Params": [ [ "ComputerName", "Specifies the computer(s) where SQL Server connection pools should be cleared. Accepts multiple computer names and supports pipeline input.\r\nUse this when connection pool issues are occurring on specific client machines or application servers connecting to SQL Server.\r\nDefaults to the local computer if not specified.", "cn,host,Server", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Alternate credential object to use for accessing the target computer(s).", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Diagnostic", "LatchStatistic", "Waits" ], "CommandName": "Clear-DbaLatchStatistics", "Name": "Clear-DbaLatchStatistics", "Author": "Patrick Flynn (@sqllensman)", "Syntax": "Clear-DbaLatchStatistics [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance specified. The object contains the result of clearing latch statistics for that instance.\nProperties:\r\n- ComputerName: The computer name of the target SQL Server instance\r\n- InstanceName: The SQL Server service/instance name\r\n- SqlInstance: The full SQL Server instance name in domain\\instance format\r\n- Status: \"Success\" if the DBCC SQLPERF command executed successfully, or an exception object if an error occurred", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eClear-DbaLatchStatistics -SqlInstance sql2008, sqlserver2012\nAfter confirmation, clears latch statistics on servers sql2008 and sqlserver2012\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eClear-DbaLatchStatistics -SqlInstance sql2008, sqlserver2012 -Confirm:$false\nClears latch statistics on servers sql2008 and sqlserver2012, without prompting\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e\u0027sql2008\u0027,\u0027sqlserver2012\u0027 | Clear-DbaLatchStatistics\nAfter confirmation, clears latch statistics on servers sql2008 and sqlserver2012\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Clear-DbaLatchStatistics -SqlInstance sql2008 -SqlCredential $cred\nConnects using sqladmin credential and clears latch statistics on servers sql2008 and sqlserver2012", "Description": "Clears all accumulated latch statistics from the sys.dm_os_latch_stats dynamic management view by executing DBCC SQLPERF (N\u0027sys.dm_os_latch_stats\u0027, CLEAR). This resets counters for latch types like BUFFER, ACCESS_METHODS_DATASET_PARENT, and others to zero values.\n\nUse this when troubleshooting latch contention to get a clean baseline before running your workload, or during performance testing to measure the impact of specific queries or operations. After clearing statistics, you can monitor sys.dm_os_latch_stats to see which latch types are experiencing the most waits and timeouts in your current workload.", "Links": "https://dbatools.io/Clear-DbaLatchStatistics", "Synopsis": "Resets SQL Server latch statistics counters to establish a fresh performance baseline", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "Allows you to specify a comma separated list of servers to query.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Diagnostic", "Memory" ], "CommandName": "Clear-DbaPlanCache", "Name": "Clear-DbaPlanCache", "Author": "Tracy Boggiano, databasesuperhero.com", "Syntax": "Clear-DbaPlanCache [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Threshold] \u003cInt32\u003e] [[-InputObject] \u003cObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per plan cache result processed. The object contains the following properties:\n- ComputerName: The name of the computer running the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The fully qualified SQL Server instance name (computer\\instance)\r\n- Size: The size of the plan cache (displayed with appropriate units)\r\n- Status: The result of the operation - either \"Plan cache cleared\" if the cache exceeded the threshold and was cleared, or \"Plan cache size below threshold (X)\" if the size was under the specified \r\nthreshold", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eClear-DbaPlanCache -SqlInstance sql2017 -Threshold 200\nLogs into the SQL Server instance \"sql2017\" and removes plan caches if over 200 MB.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eClear-DbaPlanCache -SqlInstance sql2017 -SqlCredential sqladmin\nLogs into the SQL instance using the SQL Login \u0027sqladmin\u0027 and then Windows instance as \u0027ad\\sqldba\u0027\r\nand removes if Threshold over 100 MB.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eFind-DbaInstance -ComputerName localhost | Get-DbaPlanCache | Clear-DbaPlanCache -Threshold 200\nScans localhost for instances using the browser service, traverses all instances and gets the plan cache for each, clears them out if they are above 200 MB.", "Description": "Monitors your SQL Server\u0027s plan cache for single-use adhoc and prepared plans that consume excessive memory. When these plans exceed the specified threshold (default 100MB), the function clears the entire plan cache using DBCC FREESYSTEMCACHE(\u0027SQL Plans\u0027).\n\nSingle-use plans are a common cause of memory pressure in SQL Server environments with dynamic SQL or applications that don\u0027t use parameterized queries. Instead of manually checking sys.dm_exec_cached_plans and running DBCC commands, this function automates the detection and cleanup process.\n\nUse this when you\u0027re experiencing memory pressure from plan cache bloat or as part of regular maintenance to prevent cache-related performance issues. The function only clears the cache when necessary, avoiding unnecessary disruption to your server\u0027s performance.\n\nReferences: https://www.sqlskills.com/blogs/kimberly/plan-cache-adhoc-workloads-and-clearing-the-single-use-plan-cache-bloat/", "Links": "https://dbatools.io/Clear-DbaPlanCache", "Synopsis": "Clears SQL Server plan cache when single-use adhoc and prepared plans exceed memory threshold", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Threshold", "Specifies the memory threshold in megabytes for single-use adhoc and prepared plans before the plan cache is cleared. Default is 100 MB.\r\nUse this to control when plan cache cleanup occurs based on your server\u0027s memory capacity and workload patterns.", "", false, "false", "100", "" ], [ "InputObject", "Accepts plan cache objects from Get-DbaPlanCache via pipeline input. Each object contains plan cache statistics including memory usage and instance details.\r\nUse this to process multiple instances or when you need to filter plan cache results before clearing.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Diagnostic", "WaitStats", "Waits" ], "CommandName": "Clear-DbaWaitStatistics", "Name": "Clear-DbaWaitStatistics", "Author": "Chrissy LeMaire (@cl)", "Syntax": "Clear-DbaWaitStatistics [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance, confirming the operation status.\nProperties:\r\n- ComputerName: The name of the computer hosting the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (ComputerName\\InstanceName)\r\n- Status: Either \"Success\" if the wait statistics were cleared, or the exception message if the operation failed", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eClear-DbaWaitStatistics -SqlInstance sql2008, sqlserver2012\nAfter confirmation, clears wait stats on servers sql2008 and sqlserver2012\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eClear-DbaWaitStatistics -SqlInstance sql2008, sqlserver2012 -Confirm:$false\nClears wait stats on servers sql2008 and sqlserver2012, without prompting", "Description": "Clears all accumulated wait statistics from sys.dm_os_wait_stats by executing DBCC SQLPERF (N\u0027sys.dm_os_wait_stats\u0027, CLEAR). This is essential for performance troubleshooting when you need to establish a new baseline for wait analysis. DBAs commonly clear wait stats after resolving performance issues, during maintenance windows, or when beginning focused monitoring periods to isolate specific workload patterns without historical noise.", "Links": "https://dbatools.io/Clear-DbaWaitStatistics", "Synopsis": "Resets SQL Server wait statistics to establish a clean monitoring baseline", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "AvailabilityGroup", "AG", "Job", "Agent" ], "CommandName": "Compare-DbaAgReplicaAgentJob", "Name": "Compare-DbaAgReplicaAgentJob", "Author": "dbatools team", "Syntax": "Compare-DbaAgReplicaAgentJob [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-AvailabilityGroup] \u003cString[]\u003e] [-ExcludeSystemJob] [-IncludeModifiedDate] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object for each job difference detected across Availability Group replicas. Objects are only returned when differences are found (missing jobs or differing modification dates when \r\n-IncludeModifiedDate is specified).\nProperties:\r\n- AvailabilityGroup: The name of the Availability Group being compared\r\n- Replica: The SQL Server instance name where the job status applies\r\n- JobName: The name of the SQL Agent job\r\n- Status: Job status on this replica (either \"Present\" or \"Missing\")\r\n- DateLastModified: DateTime when the job was last modified, or $null if the job is missing on this replica (only populated when -IncludeModifiedDate is specified or job is present)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCompare-DbaAgReplicaAgentJob -SqlInstance sql2016 -AvailabilityGroup AG1\nCompares all SQL Agent Jobs across replicas in the AG1 Availability Group.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCompare-DbaAgReplicaAgentJob -SqlInstance sql2016 -AvailabilityGroup AG1 -ExcludeSystemJob\nCompares user-created SQL Agent Jobs across replicas, excluding system jobs.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCompare-DbaAgReplicaAgentJob -SqlInstance sql2016 -AvailabilityGroup AG1 -IncludeModifiedDate\nCompares SQL Agent Jobs including their DateLastModified property to detect configuration drift.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sql2016 | Compare-DbaAgReplicaAgentJob\nCompares SQL Agent Jobs for all Availability Groups on sql2016 via pipeline input.", "Description": "Compares SQL Agent Jobs across all replicas in an Availability Group to identify differences in job configurations. This helps ensure consistency across AG replicas and detect when jobs have been modified on one replica but not others.\n\nThis is particularly useful for verifying that junior DBAs have applied changes to all replicas or for troubleshooting issues where job configurations have drifted between replicas.\n\nBy default, compares job names and their presence/absence. Use -IncludeModifiedDate to also compare DateLastModified timestamps to detect configuration drift.", "Links": "https://dbatools.io/Compare-DbaAgReplicaAgentJob", "Synopsis": "Compares SQL Agent Jobs across Availability Group replicas to identify configuration differences.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. Can be any replica in the Availability Group.", "", false, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "AvailabilityGroup", "Specifies one or more Availability Group names to compare jobs across their replicas.", "", false, "false", "", "" ], [ "ExcludeSystemJob", "Excludes system jobs from the comparison results.\r\nUse this to focus on user-created jobs and ignore built-in SQL Server jobs.", "", false, "false", "False", "" ], [ "IncludeModifiedDate", "Includes DateLastModified comparison in addition to job name comparison.\r\nUse this to detect when jobs have been reconfigured on some replicas but not others.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "AvailabilityGroup", "AG", "Credential", "Security" ], "CommandName": "Compare-DbaAgReplicaCredential", "Name": "Compare-DbaAgReplicaCredential", "Author": "dbatools team", "Syntax": "Compare-DbaAgReplicaCredential [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-AvailabilityGroup] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per credential that has configuration differences across replicas in the Availability Group.\nProperties:\r\n- AvailabilityGroup: The name of the Availability Group being compared\r\n- Replica: The name of the replica instance where the credential status was checked\r\n- CredentialName: The name of the SQL Server credential\r\n- Status: The credential state on this replica (\"Present\" if the credential exists, \"Missing\" if it doesn\u0027t)\r\n- Identity: The credential\u0027s identity/principal on replicas where the credential is Present; $null where Status is \"Missing\"\nOnly credentials with differences (missing on at least one replica or having different identities across replicas) are returned.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCompare-DbaAgReplicaCredential -SqlInstance sql2016 -AvailabilityGroup AG1\nCompares all SQL Server Credentials across replicas in the AG1 Availability Group.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sql2016 | Compare-DbaAgReplicaCredential\nCompares SQL Server Credentials for all Availability Groups on sql2016 via pipeline input.", "Description": "Compares SQL Server Credentials across all replicas in an Availability Group to identify differences in credential configurations. This helps ensure consistency across AG replicas and detect when credentials have been created or removed on one replica but not others.\n\nThis is particularly useful for verifying that junior DBAs have applied security changes to all replicas or for troubleshooting issues where credential configurations have drifted between replicas.\n\nCompares credential names and their associated identities to detect configuration drift.", "Links": "https://dbatools.io/Compare-DbaAgReplicaCredential", "Synopsis": "Compares SQL Server Credentials across Availability Group replicas to identify configuration differences.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. Can be any replica in the Availability Group.", "", false, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "AvailabilityGroup", "Specifies one or more Availability Group names to compare credentials across their replicas.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "AvailabilityGroup", "AG", "Login", "Security" ], "CommandName": "Compare-DbaAgReplicaLogin", "Name": "Compare-DbaAgReplicaLogin", "Author": "dbatools team", "Syntax": "Compare-DbaAgReplicaLogin [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-AvailabilityGroup] \u003cString[]\u003e] [-ExcludeSystemLogin] [-IncludeModifiedDate] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object for each login that differs across replicas in the Availability Group. Logins that are present and identical on all replicas are not returned.\nProperties:\r\n- AvailabilityGroup: The name of the Availability Group being compared\r\n- Replica: The name of the SQL Server replica instance\r\n- LoginName: The name of the login account\r\n- Status: Current status of the login on this replica (\"Present\" or \"Missing\")\r\n- ModifyDate: The datetime when the login was last modified on this replica (null if Status is \"Missing\"; only populated with accurate data when -IncludeModifiedDate is specified)\r\n- CreateDate: The datetime when the login was created on this replica (null if Status is \"Missing\")\nWhen -IncludeModifiedDate is specified, ModifyDate contains the exact modification timestamp from sys.server_principals. Without this switch, ModifyDate may be null in output objects.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCompare-DbaAgReplicaLogin -SqlInstance sql2016 -AvailabilityGroup AG1\nCompares all SQL Server logins across replicas in the AG1 Availability Group.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCompare-DbaAgReplicaLogin -SqlInstance sql2016 -AvailabilityGroup AG1 -ExcludeSystemLogin\nCompares user-created SQL Server logins across replicas, excluding system logins.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCompare-DbaAgReplicaLogin -SqlInstance sql2016 -AvailabilityGroup AG1 -IncludeModifiedDate\nCompares SQL Server logins including their modify_date property to detect configuration drift.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sql2016 | Compare-DbaAgReplicaLogin\nCompares SQL Server logins for all Availability Groups on sql2016 via pipeline input.", "Description": "Compares SQL Server logins across all replicas in an Availability Group to identify differences in login configurations. This helps ensure consistency across AG replicas and detect when logins have been created, modified, or removed on one replica but not others.\n\nThis is particularly useful for verifying that junior DBAs have applied security changes to all replicas or for troubleshooting access issues where login configurations have drifted between replicas.\n\nBy default, compares login names and their presence/absence. Use -IncludeModifiedDate to also compare modify_date timestamps from sys.server_principals to detect configuration drift.", "Links": "https://dbatools.io/Compare-DbaAgReplicaLogin", "Synopsis": "Compares SQL Server logins across Availability Group replicas to identify configuration differences.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. Can be any replica in the Availability Group.", "", false, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "AvailabilityGroup", "Specifies one or more Availability Group names to compare logins across their replicas.", "", false, "false", "", "" ], [ "ExcludeSystemLogin", "Excludes built-in system logins from the comparison results.\r\nUse this to focus on user-created logins and ignore built-in SQL Server logins.", "", false, "false", "False", "" ], [ "IncludeModifiedDate", "Includes modify_date comparison in addition to login name comparison.\r\nUse this to detect when logins have been reconfigured on some replicas but not others.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "AvailabilityGroup", "AG", "Operator", "Agent" ], "CommandName": "Compare-DbaAgReplicaOperator", "Name": "Compare-DbaAgReplicaOperator", "Author": "dbatools team", "Syntax": "Compare-DbaAgReplicaOperator [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-AvailabilityGroup] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per detected operator configuration difference across replicas. Objects are returned only when an operator configuration differs between replicas (either present on some replicas \r\nbut missing on others, or present with different email addresses).\nProperties:\r\n- AvailabilityGroup: Name of the Availability Group being compared\r\n- Replica: The SQL Server instance name of the replica\r\n- OperatorName: Name of the SQL Agent operator\r\n- Status: Configuration status of the operator on this replica (\"Present\" or \"Missing\")\r\n- EmailAddress: Email address of the operator (null if Status is \"Missing\")", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCompare-DbaAgReplicaOperator -SqlInstance sql2016 -AvailabilityGroup AG1\nCompares all SQL Agent Operators across replicas in the AG1 Availability Group.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sql2016 | Compare-DbaAgReplicaOperator\nCompares SQL Agent Operators for all Availability Groups on sql2016 via pipeline input.", "Description": "Compares SQL Agent Operators across all replicas in an Availability Group to identify differences in operator configurations. This helps ensure consistency across AG replicas and detect when operators have been created or removed on one replica but not others.\n\nThis is particularly useful for verifying that junior DBAs have applied alert notification changes to all replicas or for troubleshooting issues where operator configurations have drifted between replicas.\n\nCompares operator names and their email addresses to detect configuration drift.", "Links": "https://dbatools.io/Compare-DbaAgReplicaOperator", "Synopsis": "Compares SQL Agent Operators across Availability Group replicas to identify configuration differences.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. Can be any replica in the Availability Group.", "", false, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "AvailabilityGroup", "Specifies one or more Availability Group names to compare operators across their replicas.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "AvailabilityGroup", "AG", "Sync", "Compare" ], "CommandName": "Compare-DbaAgReplicaSync", "Name": "Compare-DbaAgReplicaSync", "Author": "the dbatools team + Claude", "Syntax": "Compare-DbaAgReplicaSync [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-AvailabilityGroup] \u003cString[]\u003e] [[-Exclude] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per difference detected across the Availability Group replicas. Each object represents a synchronization discrepancy that would impact failover readiness.\nProperties:\r\n- AvailabilityGroup: Name of the Availability Group being compared\r\n- Replica: Name of the replica where the discrepancy was detected\r\n- ObjectType: Type of object with the difference (Login, AgentJob, Credential, LinkedServer, AgentOperator, AgentAlert, AgentProxy, CustomError)\r\n- ObjectName: Name of the specific object that differs\r\n- Status: Current state of the object (\"Missing\" when object exists on another replica but not this one, \"Different\" when object exists but has different configuration)\r\n- PropertyDifferences: String containing details of property differences (populated only for Login objects when Status is \"Different\"; null for other object types or when Status is \"Missing\")", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCompare-DbaAgReplicaSync -SqlInstance sql2016 -AvailabilityGroup AG1\nCompares all server-level objects across replicas in the AG1 Availability Group and reports differences.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCompare-DbaAgReplicaSync -SqlInstance sql2016 -AvailabilityGroup AG1 -Exclude LinkedServers, DatabaseMail\nCompares server-level objects excluding LinkedServers and DatabaseMail configurations.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sql2016 | Compare-DbaAgReplicaSync\nCompares server-level objects for all Availability Groups on sql2016 via pipeline input.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eCompare-DbaAgReplicaSync -SqlInstance sql2016 -AvailabilityGroup AG1 | Where-Object Status -eq \"Missing\"\nShows only objects that are missing on one or more replicas.", "Description": "Compares server-level objects across all replicas in an Availability Group to identify differences that would prevent seamless failover. Availability groups only synchronize databases, not the server-level dependencies that applications need to function properly after failover.\n\nThis command reports differences without making any changes, making it ideal for monitoring, alerting, and situations where you need to review differences before deciding how to handle them.\n\nBy default, compares these object types across all replicas:\n\nSpConfigure\nCustomErrors\nCredentials\nDatabaseMail\nLinkedServers\nLogins\nSystemTriggers\nAgentCategory\nAgentOperator\nAgentAlert\nAgentProxy\nAgentSchedule\nAgentJob\n\nAny of these object types can be excluded using the -Exclude parameter. The command returns structured data showing what objects are missing or different on each replica.", "Links": "https://dbatools.io/Compare-DbaAgReplicaSync", "Synopsis": "Compares server-level objects across Availability Group replicas to identify synchronization differences.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. Can be any replica in the Availability Group.", "", false, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "AvailabilityGroup", "Specifies one or more Availability Group names to compare objects across their replicas.", "", false, "false", "", "" ], [ "Exclude", "Excludes specific object types from comparison. Valid values:\nSpConfigure, CustomErrors, Credentials, DatabaseMail, LinkedServers, Logins,\r\nSystemTriggers, AgentCategory, AgentOperator, AgentAlert, AgentProxy, AgentSchedule, AgentJob", "", false, "false", "", "AgentCategory,AgentOperator,AgentAlert,AgentProxy,AgentSchedule,AgentJob,Credentials,CustomErrors,DatabaseMail,LinkedServers,Logins,SpConfigure,SystemTriggers" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "AvailabilityGroup", "AG", "Job", "Login", "Credential", "Operator" ], "CommandName": "Compare-DbaAvailabilityGroup", "Name": "Compare-DbaAvailabilityGroup", "Author": "dbatools team", "Syntax": "Compare-DbaAvailabilityGroup [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-AvailabilityGroup] \u003cString[]\u003e] [[-Type] \u003cString[]\u003e] [-ExcludeSystemJob] [-ExcludeSystemLogin] [-IncludeModifiedDate] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns zero or more objects representing configuration differences detected across Availability Group replicas. The specific properties returned depend on which comparison types are executed \r\n(controlled by the -Type parameter).\nFor AgentJob comparisons:\r\n- AvailabilityGroup: The name of the Availability Group being compared\r\n- Replica: The SQL Server instance name where the job status applies\r\n- JobName: The name of the SQL Agent job\r\n- Status: Job status on this replica (\"Present\" or \"Missing\")\r\n- DateLastModified: DateTime when the job was last modified, or $null if the job is missing on this replica (only populated when -IncludeModifiedDate is specified)\nFor Login comparisons:\r\n- AvailabilityGroup: The name of the Availability Group being compared\r\n- Replica: The name of the SQL Server replica instance\r\n- LoginName: The name of the login account\r\n- Status: Current status of the login on this replica (\"Present\" or \"Missing\")\r\n- ModifyDate: The datetime when the login was last modified on this replica (null if Status is \"Missing\"; only populated when -IncludeModifiedDate is specified)\r\n- CreateDate: The datetime when the login was created on this replica (null if Status is \"Missing\")\nFor Credential comparisons:\r\n- AvailabilityGroup: The name of the Availability Group being compared\r\n- Replica: The name of the replica instance where the credential status was checked\r\n- CredentialName: The name of the SQL Server credential\r\n- Status: The credential state on this replica (\"Present\" if the credential exists, \"Missing\" if it doesn\u0027t)\r\n- Identity: The credential\u0027s identity/principal on replicas where the credential is Present; $null where Status is \"Missing\"\nFor Operator comparisons:\r\n- AvailabilityGroup: Name of the Availability Group being compared\r\n- Replica: The SQL Server instance name of the replica\r\n- OperatorName: Name of the SQL Agent operator\r\n- Status: Configuration status of the operator on this replica (\"Present\" or \"Missing\")\r\n- EmailAddress: Email address of the operator (null if Status is \"Missing\")\nOnly objects representing differences (missing items or differing values when -IncludeModifiedDate is specified) are returned. If all configurations are identical across replicas, no output is \r\ngenerated.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCompare-DbaAvailabilityGroup -SqlInstance sql2016 -AvailabilityGroup AG1\nCompares all object types (Jobs, Logins, Credentials, Operators) across replicas in AG1.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCompare-DbaAvailabilityGroup -SqlInstance sql2016 -AvailabilityGroup AG1 -Type AgentJob\nCompares only SQL Agent Jobs across replicas in AG1.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCompare-DbaAvailabilityGroup -SqlInstance sql2016 -AvailabilityGroup AG1 -Type AgentJob, Login\nCompares SQL Agent Jobs and Logins across replicas in AG1.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eCompare-DbaAvailabilityGroup -SqlInstance sql2016 -AvailabilityGroup AG1 -IncludeModifiedDate\nCompares all object types including DateLastModified timestamps for jobs and logins.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sql2016 | Compare-DbaAvailabilityGroup\nCompares all object types for all Availability Groups on sql2016 via pipeline input.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eCompare-DbaAvailabilityGroup -SqlInstance sql2016 -AvailabilityGroup AG1 -ExcludeSystemJob -ExcludeSystemLogin\nCompares all object types excluding system jobs and system logins.", "Description": "Compares multiple object types across all replicas in an Availability Group to identify configuration differences. This comprehensive command checks SQL Agent Jobs, SQL Server Logins, SQL Server Credentials, and SQL Agent Operators to ensure consistency across AG replicas.\n\nThis is the main command for comparing AG replica configurations. It can run all comparison checks or specific ones based on the Type parameter.\n\nUse this to verify that junior DBAs have applied changes to all replicas, troubleshoot issues where configurations have drifted, or perform routine audits of AG replica consistency.", "Links": "https://dbatools.io/Compare-DbaAvailabilityGroup", "Synopsis": "Compares configuration across Availability Group replicas to identify differences in Jobs, Logins, Credentials, and Operators.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. Can be any replica in the Availability Group.", "", false, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "AvailabilityGroup", "Specifies one or more Availability Group names to compare across their replicas.", "", false, "false", "", "" ], [ "Type", "Specifies which object types to compare. Valid options are: AgentJob, Login, Credential, Operator, All.\r\nDefault is All which runs all comparison checks.", "", false, "false", "All", "AgentJob,Login,Credential,Operator,All" ], [ "ExcludeSystemJob", "Excludes system jobs from the agent job comparison.\r\nOnly applicable when Type includes AgentJob or All.", "", false, "false", "False", "" ], [ "ExcludeSystemLogin", "Excludes built-in system logins from the login comparison.\r\nOnly applicable when Type includes Login or All.", "", false, "false", "False", "" ], [ "IncludeModifiedDate", "Includes DateLastModified comparison for jobs and modify_date comparison for logins.\r\nOnly applicable when Type includes AgentJob, Login, or All.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Dacpac", "Schema", "SqlPackage", "Compare", "Deployment" ], "CommandName": "Compare-DbaDbSchema", "Name": "Compare-DbaDbSchema", "Author": "the dbatools team + Claude", "Syntax": "Compare-DbaDbSchema [-SourcePath] \u003cString\u003e [[-TargetSqlInstance] \u003cDbaInstanceParameter\u003e] [[-TargetSqlCredential] \u003cPSCredential\u003e] [[-TargetDatabase] \u003cString\u003e] [[-TargetPath] \u003cString\u003e] [[-OutputPath] \u003cString\u003e] [-KeepReport] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per schema difference found between source and target.\nProperties:\r\n- SourcePath: Full path to the source DACPAC file\r\n- Target: The target database or DACPAC path\r\n- Operation: The type of change (e.g., Create, Alter, Drop, Rename)\r\n- Value: The schema object name (e.g., [dbo].[MyTable])\r\n- Type: The object type (e.g., Table, Procedure, View)\r\n- ReportPath: Full path to the XML deployment report (only present when -KeepReport is specified)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCompare-DbaDbSchema -SourcePath C:\\temp\\source.dacpac -TargetSqlInstance sql2019 -TargetDatabase AdventureWorks\nCompares the source.dacpac schema against the AdventureWorks database on sql2019 and returns a list of differences.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCompare-DbaDbSchema -SourcePath C:\\temp\\v2.dacpac -TargetPath C:\\temp\\v1.dacpac\nCompares two DACPAC files offline and returns the schema differences.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eExport-DbaDacPackage -SqlInstance sql2016 -Database db_source -FilePath C:\\temp\\db_source.dacpac\nPS C:\\\u003e Compare-DbaDbSchema -SourcePath C:\\temp\\db_source.dacpac -TargetSqlInstance sql2016 -TargetDatabase db_target\nExports a DACPAC from the source database, then compares it against the target database on the same instance.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eCompare-DbaDbSchema -SourcePath C:\\temp\\source.dacpac -TargetSqlInstance sql2019 -TargetDatabase AdventureWorks -KeepReport -OutputPath C:\\reports\nCompares schema and keeps the XML report file in C:\\reports.", "Description": "Uses sqlpackage\u0027s DeployReport action to compare a source DACPAC against a target (live database or DACPAC file) and returns a structured list of schema differences.\n\nThe source must be a DACPAC file. The target can be either a live SQL Server database or another DACPAC file.\n\nNote: Comparing two live databases is not supported by sqlpackage. To compare two live databases, first export one as a DACPAC using Export-DbaDacPackage, then pass that DACPAC as the source to this command.\n\nsqlpackage must be available. Install it via Install-DbaSqlPackage if needed.", "Links": "https://dbatools.io/Compare-DbaDbSchema", "Synopsis": "Compares the schema of a DACPAC file against a target database or DACPAC file using sqlpackage.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SourcePath", "The path to the source DACPAC file to compare from.", "Path,FilePath", true, "true (ByPropertyName)", "", "" ], [ "TargetSqlInstance", "The target SQL Server instance containing the database to compare against.", "", false, "false", "", "" ], [ "TargetSqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nOnly SQL authentication is supported. When not specified, uses Trusted Authentication.", "", false, "false", "", "" ], [ "TargetDatabase", "The name of the target database on the target SQL Server instance to compare against.", "", false, "false", "", "" ], [ "TargetPath", "The path to the target DACPAC file to compare against. Use this for offline comparisons between two DACPAC files.", "", false, "false", "", "" ], [ "OutputPath", "The directory where the XML deployment report will be saved. Defaults to the configured DbatoolsExport path.\nThe report file is removed after parsing unless -KeepReport is specified.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \"Path.DbatoolsExport\")", "" ], [ "KeepReport", "When specified, the generated XML deployment report file is kept after parsing. By default, the file is removed after processing.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Login", "Security", "Compare" ], "CommandName": "Compare-DbaLogin", "Name": "Compare-DbaLogin", "Author": "the dbatools team + Claude", "Syntax": "Compare-DbaLogin [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-Login] \u003cString[]\u003e] [[-ExcludeLogin] \u003cString[]\u003e] [-ExcludeSystemLogin] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object for each login found on either the source or destination instance.\nProperties:\r\n- SourceServer: The name of the source SQL Server instance\r\n- DestinationServer: The name of the destination SQL Server instance\r\n- LoginName: The name of the login account\r\n- LoginType: The login type (SqlLogin, WindowsUser, WindowsGroup, etc.)\r\n- Status: Indicates where the login exists - \"SourceOnly\", \"DestinationOnly\", or \"Both\"", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCompare-DbaLogin -Source sql1 -Destination sql2\nCompares all logins between sql1 and sql2, returning the status of each login.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCompare-DbaLogin -Source sql1 -Destination sql2 | Where-Object Status -eq \"DestinationOnly\"\nReturns logins that exist on sql2 but not on sql1. These logins would be lost if Copy-DbaLogin -Force were run from sql1 to sql2.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCompare-DbaLogin -Source sql1 -Destination sql2 | Where-Object Status -eq \"SourceOnly\"\nReturns logins that exist on sql1 but not on sql2. These are the logins that Copy-DbaLogin would create.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eCompare-DbaLogin -Source sql1 -Destination sql2 -ExcludeSystemLogin\nCompares user-created logins between sql1 and sql2, excluding built-in system logins.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eCompare-DbaLogin -Source sql1 -Destination sql2, sql3 -Login \"appuser\", \"reportuser\"\nCompares the specified logins between sql1 and both sql2 and sql3.", "Description": "Compares SQL Server logins between a source instance and one or more destination instances to identify which logins exist only on the source, only on the destination, or on both. This is useful for identifying logins that would be lost when using Copy-DbaLogin with -Force, or for auditing login consistency between environments.\n\nReturns one object per login per destination instance, indicating whether the login exists on the source, destination, or both.", "Links": "https://dbatools.io/Compare-DbaLogin", "Synopsis": "Compares SQL Server logins between a source and one or more destination instances.", "Availability": "Windows, Linux, macOS", "Params": [ [ "Source", "The source SQL Server instance.", "", true, "false", "", "" ], [ "SourceSqlCredential", "Login to the source instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Destination", "The destination SQL Server instance or instances.", "", true, "false", "", "" ], [ "DestinationSqlCredential", "Login to the destination instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Login", "Specifies one or more logins to include in the comparison. All other logins are excluded.", "", false, "false", "", "" ], [ "ExcludeLogin", "Specifies one or more logins to exclude from the comparison.", "", false, "false", "", "" ], [ "ExcludeSystemLogin", "Excludes built-in system logins from the comparison results.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": "Connection", "CommandName": "Connect-DbaInstance", "Name": "Connect-DbaInstance", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Connect-DbaInstance [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString\u003e] [[-ApplicationIntent] \u003cString\u003e] [-AzureUnsupported] [[-BatchSeparator] \u003cString\u003e] [[-ClientName] \u003cString\u003e] [[-ConnectTimeout] \u003cInt32\u003e] [-EncryptConnection] [[-FailoverPartner] \u003cString\u003e] [[-LockTimeout] \u003cInt32\u003e] [[-MaxPoolSize] \u003cInt32\u003e] [[-MinPoolSize] \u003cInt32\u003e] [[-MinimumVersion] \u003cInt32\u003e] [-MultipleActiveResultSets] [-MultiSubnetFailover] [[-NetworkProtocol] \u003cString\u003e] [-NonPooledConnection] [[-PacketSize] \u003cInt32\u003e] [[-PooledConnectionLifetime] \u003cInt32\u003e] [[-SqlExecutionModes] \r\n\u003cString\u003e] [[-StatementTimeout] \u003cInt32\u003e] [-TrustServerCertificate] [-AllowTrustServerCertificate] [[-WorkstationId] \u003cString\u003e] [-AlwaysEncrypted] [[-AppendConnectionString] \u003cString\u003e] [-SqlConnectionOnly] [[-AzureDomain] \u003cString\u003e] [[-Tenant] \u003cString\u003e] [[-AccessToken] \u003cPSObject\u003e] [[-AuthenticationType] \u003cString\u003e] [-DedicatedAdminConnection] [-DisableException] [\u003cCommonParameters\u003e]", "Alias": "cdi", "Outputs": "Microsoft.SqlServer.Management.Smo.Server (default)\nReturns a fully initialized SMO Server connection object configured for the specified SQL Server instance. This object provides the foundation for most dbatools operations, allowing you to execute \r\nqueries, access database objects, and perform administrative tasks.\nThe returned object includes both standard SMO properties and dbatools-specific added properties:\nAdded dbatools properties:\r\n- ComputerName: The computer name of the SQL Server instance\r\n- IsAzure: Boolean indicating if the target is Azure SQL Database\r\n- DbaInstanceName: The instance name component (for named instances like \"SQLSERVER\\INSTANCENAME\")\r\n- SqlInstance: The full SQL Server instance name in DomainInstanceName format (e.g., \"COMPUTERNAME\\INSTANCENAME\")\r\n- NetPort: The TCP port number used for the connection\r\n- ConnectedAs: The login used to establish the connection (from ConnectionContext.TrueLogin)\nStandard SMO Server object properties (selected):\r\n- Databases: Collection of Database objects on the server\r\n- Logins: Collection of Login objects on the server\r\n- LinkedServers: Collection of LinkedServer objects\r\n- Endpoints: Collection of Endpoint objects\r\n- ConnectionContext: ServerConnection object containing connection details and configuration\r\n- VersionMajor: Major version number of SQL Server (8=2000, 9=2005, 10=2008, 11=2012, 12=2014, 13=2016, 14=2017, 15=2019, 16=2022)\r\n- VersionMinor: Minor version number\r\n- Version: Full version object\r\n- ServiceInstanceId: Service instance ID\r\n- DefaultFile: Default data file path\r\n- DefaultLog: Default log file path\r\n- MasterDBLogPath: Master database log file path\r\n- MasterDBPath: Master database path\r\n- InstallDataDirectory: SQL Server installation data directory\r\n- BackupDirectory: Default backup directory\r\n- Name: The server name\r\n- DatabaseEngineType: Engine type (Standard, Compact, SqlAzureDatabase, etc.)\r\n- HostPlatform: Platform the server is running on (Windows or Linux)\nMicrosoft.Data.SqlClient.SqlConnection (when -SqlConnectionOnly is specified)\nReturns only the underlying SQL connection object from the SMO Server\u0027s ConnectionContext.SqlConnectionObject. Use this when you need basic connection functionality without the overhead of \r\ninitializing the full SMO Server object. The connection can be used with ADO.NET code or when integrating with other .NET libraries.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eConnect-DbaInstance -SqlInstance sql2014\nCreates an SMO Server object that connects using Windows Authentication\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$wincred = Get-Credential ad\\sqladmin\nPS C:\\\u003e Connect-DbaInstance -SqlInstance sql2014 -SqlCredential $wincred\nCreates an SMO Server object that connects using alternative Windows credentials\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$sqlcred = Get-Credential sqladmin\nPS C:\\\u003e $server = Connect-DbaInstance -SqlInstance sql2014 -SqlCredential $sqlcred\nLogin to sql2014 as SQL login sqladmin.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$server = Connect-DbaInstance -SqlInstance sql2014 -ClientName \"my connection\"\nCreates an SMO Server object that connects using Windows Authentication and uses the client name \"my connection\".\r\nSo when you open up profiler or use extended events, you can search for \"my connection\".\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$server = Connect-DbaInstance -SqlInstance sql2014 -AppendConnectionString \"Packet Size=4096;AttachDbFilename=C:\\MyFolder\\MyDataFile.mdf;User Instance=true;\"\nCreates an SMO Server object that connects to sql2014 using Windows Authentication, then it sets the packet size (this can also be done via -PacketSize) and other connection attributes.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e$server = Connect-DbaInstance -SqlInstance sql2014 -NetworkProtocol TcpIp -MultiSubnetFailover\nCreates an SMO Server object that connects using Windows Authentication that uses TCP/IP and has MultiSubnetFailover enabled.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003e$server = Connect-DbaInstance sql2016 -ApplicationIntent ReadOnly\nConnects with ReadOnly ApplicationIntent.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003e$server = Connect-DbaInstance -SqlInstance myserver.database.windows.net -Database mydb -SqlCredential me@mydomain.onmicrosoft.com -DisableException\nPS C:\\\u003e Invoke-DbaQuery -SqlInstance $server -Query \"select 1 as test\"\nLogs into Azure SQL DB using AAD / Azure Active Directory, then performs a sample query.\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003e$server = Connect-DbaInstance -SqlInstance psdbatools.database.windows.net -Database dbatools -DisableException\nPS C:\\\u003e Invoke-DbaQuery -SqlInstance $server -Query \"select 1 as test\"\nLogs into Azure SQL DB using AAD Integrated Auth, then performs a sample query.\n-------------------------- EXAMPLE 10 --------------------------\nPS C:\\\u003e$server = Connect-DbaInstance -SqlInstance \"myserver.public.cust123.database.windows.net,3342\" -Database mydb -SqlCredential me@mydomain.onmicrosoft.com -DisableException\nPS C:\\\u003e Invoke-DbaQuery -SqlInstance $server -Query \"select 1 as test\"\nLogs into Azure SQL Managed instance using AAD / Azure Active Directory, then performs a sample query.\n-------------------------- EXAMPLE 11 --------------------------\nPS C:\\\u003e$server = Connect-DbaInstance -SqlInstance db.mycustomazure.com -Database mydb -AzureDomain mycustomazure.com -DisableException\nPS C:\\\u003e Invoke-DbaQuery -SqlInstance $server -Query \"select 1 as test\"\nIn the event your AzureSqlDb is not on a database.windows.net domain, you can set a custom domain using the AzureDomain parameter.\r\nThis tells Connect-DbaInstance to login to the database using the method that works best with Azure.\n-------------------------- EXAMPLE 12 --------------------------\nPS C:\\\u003e$connstring = \"Data Source=TCP:mydb.database.windows.net,1433;User ID=sqladmin;Password=adfasdf;Connect Timeout=30;\"\nPS C:\\\u003e $server = Connect-DbaInstance -ConnectionString $connstring\r\nPS C:\\\u003e Invoke-DbaQuery -SqlInstance $server -Query \"select 1 as test\"\nLogs into Azure using a preconstructed connstring, then performs a sample query.\r\nConnectionString is an alias of SqlInstance, so you can use -SqlInstance $connstring as well.\n-------------------------- EXAMPLE 13 --------------------------\nPS C:\\\u003e$cred = Get-Credential guid-app-id-here # appid for username, clientsecret for password\nPS C:\\\u003e $server = Connect-DbaInstance -SqlInstance psdbatools.database.windows.net -Database abc -SqlCredential $cred -Tenant guidheremaybename\r\nPS C:\\\u003e Invoke-DbaQuery -SqlInstance $server -Query \"select 1 as test\"\nWhen connecting from a non-Azure workstation, logs into Azure using Universal with MFA Support with a username and password, then performs a sample query.\nNote that generating access tokens is not supported on Core, so when using Tenant on Core, we rewrite the connection string with Active Directory Service Principal authentication instead.\n-------------------------- EXAMPLE 14 --------------------------\nPS C:\\\u003e$cred = Get-Credential guid-app-id-here # appid for username, clientsecret for password\nPS C:\\\u003e Set-DbatoolsConfig -FullName azure.tenantid -Value \u0027guidheremaybename\u0027 -Passthru | Register-DbatoolsConfig\r\nPS C:\\\u003e Set-DbatoolsConfig -FullName azure.appid -Value $cred.Username -Passthru | Register-DbatoolsConfig\r\nPS C:\\\u003e Set-DbatoolsConfig -FullName azure.clientsecret -Value $cred.Password -Passthru | Register-DbatoolsConfig # requires securestring\r\nPS C:\\\u003e Set-DbatoolsConfig -FullName sql.connection.database -Value abc -Passthru | Register-DbatoolsConfig\r\nPS C:\\\u003e Connect-DbaInstance -SqlInstance psdbatools.database.windows.net\nPermanently sets some app id config values. To set them temporarily (just for a session), remove -Passthru | Register-DbatoolsConfig\r\nWhen connecting from a non-Azure workstation or an Azure VM without .NET 4.7.2 and higher, logs into Azure using Universal with MFA Support, then performs a sample query.\n-------------------------- EXAMPLE 15 --------------------------\nPS C:\\\u003e$azureCredential = Get-Credential -Message \u0027Azure Credential\u0027\nPS C:\\\u003e $azureAccount = Connect-AzAccount -Credential $azureCredential\r\nPS C:\\\u003e $azureToken = Get-AzAccessToken -ResourceUrl https://database.windows.net\r\nPS C:\\\u003e $azureInstance = \"YOURSERVER.database.windows.net\"\r\nPS C:\\\u003e $azureDatabase = \"MYDATABASE\"\r\nPS C:\\\u003e $server = Connect-DbaInstance -SqlInstance $azureInstance -Database $azureDatabase -AccessToken $azureToken\r\nPS C:\\\u003e Invoke-DbaQuery -SqlInstance $server -Query \"select 1 as test\"\nConnect to an Azure SQL Database or an Azure SQL Managed Instance with an AccessToken.\r\nWorks with both Azure PowerShell v13 (string tokens) and v14+ (SecureString tokens).\r\nNote that the token is valid for only one hour and cannot be renewed automatically.\n-------------------------- EXAMPLE 16 --------------------------\nPS C:\\\u003e# Azure PowerShell v14+ with SecureString token support\nPS C:\\\u003e Connect-AzAccount\r\nPS C:\\\u003e $azureToken = (Get-AzAccessToken -ResourceUrl https://database.windows.net).Token\r\nPS C:\\\u003e $azureInstance = \"YOUR-AZURE-SQL-MANAGED-INSTANCE.database.windows.net\"\r\nPS C:\\\u003e $server = Connect-DbaInstance -SqlInstance $azureInstance -Database \"YOURDATABASE\" -AccessToken $azureToken\r\nPS C:\\\u003e Invoke-DbaQuery -SqlInstance $server -Query \"select 1 as test\"\nConnect to an Azure SQL Managed Instance using Azure PowerShell v14+ where Get-AzAccessToken returns a SecureString.\r\nThe function automatically detects and converts the SecureString token to the required format.\n-------------------------- EXAMPLE 17 --------------------------\nPS C:\\\u003e$token = New-DbaAzAccessToken -Type RenewableServicePrincipal -Subtype AzureSqlDb -Tenant $tenantid -Credential $cred\nPS C:\\\u003e Connect-DbaInstance -SqlInstance sample.database.windows.net -Accesstoken $token\nUses dbatools to generate the access token for an Azure SQL Database, then logs in using that AccessToken.\n-------------------------- EXAMPLE 18 --------------------------\nPS C:\\\u003e$server = Connect-DbaInstance -SqlInstance srv1 -DedicatedAdminConnection\nPS C:\\\u003e $dbaProcess = Get-DbaProcess -SqlInstance $server -ExcludeSystemSpids\r\nPS C:\\\u003e $killedProcess = $dbaProcess | Out-GridView -OutputMode Multiple | Stop-DbaProcess\r\nPS C:\\\u003e $server | Disconnect-DbaInstance\nCreates a dedicated admin connection (DAC) to the default instance on server srv1.\r\nReceives all non-system processes from the instance using the DAC.\r\nOpens a grid view to let the user select processes to be stopped.\r\nCloses the connection.\n-------------------------- EXAMPLE 19 --------------------------\nPS C:\\\u003e$servers = \"sql1\", \"sql2\", \"sql3\"\nPS C:\\\u003e $servers | Connect-DbaInstance -AllowTrustServerCertificate\nConnects to multiple servers where some may have valid TLS certificates and others may not.\r\nFor each server, attempts connection with proper TLS validation first.\r\nIf a server fails due to certificate validation, automatically retries with TrustServerCertificate enabled.\r\nThis provides a secure-by-default approach for mixed environments without requiring separate connection logic.\n-------------------------- EXAMPLE 20 --------------------------\nPS C:\\\u003e$server = Connect-DbaInstance -SqlInstance sql01 -AuthenticationType ActiveDirectoryInteractive\nConnects to a SQL Server instance (Azure SQL VM, Azure SQL Database, Azure SQL Managed Instance, or Fabric SQL Database)\r\nusing Entra ID (Azure AD) interactive authentication with MFA. A browser dialog will appear prompting you to select\r\nyour Entra ID account and complete any required MFA steps.\n-------------------------- EXAMPLE 21 --------------------------\nPS C:\\\u003e$server = Connect-DbaInstance -SqlInstance myserver.database.windows.net -Database mydb -AuthenticationType ActiveDirectoryInteractive\nConnects to an Azure SQL Database using Entra ID interactive authentication with MFA.\r\nA browser dialog will appear to complete authentication.\n-------------------------- EXAMPLE 22 --------------------------\nPS C:\\\u003e$server = Connect-DbaInstance -SqlInstance sql01 -AuthenticationType ActiveDirectoryIntegrated\nConnects to a SQL Server instance using Entra ID integrated authentication.\r\nUses the currently signed-in Entra ID identity without prompting for credentials.", "Description": "This command creates a reusable SQL Server Management Object (SMO) that serves as the foundation for most dbatools operations. Think of it as your entry point for connecting to SQL Server instances, whether on-premises, in Azure, or anywhere else.\n\nThe returned SMO server object handles authentication automatically, detecting whether to use Windows integrated security, SQL authentication, or Azure Active Directory based on your credentials. It supports connection pooling by default for better performance and can handle complex scenarios like failover partners, dedicated admin connections, and multi-subnet environments.\n\nThis is the connection object you\u0027ll pass to other dbatools commands like Get-DbaDatabase, Invoke-DbaQuery, or Backup-DbaDatabase. Rather than each command establishing its own connection, you create one persistent connection here and reuse it, which is both faster and more reliable.\n\nThe connection includes helpful properties for scripting like ComputerName, IsAzure, and ConnectedAs, plus it automatically sets an identifiable ApplicationName in your connection string so you can track dbatools sessions in profiler or extended events.\n\nFor Azure connections, it handles the various authentication methods including service principals, managed identities, and access tokens. For on-premises instances, it supports Windows authentication (including alternative credentials), SQL logins, and dedicated administrator connections for emergency access.\n\nReference documentation:\nhttps://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring.aspx\nhttps://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder.aspx\nhttps://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.aspx\n\nTo execute SQL commands directly: $server.ConnectionContext.ExecuteReader($sql) or $server.Databases[\u0027master\u0027].ExecuteNonQuery($sql)", "Links": "https://dbatools.io/Connect-DbaInstance", "Synopsis": "Creates a persistent SQL Server Management Object (SMO) connection for database operations.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.", "Connstring,ConnectionString", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Credential object used to connect to the SQL Server Instance as a different user. This can be a Windows or SQL Server account. Windows users are determined by the existence of a backslash, so if you \r\nare intending to use an alternative Windows connection instead of a SQL login, ensure it contains a backslash.", "", false, "false", "", "" ], [ "Database", "Specifies the initial database context for the connection instead of connecting to the default database.\r\nUseful when you need to connect directly to a specific database or when the login\u0027s default database is unavailable.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027sql.connection.database\u0027)", "" ], [ "ApplicationIntent", "Declares the application workload type when connecting to an Always On Availability Group.\r\nUse \"ReadOnly\" to route connections to readable secondary replicas for reporting workloads, reducing load on the primary replica.", "", false, "false", "", "ReadOnly,ReadWrite" ], [ "AzureUnsupported", "Causes the connection to fail if the target is detected as Azure SQL Database.\r\nUse this to prevent operations that are incompatible with Azure SQL Database from attempting to connect to cloud instances.", "", false, "false", "False", "" ], [ "BatchSeparator", "Sets the batch separator for multi-statement SQL execution, defaulting to \"GO\".\r\nChange this when working with scripts that use different batch separators or when \"GO\" conflicts with your SQL content.", "", false, "false", "", "" ], [ "ClientName", "Sets a custom application name in the connection string for identification in SQL Server monitoring tools.\r\nUse this to distinguish dbatools sessions from other applications when analyzing connections in Profiler, Extended Events, or sys.dm_exec_sessions.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027sql.connection.clientname\u0027)", "" ], [ "ConnectTimeout", "Sets the connection timeout in seconds before the connection attempt fails.\r\nIncrease this for slow networks or busy servers, or decrease it for faster failure detection in automated scripts. Azure SQL Database connections typically need 30 seconds.", "", false, "false", "([Dataplat.Dbatools.Connection.ConnectionHost]::SqlConnectionTimeout)", "" ], [ "EncryptConnection", "Forces SSL encryption for all data transmitted between client and server.\r\nRequired for many compliance scenarios and recommended for connections over untrusted networks. Ensure server certificates are properly configured to avoid connection failures.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027sql.connection.encrypt\u0027)", "" ], [ "FailoverPartner", "Specifies the failover partner server name for database mirroring configurations.\r\nUse this when connecting to databases configured for database mirroring to enable automatic failover if the primary server becomes unavailable.", "", false, "false", "", "" ], [ "LockTimeout", "Sets the lock timeout in seconds for transactions on this connection.\r\nUse this to control how long statements wait for locks before timing out, which helps prevent long-running blocking scenarios.", "", false, "false", "0", "" ], [ "MaxPoolSize", "Sets the maximum number of connections allowed in the connection pool for this connection string.\r\nIncrease this for applications with high concurrency requirements, but be mindful of server resource limits and licensing constraints.", "", false, "false", "0", "" ], [ "MinPoolSize", "Sets the minimum number of connections maintained in the connection pool for this connection string.\r\nUse this to pre-warm the connection pool for better performance when you know connections will be used frequently.", "", false, "false", "0", "" ], [ "MinimumVersion", "Specifies the minimum SQL Server version required for the connection to succeed.\r\nUse this to ensure scripts only run against SQL Server versions that support the required features, preventing compatibility issues.", "", false, "false", "0", "" ], [ "MultipleActiveResultSets", "Enables Multiple Active Result Sets (MARS) allowing multiple commands to be executed simultaneously on a single connection.\r\nUse this when you need to execute multiple queries concurrently without opening additional connections, though it can impact performance.", "", false, "false", "False", "" ], [ "MultiSubnetFailover", "Enables faster detection and connection to the active server in Always On Availability Groups across multiple subnets.\r\nEssential for AG configurations where replicas are in different subnets, reducing connection time during failover scenarios.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027sql.connection.multisubnetfailover\u0027)", "" ], [ "NetworkProtocol", "Specifies the network protocol for connecting to SQL Server.\r\nUse \"TcpIp\" for remote connections, \"NamedPipes\" for local connections with better security, or \"SharedMemory\" for fastest local connections. Most modern environments use TcpIp.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027sql.connection.protocol\u0027)", "TcpIp,NamedPipes,Multiprotocol,AppleTalk,BanyanVines,Via,SharedMemory,NWLinkIpxSpx" ], [ "NonPooledConnection", "Creates a dedicated connection that bypasses connection pooling.\r\nUse this for long-running operations, dedicated admin connections, or when you need to ensure the connection isn\u0027t shared with other processes.", "", false, "false", "False", "" ], [ "PacketSize", "Sets the network packet size in bytes for communication with SQL Server.\r\nIncrease from the default 4096 bytes to improve performance for large data transfers, but ensure the server is configured to support the same packet size.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027sql.connection.packetsize\u0027)", "" ], [ "PooledConnectionLifetime", "Sets the maximum lifetime in seconds for pooled connections before they\u0027re discarded and recreated.\r\nUse this in clustered environments to force load balancing or to refresh connections periodically. Zero means unlimited lifetime.", "", false, "false", "0", "" ], [ "SqlExecutionModes", "Controls how SQL commands are processed by the connection.\r\nUse \"CaptureSql\" to generate scripts without execution, \"ExecuteAndCaptureSql\" to both execute and log commands, or \"ExecuteSql\" for normal execution.", "", false, "false", "", "CaptureSql,ExecuteAndCaptureSql,ExecuteSql" ], [ "StatementTimeout", "Sets the timeout in seconds for SQL statement execution before canceling the command.\r\nUse this to prevent runaway queries from blocking operations indefinitely. Zero means unlimited, but set reasonable limits for production environments.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027sql.execution.timeout\u0027)", "" ], [ "TrustServerCertificate", "Bypasses certificate validation when using encrypted connections.\r\nUse this for development environments or when connecting to servers with self-signed certificates, but avoid in production for security reasons.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027sql.connection.trustcert\u0027)", "" ], [ "AllowTrustServerCertificate", "Attempts connection with proper TLS validation first, then retries with TrustServerCertificate if the initial connection fails due to certificate validation.\r\nProvides a secure-by-default approach for mixed environments where some servers have valid certificates and others do not.\r\nOnly retries on certificate validation failures, not on other connection errors like authentication or network issues.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027sql.connection.allowtrustcert\u0027)", "" ], [ "WorkstationId", "Sets the workstation name visible in SQL Server monitoring and session information.\r\nUse this to identify the source of connections in sys.dm_exec_sessions or when troubleshooting connection issues.", "", false, "false", "", "" ], [ "AlwaysEncrypted", "Enables Always Encrypted support for accessing encrypted columns in databases with column-level encryption.\r\nRequired when working with sensitive data protected by Always Encrypted, allowing proper decryption of encrypted column values.", "", false, "false", "False", "" ], [ "AppendConnectionString", "Adds custom connection string parameters to the generated connection string.\r\nUse this for advanced connection properties like custom timeout values, SSL settings, or application-specific parameters that aren\u0027t covered by other parameters.", "", false, "false", "", "" ], [ "SqlConnectionOnly", "Returns only a SqlConnection object instead of the full SMO server object.\r\nUse this when you only need basic connection functionality and want to reduce memory overhead or avoid SMO initialization.", "", false, "false", "False", "" ], [ "AzureDomain", "Specifies the domain for Azure SQL Database connections, defaulting to database.windows.net.\r\nUse this when connecting to Azure SQL instances in sovereign clouds or custom domains that require different authentication methods.", "", false, "false", "database.windows.net", "" ], [ "Tenant", "Specifies the Azure Active Directory tenant ID for Azure SQL Database authentication.\r\nRequired when using service principal authentication or when your account exists in multiple Azure AD tenants.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027azure.tenantid\u0027)", "" ], [ "AccessToken", "Authenticates to Azure SQL Database using an access token generated by Get-AzAccessToken or New-DbaAzAccessToken.\r\nUse this for service principal authentication or when integrating with Azure automation that provides pre-generated tokens. Tokens expire after one hour and cannot be renewed.", "", false, "false", "", "" ], [ "AuthenticationType", "Specifies the authentication method for connecting to Azure SQL or Entra ID-protected SQL Server instances.\r\nUse \"ActiveDirectoryInteractive\" for Entra ID (Azure AD) authentication with MFA — a browser dialog will prompt you to select your Entra ID account.\r\nUse \"ActiveDirectoryIntegrated\" for Entra ID integrated authentication using your current Windows session.\r\nUse \"ActiveDirectoryPassword\" for Entra ID authentication with a username and password via SqlCredential.\r\nUse \"ActiveDirectoryServicePrincipal\" for service principal authentication (client ID and secret via SqlCredential).\r\nUse \"ActiveDirectoryManagedIdentity\" for managed identity authentication in Azure-hosted environments.\r\nUse \"ActiveDirectoryDeviceCodeFlow\" for device code flow authentication.", "", false, "false", "", "ActiveDirectoryIntegrated,ActiveDirectoryInteractive,ActiveDirectoryPassword,ActiveDirectoryServicePrincipal,ActiveDirectoryManagedIdentity,ActiveDirectoryDeviceCodeFlow" ], [ "DedicatedAdminConnection", "Creates a dedicated administrator connection (DAC) for emergency access to SQL Server.\r\nUse this when SQL Server is unresponsive to regular connections, allowing you to diagnose and resolve critical issues. Remember to manually disconnect the connection when finished.", "", false, "false", "False", "" ], [ "DisableException", "Changes exception handling from throwing errors to displaying warnings.\r\nUse this in interactive sessions where you want graceful error handling instead of script-stopping exceptions, which is the default behavior for this command.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Table", "Data" ], "CommandName": "ConvertTo-DbaDataTable", "Name": "ConvertTo-DbaDataTable", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "ConvertTo-DbaDataTable [-InputObject] \u003cPSObject[]\u003e [-TimeSpanType \u003cString\u003e] [-SizeType \u003cString\u003e] [-IgnoreNull] [-Raw] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.Data.DataTable\nReturns a single DataTable object containing all input objects as rows. Each property from the input objects becomes a column in the DataTable with an appropriate data type.\nColumn data types are automatically detected based on input object properties:\r\n- Numeric types (Int32, Int64, Decimal, Double, Single, etc.) are preserved as their original types\r\n- TimeSpan and DbaTimeSpan objects are converted based on the -TimeSpanType parameter (default: TotalMilliseconds as Int64)\r\n- DbaSize (file/database size) objects are converted based on the -SizeType parameter (default: Byte value as Int64)\r\n- DateTime objects are preserved as System.DateTime\r\n- Boolean, Guid, and Char types are preserved\r\n- String arrays and System.Object[] are joined with comma separators\r\n- Other types are converted to strings\nWhen the -Raw parameter is specified, all columns are created as strings regardless of input type, which can be useful as a fallback when type detection fails or maximum compatibility is needed.\nThe DataTable is suitable for use with Write-DbaDataTable for bulk insert operations into SQL Server tables. All properties from the input objects are included as columns in the returned DataTable.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-Service | ConvertTo-DbaDataTable\nCreates a DataTable from the output of Get-Service.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eConvertTo-DbaDataTable -InputObject $csv.cheesetypes\nCreates a DataTable from the CSV object $csv.cheesetypes.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$dblist | ConvertTo-DbaDataTable\nCreates a DataTable from the $dblist object passed in via pipeline.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-Process | ConvertTo-DbaDataTable -TimeSpanType TotalSeconds\nCreates a DataTable with the running processes and converts any TimeSpan property to TotalSeconds.", "Description": "Converts PowerShell objects into .NET DataTable objects with proper column types and database-compatible data formatting. This is essential for bulk operations like importing data into SQL Server tables using Write-DbaDataTable or other bulk insert methods.\n\nThe function automatically detects and converts data types to SQL Server-compatible formats, handling special dbatools types like DbaSize (file sizes) and DbaTimeSpan objects. You can control how these special types are converted - for example, converting TimeSpan objects to total milliseconds, seconds, or string representations.\n\nCommon scenarios include taking results from Get-DbaDatabase, Get-DbaBackupHistory, or other dbatools commands and preparing them for storage in custom reporting tables. The function handles complex object arrays, null values, and provides both strongly-typed and raw string conversion modes.\n\nThanks to Chad Miller, this is based on his script. https://gallery.technet.microsoft.com/scriptcenter/4208a159-a52e-4b99-83d4-8048468d29dd\n\nIf the attempt to convert to data table fails, try the -Raw parameter for less accurate datatype detection.", "Links": "https://dbatools.io/ConvertTo-DbaDataTable", "Synopsis": "Converts PowerShell objects into .NET DataTable objects for bulk SQL Server operations", "Availability": "Windows, Linux, macOS", "Params": [ [ "InputObject", "PowerShell objects to convert into a DataTable with proper SQL Server-compatible column types.\r\nAccepts results from dbatools commands like Get-DbaDatabase, Get-DbaBackupHistory, or any PowerShell object array.\r\nHandles complex properties, arrays, and dbatools-specific types like DbaSize and DbaTimeSpan automatically.", "", true, "true (ByValue)", "", "" ], [ "TimeSpanType", "Controls how TimeSpan and DbaTimeSpan objects are converted for database storage.\r\nUse \u0027TotalMilliseconds\u0027 (default) for precise timing data, \u0027TotalSeconds\u0027 for general duration tracking, or \u0027String\u0027 to preserve readable format.\r\nCommon when converting backup duration, job runtime, or database uptime data for reporting tables.", "", false, "false", "TotalMilliseconds", "Ticks,TotalDays,TotalHours,TotalMinutes,TotalSeconds,TotalMilliseconds,String" ], [ "SizeType", "Controls how DbaSize objects (file sizes, database sizes) are converted for database storage.\r\nUse \u0027Int64\u0027 (default) for precise byte values suitable for calculations, \u0027Int32\u0027 for smaller datasets, or \u0027String\u0027 to preserve human-readable format like \u00271.5 GB\u0027.\r\nEssential when storing database size reports, backup file information, or disk space data.", "", false, "false", "Int64", "Int64,Int32,String" ], [ "IgnoreNull", "Excludes null objects from the DataTable instead of creating empty rows.\r\nUse this when preparing clean datasets for bulk insert operations where empty rows would cause issues.\r\nHelpful when processing filtered results that may contain null entries from failed connections or missing databases.", "", false, "false", "False", "" ], [ "Raw", "Forces all DataTable columns to be strings instead of detecting proper data types.\r\nUse this as a fallback when automatic type detection fails or when you need maximum compatibility with target tables that expect string data.\r\nTrades type safety for reliability when dealing with complex or problematic object properties.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Utility", "Chart" ], "CommandName": "ConvertTo-DbaTimeline", "Name": "ConvertTo-DbaTimeline", "Author": "Marcin Gminski (@marcingminski)", "Syntax": "ConvertTo-DbaTimeline [-InputObject] \u003cObject[]\u003e [-ExcludeRowLabel] [[-DateFormat] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.String\nReturns HTML code as an array of three string objects that together form a complete, self-contained HTML document with an interactive Google Charts timeline visualization. The three strings are: \r\nheader/scripts (HTML head section), body rows (timeline data), and footer (HTML closing tags and chart rendering code).\nThe output can be piped directly to Out-File to create an HTML file, or to Out-String to view as text, or captured in a variable for further processing. When saved to a file with Out-File and opened \r\nin a web browser, renders an interactive timeline with:\r\n- Horizontal timeline bars showing execution duration\r\n- Color-coded status indicators (Success, Failure, etc. based on input data)\r\n- Hover tooltips displaying item name, status, start time, end time, and duration\r\n- Configurable row labels (disabled with -ExcludeRowLabel parameter)\r\n- Responsive sizing that adjusts to content\r\n- Multi-instance support with automatic instance labeling", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAgentJobHistory -SqlInstance sql-1 -StartDate \u00272018-08-13 00:00\u0027 -EndDate \u00272018-08-13 23:59\u0027 -ExcludeJobSteps | ConvertTo-DbaTimeline | Out-File C:\\temp\\DbaAgentJobHistory.html \r\n-Encoding ASCII\nCreates an output file containing a pretty timeline for all of the agent job history results for sql-1 the whole day of 2018-08-13\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaRegServer -SqlInstance sqlcm | Get-DbaDbBackupHistory -Since \u00272018-08-13 00:00\u0027 | ConvertTo-DbaTimeline | Out-File C:\\temp\\DbaBackupHistory.html -Encoding ASCII\nCreates an output file containing a pretty timeline for the agent job history since 2018-08-13 for all of the registered servers on sqlcm\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eFind-DbaDbGrowthEvent -SqlInstance sql-1 | ConvertTo-DbaTimeline | Out-File C:\\temp\\DbaDbGrowthEvent.html -Encoding ASCII\nCreates an output file containing a timeline of all database auto-growth and auto-shrink events for sql-1.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaAgentJobHistory -SqlInstance sql-1 -ExcludeJobSteps | ConvertTo-DbaTimeline -DateFormat \"MM/dd\" | Out-File C:\\temp\\DbaAgentJobHistory.html -Encoding ASCII\nCreates a timeline that displays month-first dates in tooltips and on the horizontal axis.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$messageParameters = @{\n\u003e\u003e Subject = \"Backup history for sql2017 and sql2016\"\r\n\u003e\u003e Body = Get-DbaDbBackupHistory -SqlInstance sql2017, sql2016 -Since \u00272018-08-13 00:00\u0027 | ConvertTo-DbaTimeline | Out-String\r\n\u003e\u003e From = \"dba@ad.local\"\r\n\u003e\u003e To = \"dba@ad.local\"\r\n\u003e\u003e SmtpServer = \"smtp.ad.local\"\r\n\u003e\u003e }\r\n\u003e\u003e\r\nPS C:\\\u003e Send-MailMessage @messageParameters -BodyAsHtml\nSends an email to dba@ad.local with the results of Get-DbaDbBackupHistory. Note that viewing these reports may not be supported in all email clients.", "Description": "Transforms SQL Server job execution, backup operation, and database growth event data into visual timeline reports for analysis and troubleshooting. Takes piped output from Get-DbaAgentJobHistory, Get-DbaDbBackupHistory, or Find-DbaDbGrowthEvent and generates a complete HTML file with an interactive Google Charts timeline.\n\nPerfect for analyzing job schedules, identifying backup windows, visualizing auto-growth events, troubleshooting overlapping operations, or creating visual reports for management. The timeline shows execution duration, status, and timing relationships across multiple instances, with hover tooltips displaying detailed information including start/end times and duration calculations.\n\nOutput is a self-contained HTML file that can be viewed in any browser, emailed to stakeholders, or archived for historical analysis. Supports both single and multi-instance scenarios with automatic labeling and color-coded status indicators.", "Links": "https://dbatools.io/ConvertTo-DbaTimeline", "Synopsis": "Generates interactive HTML timeline visualizations from SQL Server job history, backup history, and database growth event data", "Availability": "Windows, Linux, macOS", "Params": [ [ "InputObject", "Specifies the SQL Server data to convert into timeline visualization. Accepts piped output from Get-DbaAgentJobHistory, Get-DbaDbBackupHistory, or Find-DbaDbGrowthEvent.\r\nUse this to transform job execution history, backup operation data, or database auto-growth/shrink events into an interactive HTML timeline chart.\r\nThe function automatically detects the input type and formats the timeline appropriately with status colors and duration calculations.", "", true, "true (ByValue)", "", "" ], [ "ExcludeRowLabel", "Removes the row labels showing SQL instance and item names from the left side of the timeline chart. By default, labels display \"[InstanceName] JobName\" or \"[InstanceName] DatabaseName\" for each \r\ntimeline row.\r\nUse this when you need to maximize chart space for better visualization of timeline data, especially with long instance or job names.\r\nAll label information remains available in the hover tooltips when you mouse over timeline bars.", "", false, "false", "False", "" ], [ "DateFormat", "Specifies the Google Charts date pattern used for tooltip dates and the horizontal timeline axis. If the pattern does not include a year, /yy is appended to tooltip dates. Defaults to dd/MM to \r\npreserve the existing output.\r\nUse MM/dd for month-first dates or yyyy-MM-dd for an ISO-style date. The pattern accepts Google Charts day, month, year, and weekday tokens with common separators.", "", false, "false", "dd/MM", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Trace", "ExtendedEvent" ], "CommandName": "ConvertTo-DbaXESession", "Name": "ConvertTo-DbaXESession", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "ConvertTo-DbaXESession [-InputObject] \u003cObject[]\u003e [-Name] \u003cString\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-OutputScriptOnly] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.String (when -OutputScriptOnly is specified)\nReturns the T-SQL CREATE EVENT SESSION script as a string. The script contains the complete Extended Events session definition with all events, columns, actions, and filters mapped from the original \r\nSQL Trace.\nMicrosoft.SqlServer.Management.XEvent.Session (default output)\nReturns one Extended Events session object per trace converted. When creating sessions on the target server (default behavior), the function returns the created session object with the following \r\nproperties added by Get-DbaXESession:\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Name: The Extended Events session name (the converted trace name)\r\n- Status: Current session status (Running or Stopped)\r\n- StartTime: Date and time the session started\r\n- AutoStart: Boolean indicating if the session auto-starts on SQL Server startup\r\n- State: Session state (Created, Running, etc.)\r\n- Targets: Extended Events targets collecting the data\r\n- TargetFile: Path to the target output file(s)\r\n- Events: Extended Events events configured in the session\r\n- MaxMemory: Maximum memory allocated to the session in MB\r\n- MaxEventSize: Maximum size of events in KB\nAdditional properties available (from SMO XEStore.ServerSession object):\r\n- Session: The session name (duplicate of Name property)\r\n- RemoteTargetFile: UNC path to the target output file(s) for remote access\r\n- Parent: Reference to the SQL Server SMO server object\r\n- Store: Reference to the XEStore object\r\n- IsRunning: Boolean indicating if the session is currently running\r\n- Description: Session description\r\n- CreateDate: Date and time the session was created\r\n- ModifyDate: Date and time the session was last modified", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaTrace -SqlInstance sql2017, sql2012 | Where-Object Id -eq 2 | ConvertTo-DbaXESession -Name \u0027Test\u0027\nConverts Trace with ID 2 to a Session named Test on SQL Server instances named sql2017 and sql2012 and creates the Session on each respective server.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaTrace -SqlInstance sql2014 | Out-GridView -PassThru | ConvertTo-DbaXESession -Name \u0027Test\u0027 | Start-DbaXESession\nConverts selected traces on sql2014 to sessions, creates the session, and starts it.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaTrace -SqlInstance sql2014 | Where-Object Id -eq 1 | ConvertTo-DbaXESession -Name \u0027Test\u0027 -OutputScriptOnly\nConverts trace ID 1 on sql2014 to an Extended Event and outputs the resulting T-SQL.", "Description": "Converts existing SQL Server Traces to Extended Events sessions by analyzing trace definitions and mapping events, columns, actions, and filters to their Extended Events equivalents. This eliminates the need to manually recreate monitoring configurations when migrating from the deprecated SQL Trace to Extended Events.\n\nThe function uses a comprehensive mapping table that translates trace events like RPC:Completed, SQL:BatchCompleted, and Lock events to their corresponding Extended Events such as rpc_completed, sql_batch_completed, and lock_acquired. It preserves filters and column selections from the original trace, ensuring equivalent monitoring capabilities in the new Extended Events session.\n\nBy default, the function creates and starts the Extended Events session on the target server. Alternatively, you can generate just the T-SQL script for review or manual execution. This is particularly useful for compliance environments where script review is required before deployment.\n\nT-SQL code by: Jonathan M. Kehayias, SQLskills.com. T-SQL can be found in this module directory and at\nhttps://www.sqlskills.com/blogs/jonathan/converting-sql-trace-to-extended-events-in-sql-server-2012/", "Links": "https://dbatools.io/ConvertTo-DbaXESession", "Synopsis": "Converts SQL Server Traces to Extended Events sessions using intelligent column and event mapping.", "Availability": "Windows, Linux, macOS", "Params": [ [ "InputObject", "Specifies the SQL Server Trace objects to convert to Extended Events sessions. Must be trace objects returned by Get-DbaTrace.\r\nUse this to convert existing traces from SQL Trace to Extended Events, preserving event mappings and filter configurations.", "", true, "true (ByValue)", "", "" ], [ "Name", "Specifies the name for the new Extended Events session. If a session with this name already exists, the function automatically appends the trace ID or a random number to avoid conflicts.\r\nChoose a descriptive name that identifies the monitoring purpose, as this becomes the session name visible in SQL Server Management Studio and sys.server_event_sessions.", "", true, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "OutputScriptOnly", "Returns the T-SQL CREATE EVENT SESSION script without executing it on the server. Use this when you need to review the generated script before deployment or save it for later execution.\r\nParticularly useful in compliance environments where all scripts require approval before running against production databases.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Migration", "Agent" ], "CommandName": "Copy-DbaAgentAlert", "Name": "Copy-DbaAgentAlert", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Copy-DbaAgentAlert [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-Alert] \u003cObject[]\u003e] [[-ExcludeAlert] \u003cObject[]\u003e] [-IncludeDefaults] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per migration action performed. Multiple objects may be returned when processing multiple destination servers or when an alert has job associations and notifications.\nProperties:\r\n- SourceServer: Name of the source SQL Server instance\r\n- DestinationServer: Name of the destination SQL Server instance where the alert was copied\r\n- Name: Name of the alert or configuration item being copied\r\n- Type: Type of object being processed (Agent Alert, Agent Alert Job Association, Agent Alert Notification, or Alert Defaults)\r\n- Status: Result of the operation (Successful, Failed, or Skipped)\r\n- Notes: Additional details about the operation, such as why it was skipped or error message\r\n- DateTime: Timestamp when the operation was performed (Dataplat.Dbatools.Utility.DbaDateTime)\nWhen an alert is skipped due to missing operators, conflicts, or missing job dependencies, Status will be \"Skipped\" with explanatory Notes. When -Force is used to drop and recreate an existing alert, \r\nthe operation is shown as a separate action in the output.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaAgentAlert -Source sqlserver2014a -Destination sqlcluster\nCopies all alerts from sqlserver2014a to sqlcluster using Windows credentials. If alerts with the same name exist on sqlcluster, they will be skipped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaAgentAlert -Source sqlserver2014a -Destination sqlcluster -Alert PSAlert -SourceSqlCredential $cred -Force\nCopies a only the alert named PSAlert from sqlserver2014a to sqlcluster using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster. If an alert with the same name exists on \r\nsqlcluster, it will be dropped and recreated because -Force was used.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaAgentAlert -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force\nShows what would happen if the command were executed using force.", "Description": "Transfers SQL Server Agent alerts from a source instance to one or more destination instances, preserving their configurations, notification settings, and job associations. This function handles the complex dependencies between alerts, operators, and jobs automatically, ensuring alerts work properly after migration.\n\nEssential for server migrations, disaster recovery preparation, and standardizing monitoring across multiple SQL Server environments. Prevents manual recreation of dozens of alerts and their intricate notification chains.\n\nBy default, all alerts are copied, but you can specify individual alerts with the -Alert parameter. Existing alerts are skipped unless -Force is used to overwrite them.", "Links": "https://dbatools.io/Copy-DbaAgentAlert", "Synopsis": "Copies SQL Server Agent alerts from source instance to destination instances", "Availability": "Windows, Linux, macOS", "Params": [ [ "Source", "Specifies the source SQL Server instance containing the alerts to copy. Must be SQL Server 2000 or higher.\r\nUse this to identify the server with the alert configurations you want to migrate or replicate.", "", true, "false", "", "" ], [ "SourceSqlCredential", "Specifies alternative credentials for connecting to the source SQL Server instance.\r\nUse this when the current Windows credentials don\u0027t have access to the source server or when connecting with SQL Server authentication.", "", false, "false", "", "" ], [ "Destination", "Specifies one or more destination SQL Server instances where alerts will be copied. Must be SQL Server 2000 or higher.\r\nAccepts multiple instances to copy alerts to several servers simultaneously during migrations or standardization efforts.", "", true, "false", "", "" ], [ "DestinationSqlCredential", "Specifies alternative credentials for connecting to the destination SQL Server instances.\r\nUse this when the current Windows credentials don\u0027t have access to destination servers or when connecting with SQL Server authentication.", "", false, "false", "", "" ], [ "Alert", "Specifies specific alert names to copy instead of copying all alerts from the source instance.\r\nUse this when you only need to migrate particular alerts rather than the entire alert configuration.", "", false, "false", "", "" ], [ "ExcludeAlert", "Specifies alert names to skip during the copy operation while processing all other alerts.\r\nUse this when you want to copy most alerts but exclude specific ones that shouldn\u0027t be migrated.", "", false, "false", "", "" ], [ "IncludeDefaults", "Copies SQL Server Agent system settings including FailSafeEmailAddress, ForwardingServer, and PagerSubjectTemplate.\r\nUse this when migrating to a new server where you want to replicate the source server\u0027s Agent notification configuration.", "", false, "false", "False", "" ], [ "Force", "Drops and recreates alerts that already exist on the destination servers instead of skipping them.\r\nUse this when you need to overwrite existing alerts with updated configurations from the source.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Migration", "Agent", "Job" ], "CommandName": "Copy-DbaAgentJob", "Name": "Copy-DbaAgentJob", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Copy-DbaAgentJob [[-Source] \u003cDbaInstanceParameter\u003e] [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-Job] \u003cObject[]\u003e] [[-ExcludeJob] \u003cObject[]\u003e] [-DisableOnSource] [-DisableOnDestination] [-Force] [[-NewName] \u003cString\u003e] [-UseLastModified] [[-InputObject] \u003cJob[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "MigrationObject (PSCustomObject)\nReturns one object per job processed, regardless of whether it was successfully copied, skipped, or failed. This provides a consistent record of all job migration operations.\nProperties:\r\n- DateTime: Timestamp when the operation was attempted (DbaDateTime type)\r\n- SourceServer: The name of the source SQL Server instance\r\n- DestinationServer: The name of the destination SQL Server instance\r\n- Name: The name of the SQL Agent job\r\n- Type: Always \"Agent Job\" indicating the type of object being migrated\r\n- Status: The outcome of the operation - \"Successful\", \"Skipped\", or \"Failed\"\r\n- Notes: Descriptive message explaining the status (reason for skip, error details, etc.)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaAgentJob -Source sqlserver2014a -Destination sqlcluster\nCopies all jobs from sqlserver2014a to sqlcluster, using Windows credentials. If jobs with the same name exist on sqlcluster, they will be skipped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaAgentJob -Source sqlserver2014a -Destination sqlcluster -Job PSJob -SourceSqlCredential $cred -Force\nCopies a single job, the PSJob job from sqlserver2014a to sqlcluster, using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster. If a job with the same name exists on \r\nsqlcluster, it will be dropped and recreated because -Force was used.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaAgentJob -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force\nShows what would happen if the command were executed using force.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaAgentJob -SqlInstance sqlserver2014a | Where-Object Category -eq \"Report Server\" | Copy-DbaAgentJob -Destination sqlserver2014b\nCopies all SSRS jobs (subscriptions) from AlwaysOn Primary SQL instance sqlserver2014a to AlwaysOn Secondary SQL instance sqlserver2014b\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eCopy-DbaAgentJob -Source sqlserver2014a -Destination sqlserver2014b -UseLastModified\nCopies jobs from sqlserver2014a to sqlserver2014b, but only creates new jobs or updates existing jobs where the source job has a newer date_modified timestamp. Jobs with matching timestamps are \r\nskipped.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eCopy-DbaAgentJob -Source sqlserver2014a -Destination sqlserver2014a -Job \"OriginalJob\" -NewName \"JobCopy\"\nCopies the job \"OriginalJob\" on sqlserver2014a to the same server as \"JobCopy\". When source and destination are the same instance, -NewName is required.", "Description": "Copies SQL Server Agent jobs from one instance to another while automatically validating all dependencies including databases, logins, proxy accounts, and operators. This eliminates the manual process of checking prerequisites before moving jobs during migrations, disaster recovery, or environment promotions.\n\nThe function intelligently skips jobs associated with maintenance plans and provides detailed validation messages for any missing dependencies. By default, existing jobs are preserved unless -Force is specified to overwrite them.", "Links": "https://dbatools.io/Copy-DbaAgentJob", "Synopsis": "Migrates SQL Server Agent jobs between instances with dependency validation", "Availability": "Windows, Linux, macOS", "Params": [ [ "Source", "Source SQL Server instance containing the jobs to copy. You must have sysadmin access and server version must be SQL Server version 2000 or higher.\r\nUse this when copying jobs from a specific instance rather than piping job objects with InputObject.", "", false, "false", "", "" ], [ "SourceSqlCredential", "Alternative credentials for connecting to the source SQL Server instance. Accepts PowerShell credentials (Get-Credential).\r\nUse this when the source server requires different authentication than your current Windows session, such as SQL authentication or cross-domain scenarios.\r\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.", "", false, "false", "", "" ], [ "Destination", "Destination SQL Server instance(s) where jobs will be created. You must have sysadmin access and the server must be SQL Server 2000 or higher.\r\nSupports multiple destinations to copy jobs to multiple servers simultaneously during migrations or DR setup.", "", true, "false", "", "" ], [ "DestinationSqlCredential", "Alternative credentials for connecting to the destination SQL Server instance. Accepts PowerShell credentials (Get-Credential).\r\nUse this when the destination server requires different authentication than your current Windows session, such as SQL authentication or cross-domain scenarios.\r\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.", "", false, "false", "", "" ], [ "Job", "Specifies which SQL Agent jobs to copy by name. Accepts wildcards and multiple job names.\r\nUse this to copy specific jobs instead of all jobs, such as during selective migrations or when testing job deployments.\r\nIf unspecified, all jobs will be processed.", "", false, "false", "", "" ], [ "ExcludeJob", "Specifies which SQL Agent jobs to skip during the copy operation. Accepts wildcards and multiple job names.\r\nUse this to exclude specific jobs from bulk operations, such as skipping environment-specific jobs or maintenance tasks that shouldn\u0027t be migrated.", "", false, "false", "", "" ], [ "DisableOnSource", "Disables the job on the source server after successfully copying it to the destination.\r\nUse this during server migrations or failover scenarios where you want to prevent the job from running on the old server while it runs on the new one.", "", false, "false", "False", "" ], [ "DisableOnDestination", "Creates the job on the destination server but leaves it disabled.\r\nUse this when deploying jobs to test environments or when you need to review and modify job steps before enabling them in the new environment.", "", false, "false", "False", "" ], [ "Force", "Overwrites existing jobs on the destination server and automatically sets missing job owners to the \u0027sa\u0027 login.\r\nUse this when you need to replace existing jobs or when source job owners don\u0027t exist on the destination server during migrations.", "", false, "false", "False", "" ], [ "NewName", "The new name for the job on the destination server.\r\nRequired when source and destination are the same server instance. Use this to create a copy of a job under a different name on the same or a different server.\r\nCannot be used when copying multiple jobs simultaneously.", "", false, "false", "", "" ], [ "UseLastModified", "When enabled, compares the last modification date (date_modified) from msdb.dbo.sysjobs between source and destination instances.\r\nJobs are only copied or updated if the source job is newer than the destination job. This provides intelligent synchronization:\r\n- If job doesn\u0027t exist on destination: creates it\r\n- If source date_modified is newer: drops and recreates the job\r\n- If dates are equal: skips the job\r\n- If destination is newer: skips with a warning\r\nUse this for incremental synchronization scenarios where you want to keep jobs up-to-date without unconditionally overwriting them.", "", false, "false", "False", "" ], [ "InputObject", "Accepts SQL Agent job objects from the pipeline, typically from Get-DbaAgentJob.\r\nUse this to copy pre-filtered jobs or when combining with other job management cmdlets for complex workflows.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Migration", "Agent" ], "CommandName": "Copy-DbaAgentJobCategory", "Name": "Copy-DbaAgentJobCategory", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Copy-DbaAgentJobCategory -Source \u003cDbaInstanceParameter\u003e [-SourceSqlCredential \u003cPSCredential\u003e] -Destination \u003cDbaInstanceParameter[]\u003e [-DestinationSqlCredential \u003cPSCredential\u003e] [-JobCategory \u003cString[]\u003e] [-AgentCategory \u003cString[]\u003e] [-OperatorCategory \u003cString[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nCopy-DbaAgentJobCategory -Source \u003cDbaInstanceParameter\u003e [-SourceSqlCredential \u003cPSCredential\u003e] -Destination \u003cDbaInstanceParameter[]\u003e [-DestinationSqlCredential \u003cPSCredential\u003e] [-CategoryType \u003cString[]\u003e] [-JobCategory \u003cString[]\u003e] [-AgentCategory \u003cString[]\u003e] [-OperatorCategory \u003cString[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per category processed (whether skipped, successfully copied, or failed). When multiple categories or multiple destination servers are specified, returns multiple objects.\nDefault display properties (via Select-DefaultView with TypeName MigrationObject):\r\n- DateTime: The date and time when the category copy was attempted (DbaDateTime object)\r\n- SourceServer: The name of the source SQL Server instance\r\n- DestinationServer: The name of the destination SQL Server instance\r\n- Name: The name of the category being copied\r\n- Type: The type of category (\"Agent Job Category\", \"Agent Operator Category\", or \"Agent Alert Category\")\r\n- Status: The outcome of the copy operation (Successful, Failed, or Skipped)\r\n- Notes: Additional context about the operation result (e.g., \"Already exists on destination\")\nAll properties are accessible using Select-Object * even though only the above default properties are displayed.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaAgentJobCategory -Source sqlserver2014a -Destination sqlcluster\nCopies all operator categories from sqlserver2014a to sqlcluster using Windows authentication. If operator categories with the same name exist on sqlcluster, they will be skipped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaAgentJobCategory -Source sqlserver2014a -Destination sqlcluster -OperatorCategory PSOperator -SourceSqlCredential $cred -Force\nCopies a single operator category, the PSOperator operator category from sqlserver2014a to sqlcluster using SQL credentials to authenticate to sqlserver2014a and Windows credentials for sqlcluster. \r\nIf an operator category with the same name exists on sqlcluster, it will be dropped and recreated because -Force was used.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaAgentJobCategory -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force\nShows what would happen if the command were executed using force.", "Description": "Migrates custom SQL Agent categories from a source SQL Server to one or more destination servers, so you don\u0027t have to manually recreate organizational structures during server migrations or environment setups.\nThis function copies only user-defined categories (ID \u003e= 100), preserving built-in system categories on the destination.\nEssential for maintaining consistent job categorization across multiple SQL Server instances in enterprise environments.\n\nYou can copy all categories at once or filter by category type (Job, Alert, Operator) or specify individual category names.\nCategories that already exist on the destination will be skipped unless you use -Force to drop and recreate them.\nThe function uses SQL Server Management Objects (SMO) to script category definitions and recreate them on the target server.", "Links": "https://dbatools.io/Copy-DbaAgentJobCategory", "Synopsis": "Copies custom SQL Agent categories for jobs, alerts, and operators between SQL Server instances.", "Availability": "Windows, Linux, macOS", "Params": [ [ "Source", "The source SQL Server instance from which to copy Agent job categories. Requires sysadmin permissions to access MSDB and read category definitions.\r\nUse this to specify the server that has the custom categories you want to replicate to other instances.", "", true, "false", "", "" ], [ "SourceSqlCredential", "Alternative credentials for connecting to the source SQL Server instance. Use this when your current Windows authentication doesn\u0027t have sufficient permissions on the source server.\r\nAccepts credentials created with Get-Credential for SQL authentication or different Windows accounts.", "", false, "false", "", "" ], [ "Destination", "One or more destination SQL Server instances where the Agent job categories will be created. Accepts an array to copy categories to multiple servers simultaneously.\r\nRequires sysadmin permissions to create categories in each destination server\u0027s MSDB database.", "", true, "false", "", "" ], [ "DestinationSqlCredential", "Alternative credentials for connecting to the destination SQL Server instances. Use this when different authentication is needed for the destination servers than your current context.\r\nAccepts credentials created with Get-Credential and applies to all destination servers specified.", "", false, "false", "", "" ], [ "CategoryType", "Filters the copy operation to specific category types: Job, Alert, or Operator. When specified, copies all categories of the selected type(s) from the source.\r\nUse this for bulk migration of entire category types rather than individual category names. Leave empty to copy all category types.", "", false, "false", "", "Job,Alert,Operator" ], [ "JobCategory", "Specific job category names to copy from the source server. Use this for selective migration when you only need certain job categories.\r\nSupports tab completion from the source server\u0027s existing job categories for convenience.", "", false, "false", "", "" ], [ "AgentCategory", "Specific alert category names to copy from the source server. Use this for selective migration when you only need certain alert categories.\r\nNote: This parameter is currently not implemented in the function code and will be ignored if used.", "", false, "false", "", "" ], [ "OperatorCategory", "Specific operator category names to copy from the source server. Use this for selective migration when you only need certain operator categories.\r\nSupports tab completion from the source server\u0027s existing operator categories for convenience.", "", false, "false", "", "" ], [ "Force", "Drops and recreates existing categories on the destination servers instead of skipping them. Use this when you need to overwrite categories that have changed on the source.\r\nWithout this switch, categories that already exist on the destination will be skipped to prevent data loss.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Migration", "Agent", "Job" ], "CommandName": "Copy-DbaAgentJobStep", "Name": "Copy-DbaAgentJobStep", "Author": "the dbatools team + Claude", "Syntax": "Copy-DbaAgentJobStep [[-Source] \u003cDbaInstanceParameter\u003e] [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-Job] \u003cObject[]\u003e] [[-ExcludeJob] \u003cObject[]\u003e] [[-Step] \u003cString[]\u003e] [[-InputObject] \u003cJob[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject (MigrationObject)\nReturns one object per job processed with the following properties:\nDefault display properties (via Select-DefaultView):\r\n- DateTime: The timestamp when the job step copy operation was executed\r\n- SourceServer: The name of the source SQL Server instance\r\n- DestinationServer: The name of the destination SQL Server instance\r\n- Name: The name of the SQL Agent job\r\n- Type: The operation type, always \"Agent Job Steps\"\r\n- Status: The status of the operation - \"Successful\" if steps were copied, \"Skipped\" if the destination job does not exist, or \"Failed\" if an error occurred\r\n- Notes: Additional information about the operation, such as the number of steps synchronized or reason for skipping/failure\nAll properties are always available on the returned object even though Select-DefaultView limits the display.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaAgentJobStep -Source PrimaryAG -Destination SecondaryAG1, SecondaryAG2 -Job \"MaintenanceJob\"\nCopies all job steps from the \"MaintenanceJob\" on PrimaryAG to the same job on SecondaryAG1 and SecondaryAG2, preserving job history on the destination servers.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgentJob -SqlInstance PrimaryAG -Job \"BackupJob\" | Copy-DbaAgentJobStep -Destination SecondaryAG1\nRetrieves the BackupJob from PrimaryAG and synchronizes its steps to the same job on SecondaryAG1 using pipeline input.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaAgentJobStep -Source sqlserver2014a -Destination sqlcluster -Job \"DataETL\" -SourceSqlCredential $cred\nCopies job steps for the \"DataETL\" job from sqlserver2014a to sqlcluster, using SQL credentials for the source server and Windows credentials for the destination.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eCopy-DbaAgentJobStep -Source Primary -Destination Replica1, Replica2, Replica3\nSynchronizes all job steps from Primary to multiple AG replicas, ensuring all replicas have identical job step definitions while preserving their individual job execution histories.", "Description": "Synchronizes SQL Server Agent job steps between instances by copying step definitions from source jobs to destination jobs. Unlike Copy-DbaAgentJob with -Force, this command preserves job execution history because it only drops and recreates individual steps rather than the entire job. This is essential for maintaining historical job execution data in Always On Availability Group scenarios, disaster recovery environments, or when deploying step modifications across multiple servers.\n\nThe function removes all existing steps from the destination job before copying source steps, ensuring a clean synchronization. Job metadata like ownership, schedules, and alerts remain unchanged on the destination.", "Links": "https://dbatools.io/Copy-DbaAgentJobStep", "Synopsis": "Copies job steps from one SQL Server Agent job to another, preserving job history by synchronizing steps without dropping the job itself.", "Availability": "Windows, Linux, macOS", "Params": [ [ "Source", "Source SQL Server instance containing the jobs with steps to copy. You must have sysadmin access and server version must be SQL Server 2000 or higher.\r\nUse this when copying job steps from a specific instance rather than piping job objects with InputObject.", "", false, "false", "", "" ], [ "SourceSqlCredential", "Alternative credentials for connecting to the source SQL Server instance. Accepts PowerShell credentials (Get-Credential).\r\nUse this when the source server requires different authentication than your current Windows session, such as SQL authentication or cross-domain scenarios.\r\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.", "", false, "false", "", "" ], [ "Destination", "Destination SQL Server instance(s) where job steps will be synchronized. You must have sysadmin access and the server must be SQL Server 2000 or higher.\r\nSupports multiple destinations to copy job steps to multiple servers simultaneously, such as syncing all AG replicas or DR servers.", "", true, "false", "", "" ], [ "DestinationSqlCredential", "Alternative credentials for connecting to the destination SQL Server instance. Accepts PowerShell credentials (Get-Credential).\r\nUse this when the destination server requires different authentication than your current Windows session, such as SQL authentication or cross-domain scenarios.\r\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.", "", false, "false", "", "" ], [ "Job", "Specifies which SQL Agent jobs to process by name. Accepts wildcards and multiple job names.\r\nUse this to synchronize steps for specific jobs, such as copying modified steps from a primary AG replica to secondary replicas.\r\nIf unspecified, all jobs will be processed.", "", false, "false", "", "" ], [ "ExcludeJob", "Specifies which SQL Agent jobs to skip during the copy operation. Accepts wildcards and multiple job names.\r\nUse this to exclude specific jobs from bulk operations, such as skipping environment-specific jobs that shouldn\u0027t be synchronized.", "", false, "false", "", "" ], [ "Step", "Specifies which job steps to copy by name. If not specified, all steps are copied.\r\nUse this to synchronize specific steps rather than all steps from a job.", "", false, "false", "", "" ], [ "InputObject", "Accepts SQL Agent job objects from the pipeline, typically from Get-DbaAgentJob.\r\nUse this to copy steps for pre-filtered jobs or when combining with other job management cmdlets for complex workflows.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Migration", "Agent", "Operator" ], "CommandName": "Copy-DbaAgentOperator", "Name": "Copy-DbaAgentOperator", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Copy-DbaAgentOperator [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-Operator] \u003cObject[]\u003e] [[-ExcludeOperator] \u003cObject[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "MigrationObject (PSCustomObject)\nReturns one object per operator processed, containing the migration status for that operator.\nDefault display properties:\r\n- DateTime: Timestamp when the copy operation was executed\r\n- SourceServer: Name of the source SQL Server instance\r\n- DestinationServer: Name of the destination SQL Server instance\r\n- Name: The name of the Agent Operator that was copied\r\n- Type: Always set to \"Agent Operator\"\r\n- Status: Result of the copy operation (Successful, Skipped, or Failed)\r\n- Notes: Additional details about the operation result (e.g., \"Already exists on destination\")\nAll properties from the object are accessible via Select-Object * if needed.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaAgentOperator -Source sqlserver2014a -Destination sqlcluster\nCopies all operators from sqlserver2014a to sqlcluster using Windows credentials. If operators with the same name exist on sqlcluster, they will be skipped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaAgentOperator -Source sqlserver2014a -Destination sqlcluster -Operator PSOperator -SourceSqlCredential $cred -Force\nCopies only the PSOperator operator from sqlserver2014a to sqlcluster using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster. If an operator with the same name exists on \r\nsqlcluster, it will be dropped and recreated because -Force was used.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaAgentOperator -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force\nShows what would happen if the command were executed using force.", "Description": "Copies SQL Server Agent operators from a source instance to one or more destination instances, preserving all operator properties including email addresses, pager numbers, and notification schedules. This is essential during server migrations, environment standardization, or when setting up identical alerting configurations across multiple instances.\n\nAll operators are copied by default, but you can target specific operators or exclude certain ones. Existing operators on the destination are skipped unless you use -Force to overwrite them. The function protects failsafe operators from being accidentally dropped during forced operations.\n\nEach operator is scripted from the source using SQL Management Objects and recreated on the destination, ensuring all configuration details are preserved exactly as configured on the source instance.", "Links": "https://dbatools.io/Copy-DbaAgentOperator", "Synopsis": "Copies SQL Server Agent operators between instances for migration and standardization.", "Availability": "Windows, Linux, macOS", "Params": [ [ "Source", "The SQL Server instance containing the operators you want to copy from. Must be SQL Server 2000 or higher.\r\nUse this to specify which instance has the existing operators that need to be migrated or replicated to other instances.", "", true, "false", "", "" ], [ "SourceSqlCredential", "Credentials for connecting to the source SQL Server instance when Windows Authentication is not available.\r\nUse this when the source server requires SQL Server Authentication or when running under a different user context than your current Windows session.", "", false, "false", "", "" ], [ "Destination", "One or more SQL Server instances where the operators will be copied to. Must be SQL Server 2000 or higher.\r\nAccepts multiple instances to copy operators to several servers at once during migrations or standardization projects.", "", true, "false", "", "" ], [ "DestinationSqlCredential", "Credentials for connecting to the destination SQL Server instances when Windows Authentication is not available.\r\nUse this when the destination servers require SQL Server Authentication or when running under a different user context than your current Windows session.", "", false, "false", "", "" ], [ "Operator", "Specifies which operators to copy by name. Accepts wildcards and multiple operator names.\r\nUse this when you only need to migrate specific operators instead of copying all operators from the source instance.", "", false, "false", "", "" ], [ "ExcludeOperator", "Operators to skip during the copy operation. Accepts wildcards and multiple operator names.\r\nUse this to copy most operators while excluding specific ones, such as development-only or temporary operators.", "", false, "false", "", "" ], [ "Force", "Drops and recreates operators that already exist on the destination instances.\r\nUse this when you need to overwrite existing operators with updated configurations from the source, but note that failsafe operators are protected and will be skipped.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Migration", "Agent" ], "CommandName": "Copy-DbaAgentProxy", "Name": "Copy-DbaAgentProxy", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Copy-DbaAgentProxy [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-ProxyAccount] \u003cString[]\u003e] [[-ExcludeProxyAccount] \u003cString[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject (MigrationObject)\nReturns one object per proxy account processed, showing the migration status and details.\nDefault display properties (via Select-DefaultView):\r\n- DateTime: The timestamp when the operation was performed (DbaDateTime type)\r\n- SourceServer: The name of the source SQL Server instance\r\n- DestinationServer: The name of the destination SQL Server instance\r\n- Name: The name of the proxy account or associated credential being migrated\r\n- Type: The object type being migrated (Agent Proxy, Credential, or ProxyAccount)\r\n- Status: The migration status (Successful, Skipped, Failed, or Skipping)\r\n- Notes: Additional details about the operation outcome or reason for skipping", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaAgentProxy -Source sqlserver2014a -Destination sqlcluster\nCopies all proxy accounts from sqlserver2014a to sqlcluster using Windows credentials. If proxy accounts with the same name exist on sqlcluster, they will be skipped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaAgentProxy -Source sqlserver2014a -Destination sqlcluster -ProxyAccount PSProxy -SourceSqlCredential $cred -Force\nCopies only the PSProxy proxy account from sqlserver2014a to sqlcluster using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster. If a proxy account with the same name exists \r\non sqlcluster, it will be dropped and recreated because -Force was used.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaAgentProxy -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force\nShows what would happen if the command were executed using force.", "Description": "Migrates SQL Server Agent proxy accounts between instances, enabling job steps to run under different security contexts than the SQL Agent service account. By default, all proxy accounts are copied, but you can specify individual accounts to migrate or exclude specific ones. The function requires that associated credentials already exist on the destination server before copying proxy accounts. If a proxy account already exists on the destination, it will be skipped unless you use -Force to overwrite it.", "Links": "https://dbatools.io/Copy-DbaAgentProxy", "Synopsis": "Copies SQL Server Agent proxy accounts from one instance to another.", "Availability": "Windows, Linux, macOS", "Params": [ [ "Source", "Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.", "", true, "false", "", "" ], [ "SourceSqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Destination", "Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.", "", true, "false", "", "" ], [ "DestinationSqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "ProxyAccount", "Specifies which proxy accounts to copy from the source server. Accepts an array of proxy account names.\r\nUse this when you only need to migrate specific proxy accounts instead of all available accounts on the source server.", "", false, "false", "", "" ], [ "ExcludeProxyAccount", "Specifies proxy accounts to skip during migration. Accepts an array of proxy account names to exclude.\r\nUse this when you want to copy most proxy accounts but need to avoid migrating specific ones that may conflict or aren\u0027t needed on the destination.", "", false, "false", "", "" ], [ "Force", "Forces overwriting of existing proxy accounts on the destination server by dropping and recreating them.\r\nUse this when you need to update proxy accounts that already exist on the destination with the current configuration from the source server.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Migration", "Agent" ], "CommandName": "Copy-DbaAgentSchedule", "Name": "Copy-DbaAgentSchedule", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Copy-DbaAgentSchedule [[-Source] \u003cDbaInstanceParameter\u003e] [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-Schedule] \u003cString[]\u003e] [[-Id] \u003cInt32[]\u003e] [[-InputObject] \u003cJobSchedule[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per schedule copied, with migration status details for each operation.\nProperties:\r\n- SourceServer: Name of the source SQL Server instance containing the original schedule\r\n- DestinationServer: Name of the destination SQL Server instance where the schedule was copied\r\n- Name: The name of the job schedule that was copied\r\n- Type: The type of object copied (always \"Agent Schedule\")\r\n- Status: The result of the copy operation (\"Successful\", \"Skipped\", or \"Failed\")\r\n- Notes: Additional context explaining the status (e.g., \"Already exists on destination\", \"Schedule has associated jobs\")\r\n- DateTime: Timestamp (UTC) when the copy operation was performed\nDefault display order: DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaAgentSchedule -Source sqlserver2014a -Destination sqlcluster\nCopies all shared job schedules from sqlserver2014a to sqlcluster using Windows credentials. If shared job schedules with the same name exist on sqlcluster, they will be skipped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaAgentSchedule -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force\nShows what would happen if the command were executed using force.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaAgentSchedule -SqlInstance sql2016 | Out-GridView -Passthru | Copy-DbaAgentSchedule -Destination sqlcluster\nGets a list of schedule, outputs to a gridview which can be selected from, then copies to SqlInstance", "Description": "Copies shared job schedules (not job-specific schedules) from the source SQL Server Agent to one or more destination instances using T-SQL scripting. This is essential when standardizing job schedules across multiple servers or migrating Agent configurations to new instances. Existing schedules are skipped by default unless -Force is specified, and schedules with associated jobs cannot be overwritten even with Force to prevent breaking existing job assignments. Use this instead of manually recreating complex recurring schedules with specific timing requirements across your SQL Server environment.", "Links": "https://dbatools.io/Copy-DbaAgentSchedule", "Synopsis": "Migrates SQL Agent shared job schedules between SQL Server instances for job schedule standardization.", "Availability": "Windows, Linux, macOS", "Params": [ [ "Source", "Specifies the source SQL Server instance containing the shared job schedules to copy. When specified, all shared schedules (or those filtered by Schedule/Id parameters) will be copied from this \r\ninstance.\r\nUse this parameter when copying schedules from a specific server, or omit it when piping schedules from Get-DbaAgentSchedule.", "", false, "false", "", "" ], [ "SourceSqlCredential", "Specifies alternative credentials for connecting to the source SQL Server instance. Use this when the current Windows user lacks sufficient permissions or when connecting with SQL Server \r\nauthentication.\r\nAccepts credentials created with Get-Credential or saved credential objects. Required when copying from instances that don\u0027t accept your current Windows authentication.", "", false, "false", "", "" ], [ "Destination", "Specifies one or more destination SQL Server instances where the shared job schedules will be copied. This parameter accepts multiple instances, allowing you to deploy schedules to several servers \r\nsimultaneously.\r\nUse this when standardizing schedules across multiple instances or when migrating Agent configurations to new servers.", "", true, "false", "", "" ], [ "DestinationSqlCredential", "Specifies alternative credentials for connecting to the destination SQL Server instances. Use this when the current Windows user lacks sufficient permissions on the target servers or when connecting \r\nwith SQL Server authentication.\r\nAccepts credentials created with Get-Credential or saved credential objects. Required when copying to instances that don\u0027t accept your current Windows authentication.", "", false, "false", "", "" ], [ "Schedule", "Filters the operation to copy only schedules with specific names. Accepts an array of schedule names using wildcard patterns for flexible matching.\r\nUse this when you need to copy only certain schedules instead of all shared schedules. Since SQL Server allows duplicate schedule names, combine with Id parameter for precise targeting.", "", false, "false", "", "" ], [ "Id", "Filters the operation to copy only schedules with specific numeric IDs. Accepts an array of schedule IDs for targeting multiple specific schedules.\r\nUse this instead of schedule names when you need precise identification, especially when duplicate schedule names exist on the source instance.", "", false, "false", "", "" ], [ "InputObject", "Accepts job schedule objects from the pipeline, typically from Get-DbaAgentSchedule. When provided, these specific schedule objects will be copied instead of querying the source instance.\r\nUse this for advanced scenarios like selective copying based on complex filtering or when working with schedules from multiple source instances.", "", false, "true (ByValue)", "", "" ], [ "Force", "Forces the overwrite of existing schedules on the destination instances by dropping and recreating them. Without this switch, existing schedules are skipped.\r\nUse this when you need to update existing schedules with new configurations. Note that schedules currently assigned to jobs cannot be overwritten, even with Force enabled.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Migration", "SqlServerAgent", "SqlAgent" ], "CommandName": "Copy-DbaAgentServer", "Name": "Copy-DbaAgentServer", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Copy-DbaAgentServer [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [-DisableJobsOnDestination] [-DisableJobsOnSource] [-ExcludeServerProperties] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject (MigrationObject type)\nReturns one object per destination instance. The object contains details about the Agent server properties migration status.\nDefault display properties:\r\n- DateTime: The timestamp when the copy operation was executed (DbaDateTime)\r\n- SourceServer: The name of the source SQL Server instance\r\n- DestinationServer: The name of the destination SQL Server instance\r\n- Name: Description of what was copied (\"Server level properties\")\r\n- Type: Category of objects copied (\"Agent Properties\")\r\n- Status: Result of the copy operation (Skipped, Successful, or Failed)\r\n- Notes: Error message if the operation failed; null if successful or skipped\nWhen -ExcludeServerProperties is specified, Status will be \"Skipped\". Otherwise, Status will be \"Successful\" unless an error occurred during the copy operation.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaAgentServer -Source sqlserver2014a -Destination sqlcluster\nCopies all job server objects from sqlserver2014a to sqlcluster using Windows credentials for authentication. If job objects with the same name exist on sqlcluster, they will be skipped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaAgentServer -Source sqlserver2014a -Destination sqlcluster -SourceSqlCredential $cred\nCopies all job objects from sqlserver2014a to sqlcluster using SQL credentials to authentication to sqlserver2014a and Windows credentials to authenticate to sqlcluster.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaAgentServer -Source sqlserver2014a -Destination sqlcluster -WhatIf\nShows what would happen if the command were executed.", "Description": "Migrates complete SQL Server Agent configuration including jobs, operators, alerts, schedules, job categories, and proxies from one instance to another. This function handles the proper sequence of object creation and also copies server-level Agent properties like job history retention settings, error log locations, and database mail profiles. Essential for server migrations, disaster recovery setups, or standardizing Agent configurations across multiple environments without manually recreating dozens of objects.\n\nYou must have sysadmin access and server version must be SQL Server version 2000 or greater.", "Links": "https://dbatools.io/Copy-DbaAgentServer", "Synopsis": "Copies all SQL Server Agent objects and server properties between instances.", "Availability": "Windows, Linux, macOS", "Params": [ [ "Source", "Source SQL Server instance containing the Agent objects you want to copy. All jobs, schedules, operators, alerts, proxies, and server properties will be migrated from this instance.\r\nMust have sysadmin access and be SQL Server 2000 or higher.", "", true, "false", "", "" ], [ "SourceSqlCredential", "Authentication credentials for connecting to the Source SQL Server instance. Use this when you need SQL Server authentication instead of Windows authentication.\r\nCreate credentials using Get-Credential and pass them to this parameter. Common when source server is in different domain or requires SQL login.", "", false, "false", "", "" ], [ "Destination", "Target SQL Server instance(s) where Agent objects will be copied. Accepts multiple instances to copy the same configuration to several servers at once.\r\nMust have sysadmin access and be SQL Server 2000 or higher. Useful for standardizing Agent configurations across development, test, and production environments.", "", true, "false", "", "" ], [ "DestinationSqlCredential", "Authentication credentials for connecting to the Destination SQL Server instance(s). Use this when you need SQL Server authentication instead of Windows authentication.\r\nCreate credentials using Get-Credential and pass them to this parameter. Required when destination servers use different authentication than your current context.", "", false, "false", "", "" ], [ "DisableJobsOnDestination", "Disables all copied jobs on the destination instance after migration completes. Jobs will exist but won\u0027t run until manually enabled.\r\nUse this when copying to test environments where you don\u0027t want production jobs running automatically, or during staged migrations where jobs should remain inactive initially.", "", false, "false", "False", "" ], [ "DisableJobsOnSource", "Disables all jobs on the source instance after copying them to destination. Jobs will exist but won\u0027t run until manually re-enabled.\r\nUse this during server migrations when you want to prevent jobs from running on the old server after moving them to the new instance.", "", false, "false", "False", "" ], [ "ExcludeServerProperties", "Skips copying SQL Agent server-level configuration like job history retention settings, error log locations, database mail profiles, and service restart preferences.\r\nUse this when you only want to copy jobs and schedules but keep the destination server\u0027s existing Agent configuration settings intact.", "", false, "false", "False", "" ], [ "Force", "Overwrites existing Agent objects on destination that have matching names from source. Objects are dropped first, then recreated with source configuration.\r\nUse this when you want to ensure destination matches source exactly, replacing any existing jobs, operators, or schedules with conflicting names.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Migration", "Backup" ], "CommandName": "Copy-DbaBackupDevice", "Name": "Copy-DbaBackupDevice", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Copy-DbaBackupDevice [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-BackupDevice] \u003cObject[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per backup device processed, containing the status and details of the copy operation.\nProperties:\r\n- DateTime: Timestamp when the operation was processed (DbaDateTime object)\r\n- SourceServer: Name of the source SQL Server instance\r\n- DestinationServer: Name of the destination SQL Server instance\r\n- Name: Name of the backup device\r\n- Type: Always returns \"Backup Device\"\r\n- Status: Result of the operation (Successful, Skipped, or Failed)\r\n- Notes: Additional information about the operation (e.g., \"Already exists on destination\" or error details)\nThe output uses Select-DefaultView to display the properties in the order: DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes. All properties are available via Select-Object * if \r\nadditional fields are needed.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaBackupDevice -Source sqlserver2014a -Destination sqlcluster\nCopies all server backup devices from sqlserver2014a to sqlcluster using Windows credentials. If backup devices with the same name exist on sqlcluster, they will be skipped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaBackupDevice -Source sqlserver2014a -Destination sqlcluster -BackupDevice backup01 -SourceSqlCredential $cred -Force\nCopies only the backup device named backup01 from sqlserver2014a to sqlcluster using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster. If a backup device with the same \r\nname exists on sqlcluster, it will be dropped and recreated because -Force was used.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaBackupDevice -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force\nShows what would happen if the command were executed using force.", "Description": "Copies SQL Server backup devices from one instance to another, handling both the logical device definition and the physical backup files. This simplifies server migrations and disaster recovery setup by ensuring backup devices are available on target instances.\n\nPhysical backup files are transferred using admin shares, and if the original directory structure doesn\u0027t exist on the destination, files are automatically placed in SQL Server\u0027s default backup directory. Existing backup devices are skipped unless -Force is specified to overwrite them.", "Links": "https://dbatools.io/Copy-DbaBackupDevice", "Synopsis": "Migrates SQL Server backup devices between instances including both device definitions and physical files", "Availability": "Windows only", "Params": [ [ "Source", "Specifies the source SQL Server instance containing the backup devices to copy. The source instance must be SQL Server 2000 or higher with sysadmin access required.\r\nUse this when migrating backup devices from an existing SQL Server to consolidate backup infrastructure or during server migrations.", "", true, "false", "", "" ], [ "SourceSqlCredential", "Specifies alternative credentials for connecting to the source SQL Server instance. Accepts PowerShell credentials created with Get-Credential.\r\nUse this when the source server requires different authentication than your current Windows session, such as SQL Server authentication or a different domain account.\r\nSupports Windows Authentication, SQL Server Authentication, Active Directory Password, and Active Directory Integrated. For MFA support, use Connect-DbaInstance first.", "", false, "false", "", "" ], [ "Destination", "Specifies one or more destination SQL Server instances where backup devices will be created. Each destination instance must be SQL Server 2000 or higher with sysadmin access required.\r\nUse this to specify target servers during migrations, disaster recovery setup, or when standardizing backup device configurations across multiple instances.", "", true, "false", "", "" ], [ "DestinationSqlCredential", "Specifies alternative credentials for connecting to the destination SQL Server instances. Accepts PowerShell credentials created with Get-Credential.\r\nUse this when destination servers require different authentication than your current Windows session, such as SQL Server authentication or different domain accounts.\r\nSupports Windows Authentication, SQL Server Authentication, Active Directory Password, and Active Directory Integrated. For MFA support, use Connect-DbaInstance first.", "", false, "false", "", "" ], [ "BackupDevice", "Specifies which backup devices to copy from the source instance. Accepts an array of backup device names and supports tab completion with available devices.\r\nUse this to selectively copy specific backup devices instead of migrating all devices, which is helpful when you only need certain backup configurations on the destination.", "", false, "false", "", "" ], [ "Force", "Forces the recreation of backup devices that already exist on the destination instance by dropping them first. Without this switch, existing backup devices are skipped.\r\nUse this when you need to overwrite existing backup device configurations with updated settings from the source, such as changing file paths or device properties during migrations.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "WSMan", "Migration" ], "CommandName": "Copy-DbaCredential", "Name": "Copy-DbaCredential", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Copy-DbaCredential [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-Name] \u003cString[]\u003e] [[-ExcludeName] \u003cString[]\u003e] [[-Identity] \u003cString[]\u003e] [[-ExcludeIdentity] \u003cString[]\u003e] [-ExcludePassword] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject (MigrationObject type)\nReturns one object per credential copy operation (successful, skipped, or failed).\nProperties:\r\n- DateTime: Timestamp of when the operation was executed (DbaDateTime)\r\n- SourceServer: The name of the source SQL Server instance where the credential was copied from\r\n- DestinationServer: The name of the destination SQL Server instance where the credential was copied to\r\n- Name: The name of the credential that was migrated\r\n- Type: The type of object migrated (always \"Credential\" for this command)\r\n- Status: The result of the operation (Successful, Skipping, or Failed)\r\n- Notes: Additional details about the operation result, such as why a credential was skipped or the reason for failure", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaCredential -Source sqlserver2014a -Destination sqlcluster\nCopies all SQL Server Credentials on sqlserver2014a to sqlcluster. If Credentials exist on destination, they will be skipped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaCredential -Source sqlserver2014a -Destination sqlcluster -Name \"PowerShell Proxy Account\" -Force\nCopies over one SQL Server Credential (PowerShell Proxy Account) from sqlserver to sqlcluster. If the Credential already exists on the destination, it will be dropped and recreated.", "Description": "Copies SQL Server credentials from source to destination instances without losing the original passwords, which normally can\u0027t be retrieved through standard methods. This function uses a Dedicated Admin Connection (DAC) and password decryption techniques to extract the actual credential passwords from the source server and recreate them identically on the destination.\n\nThis is essential for server migrations, disaster recovery setup, or environment synchronization where you need to move service accounts, proxy credentials, or linked server authentication without having to reset passwords or contact application teams for credentials.\n\nThe function requires sysadmin privileges on both servers, Windows administrator access, and DAC enabled on the source instance. It supports filtering by credential name or identity and can handle cryptographic provider credentials used for Extensible Key Management (EKM).\n\nCredit: Based on password decryption techniques by Antti Rantasaari (NetSPI, 2014)\nhttps://blog.netspi.com/decrypting-mssql-database-link-server-passwords/", "Links": "https://dbatools.io/Copy-DbaCredential", "Synopsis": "Migrates SQL Server credentials between instances while preserving encrypted passwords.", "Availability": "Windows only", "Params": [ [ "Source", "Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2005 or higher.\nYou must be able to open a dedicated admin connection (DAC) to the source SQL Server.", "", true, "false", "", "" ], [ "SourceSqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Credential", "Login to the target OS using alternative credentials. Accepts credential objects (Get-Credential)\nOnly used when passwords are being exported, as it requires access to the Windows OS via PowerShell remoting to decrypt the passwords.", "", false, "false", "", "" ], [ "Destination", "Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2005 or higher.", "", true, "false", "", "" ], [ "DestinationSqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Name", "Specifies the credential names to copy from the source server. Does not supports wildcards for pattern matching.\r\nUse this when you only need to migrate specific credentials instead of all credentials on the server.\r\nNote: if spaces exist in the credential name, you will have to type \"\" or \u0027\u0027 around it.", "", false, "false", "", "" ], [ "ExcludeName", "Specifies credential names to exclude from the copy operation. Does not support wildcards for pattern matching.\r\nUse this when you want to copy most credentials but skip specific ones like test accounts or deprecated credentials.", "", false, "false", "", "" ], [ "Identity", "Specifies the credential identities (user accounts) to copy from the source server. Does not support wildcards for pattern matching.\r\nUse this when you need to migrate credentials for specific service accounts or domain users rather than filtering by credential name.\r\nNote: if spaces exist in the credential identity, you will have to type \"\" or \u0027\u0027 around it.", "CredentialIdentity", false, "false", "", "" ], [ "ExcludeIdentity", "Specifies credential identities (user accounts) to exclude from the copy operation. Does not support wildcards for pattern matching.\r\nUse this when you want to copy most credentials but skip those associated with specific service accounts or domain users.", "ExcludeCredentialIdentity", false, "false", "", "" ], [ "ExcludePassword", "Copies credential definitions without the actual password values.\r\nUse this in security-conscious environments where password decryption is restricted or when passwords should be manually reset after migration.", "", false, "false", "False", "" ], [ "Force", "Overwrites existing credentials on the destination server by dropping and recreating them with the source values.\r\nUse this when you need to update credential passwords or identities that have changed on the source server since the last migration.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Migration", "CustomError" ], "CommandName": "Copy-DbaCustomError", "Name": "Copy-DbaCustomError", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Copy-DbaCustomError [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-CustomError] \u003cObject[]\u003e] [[-ExcludeCustomError] \u003cObject[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per custom error processed (whether skipped, failed, or successfully copied). Each object represents the migration status of a single custom error ID and language combination.\nDefault display properties (via Select-DefaultView):\r\n- DateTime: Timestamp when the operation occurred\r\n- SourceServer: The name of the source SQL Server instance\r\n- DestinationServer: The name of the destination SQL Server instance\r\n- Name: The custom error ID being migrated\r\n- Type: The type of object migrated (always \"Custom error\")\r\n- Status: The outcome of the operation (Successful, Skipped, or Failed)\r\n- Notes: Additional details about the operation (error message if failed, reason if skipped)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaCustomError -Source sqlserver2014a -Destination sqlcluster\nCopies all server custom errors from sqlserver2014a to sqlcluster using Windows credentials. If custom errors with the same name exist on sqlcluster, they will be skipped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaCustomError -Source sqlserver2014a -SourceSqlCredential $scred -Destination sqlcluster -DestinationSqlCredential $dcred -CustomError 60000 -Force\nCopies only the custom error with ID number 60000 from sqlserver2014a to sqlcluster using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster. If a custom error with the same \r\nname exists on sqlcluster, it will be updated because -Force was used.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaCustomError -Source sqlserver2014a -Destination sqlcluster -ExcludeCustomError 60000 -Force\nCopies all the custom errors found on sqlserver2014a except the custom error with ID number 60000 to sqlcluster. If a custom error with the same name exists on sqlcluster, it will be updated because \r\n-Force was used.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eCopy-DbaCustomError -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force\nShows what would happen if the command were executed using force.", "Description": "Copies user-defined error messages from the source server\u0027s sys.messages system catalog to one or more destination servers. This is essential when migrating applications that rely on custom error numbers and messages, or when standardizing error handling across multiple SQL Server environments.\n\nCustom errors created with sp_addmessage are automatically discovered and migrated, including all language translations. The English (us_english) version is always created first since SQL Server requires it as the base language before adding translations.\n\nBy default, existing custom errors on the destination are skipped to prevent conflicts. Use -Force to overwrite existing errors. If you drop the English version of a custom error, all language translations for that error ID are automatically dropped as well.", "Links": "https://dbatools.io/Copy-DbaCustomError", "Synopsis": "Migrates custom error messages and their language translations between SQL Server instances", "Availability": "Windows, Linux, macOS", "Params": [ [ "Source", "Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.", "", true, "false", "", "" ], [ "SourceSqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Destination", "Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.", "", true, "false", "", "" ], [ "DestinationSqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "CustomError", "Specifies which custom error message IDs to migrate from the source server. Only the specified error numbers will be copied to the destination.\r\nUse this when you need to migrate specific custom errors rather than all of them, such as when standardizing only certain application error codes across environments.", "", false, "false", "", "" ], [ "ExcludeCustomError", "Specifies which custom error message IDs to skip during migration. All custom errors except the excluded ones will be copied.\r\nUse this when you want to migrate most custom errors but exclude problematic ones, or when certain error IDs are environment-specific and shouldn\u0027t be copied.", "", false, "false", "", "" ], [ "Force", "Overwrites existing custom errors on the destination server by dropping and recreating them with source values.\r\nUse this when you need to update custom error messages that have changed on the source, or when synchronizing error definitions across environments.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Migration", "Backup", "Restore" ], "CommandName": "Copy-DbaDatabase", "Name": "Copy-DbaDatabase", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Copy-DbaDatabase [-Source \u003cDbaInstanceParameter\u003e] [-SourceSqlCredential \u003cPSCredential\u003e] -Destination \u003cDbaInstanceParameter[]\u003e [-DestinationSqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-AllDatabases] -BackupRestore [-AdvancedBackupParams \u003cHashtable\u003e] [-SharedPath \u003cString\u003e] [-AzureCredential \u003cString\u003e] [-WithReplace] [-NoRecovery] [-NoBackupCleanup] [-NumberFiles \u003cInt32\u003e] [-SetSourceReadOnly] [-SetSourceOffline] [-ReuseSourceFolderStructure] [-IncludeSupportDbs] [-UseLastBackup] [-Continue] [-InputObject \u003cDatabase[]\u003e] [-NoCopyOnly] [-KeepCDC] \r\n[-KeepReplication] [-NewName \u003cString\u003e] [-Prefix \u003cString\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nCopy-DbaDatabase [-Source \u003cDbaInstanceParameter\u003e] [-SourceSqlCredential \u003cPSCredential\u003e] -Destination \u003cDbaInstanceParameter[]\u003e [-DestinationSqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-AllDatabases] [-AzureCredential \u003cString\u003e] -DetachAttach [-Reattach] [-SetSourceReadOnly] [-SetSourceOffline] [-ReuseSourceFolderStructure] [-IncludeSupportDbs] [-InputObject \u003cDatabase[]\u003e] [-NoCopyOnly] [-NewName \u003cString\u003e] [-Prefix \u003cString\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database migrated, with the following properties:\r\n- DateTime: The timestamp when the migration status was recorded (DbaDateTime)\r\n- SourceServer: The name of the source SQL Server instance\r\n- DestinationServer: The name of the destination SQL Server instance\r\n- Name: The original database name on the source instance\r\n- DestinationDatabase: The database name on the destination instance (may differ if -NewName or -Prefix was used)\r\n- Type: The migration method used - either \"Database (BackupRestore)\" or \"Database (DetachAttach)\"\r\n- Status: The outcome of the migration operation (Successful, Failed, or Skipped)\r\n- Notes: Additional details about the migration, including reasons for failure or skip conditions", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaDatabase -Source sql2014a -Destination sql2014b -Database TestDB -BackupRestore -SharedPath \\\\fileshare\\sql\\migration\nMigrates a single user database TestDB using Backup and restore from instance sql2014a to sql2014b. Backup files are stored in \\\\fileshare\\sql\\migration.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaDatabase -Source sql2012 -Destination sql2014, sql2016 -DetachAttach -Reattach\nDatabases will be migrated from sql2012 to both sql2014 and sql2016 using the detach/copy files/attach method. The following will be performed: kick all users out of the database, detach all data/log \r\nfiles, files copied to the admin share (\\\\SqlSERVER\\M$\\MSSql...) of destination server, attach file on destination server, reattach at source. If the database files (*.mdf, *.ndf, *.ldf) on \r\n*destination* exist and aren\u0027t in use, they will be overwritten.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaDatabase -Source sql2014a -Destination sqlcluster, sql2016 -BackupRestore -UseLastBackup -Force\nMigrates all user databases to sqlcluster and sql2016 using the last Full, Diff and Log backups from sql204a. If the databases exist on the destinations, they will be dropped prior to attach.\nNote that the backups must exist in a location accessible by all destination servers, such a network share.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eCopy-DbaDatabase -Source sql2014a -Destination sqlcluster -ExcludeDatabase Northwind, pubs -IncludeSupportDbs -Force -BackupRestore -SharedPath \\\\fileshare\\sql\\migration\nMigrates all user databases except for Northwind and pubs by using backup/restore (copy-only). Backup files are stored in \\\\fileshare\\sql\\migration. If the database exists on the destination, it will \r\nbe dropped prior to attach.\nIt also includes the support databases (ReportServer, ReportServerTempDb, SSISDB, distribution).\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eCopy-DbaDatabase -Source sql2014 -Destination managedinstance.cus19c972e4513d6.database.windows.net -DestinationSqlCredential $cred -AllDatabases -BackupRestore -SharedPath \r\nhttps://someblob.blob.core.windows.net/sql\nMigrate all user databases from instance sql2014 to the specified Azure SQL Manage Instance using the blob storage account https://someblob.blob.core.windows.net/sql using a Shared Access Signature \r\n(SAS) credential with a name matching the blob storage account\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eCopy-DbaDatabase -Source sql2014 -Destination managedinstance.cus19c972e4513d6.database.windows.net -DestinationSqlCredential $cred -Database MyDb -NewName AzureDb -WithReplace -BackupRestore \r\n-SharedPath https://someblob.blob.core.windows.net/sql -AzureCredential AzBlobCredential\nMigrates Mydb from instance sql2014 to AzureDb on the specified Azure SQL Manage Instance, replacing the existing AzureDb if it exists, using the blob storage account \r\nhttps://someblob.blob.core.windows.net/sql using the Sql Server Credential AzBlobCredential\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eCopy-DbaDatabase -Source sql2014a -Destination sqlcluster -BackupRestore -SharedPath \\\\FS\\Backup -AdvancedBackupParams @{ CompressBackup = $true }\nMigrates all user databases to sqlcluster. Uses the parameter CompressBackup with the backup command to save some space on the shared path.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eCopy-DbaDatabase -Source sqlcs -Destination sqlcs -Database t -DetachAttach -NewName t_copy -Reattach\nCopies database t from sqlcs to the same server (sqlcs) using the detach/copy/attach method. The new database will be named t_copy and the original database will be reattached.", "Description": "Moves user databases from one SQL Server instance to another, supporting both on-premises and Azure SQL Managed Instance destinations. Ideal for server migrations, environment refreshes, disaster recovery testing, and cloud migrations where you need to relocate entire databases with their data and structure intact.\n\nOffers two migration methods: backup/restore (safer, supports cross-version migrations) and detach/attach (faster, requires same SQL Server version). The backup/restore method creates copy-only backups to avoid breaking your existing backup chain, while detach/attach physically moves database files via administrative shares.\n\nAutomatically handles file path mapping, preserves database properties like ownership chaining and trustworthy settings, and includes safety checks for Availability Groups, mirroring, and replication. By default, databases are placed in the destination server\u0027s default data and log directories, but you can preserve the original folder structure.\n\nWorks with named instances, clusters, SQL Server Express Edition, and Azure blob storage for cloud scenarios. Supports multiple destination servers, database renaming, and batch operations for migrating multiple databases efficiently.\n\nIf you are experiencing issues with Copy-DbaDatabase, please use Backup-DbaDatabase | Restore-DbaDatabase instead.", "Links": "https://dbatools.io/Copy-DbaDatabase", "Synopsis": "Migrates SQL Server databases between instances using backup/restore or detach/attach methods.", "Availability": "Windows, Linux, macOS", "Params": [ [ "Source", "Specifies the source SQL Server instance containing the databases to migrate.\r\nSupports named instances, clusters, and SQL Server Express editions.", "", false, "false", "", "" ], [ "SourceSqlCredential", "Specifies credentials for connecting to the source SQL Server instance when Windows authentication is not available.\r\nUse this when the source server requires SQL authentication or when running under a different security context.", "", false, "false", "", "" ], [ "Destination", "Specifies one or more destination SQL Server instances where databases will be migrated.\r\nSupports on-premises instances and Azure SQL Managed Instances for cloud migrations.\r\nWhen targeting multiple destinations, backups are performed once and shared across all targets.", "", true, "false", "", "" ], [ "DestinationSqlCredential", "Specifies credentials for connecting to the destination SQL Server instance when Windows authentication is not available.\r\nRequired for Azure SQL Managed Instance destinations or when destination requires SQL authentication.", "", false, "false", "", "" ], [ "Database", "Specifies which user databases to migrate by name.\r\nUse this when you need to migrate specific databases rather than all databases on the instance.\r\nSupports tab completion from the source instance and accepts multiple database names.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies databases to exclude when using -AllDatabases.\r\nUse this to skip problematic databases like those in use, under maintenance, or containing sensitive data.", "", false, "false", "", "" ], [ "AllDatabases", "Migrates all user databases from the source instance, excluding system databases (master, model, msdb, tempdb).\r\nUse this for full server migrations or when moving all business databases to a new instance.", "All", false, "false", "False", "" ], [ "BackupRestore", "Uses backup and restore method for database migration, creating copy-only backups to preserve existing backup chains.\r\nThis is the safest method for cross-version migrations and works with Azure blob storage.\r\nRequires either -SharedPath for backup location or -UseLastBackup to use existing backups.", "", true, "false", "False", "" ], [ "AdvancedBackupParams", "Specifies additional parameters for the backup operation as a hashtable.\r\nUse this to enable compression (@{CompressBackup = $true}), checksum verification, or other backup options.", "", false, "false", "", "" ], [ "SharedPath", "Specifies the storage location accessible by both source and destination SQL Server instances.\r\nAccepts local paths (C:\\Backups), UNC shares (\\\\server\\backups), or Azure blob storage URLs.\r\nSQL Server service accounts on both instances must have read/write permissions to this location.", "", false, "false", "", "" ], [ "AzureCredential", "Specifies the SQL Server credential name for Azure blob storage authentication.\r\nRequired when using storage access keys with Azure blob storage paths.\r\nFor SAS tokens, the credential name should match the Azure storage URL.", "", false, "false", "", "" ], [ "WithReplace", "Overwrites existing databases at the destination with the same name.\r\nUse this when refreshing existing databases or when you want to replace destination databases completely.", "", false, "false", "False", "" ], [ "NoRecovery", "Restores databases in NORECOVERY mode, leaving them ready for additional transaction log restores.\r\nUse this for staging environments or when setting up log shipping scenarios.", "", false, "false", "False", "" ], [ "NoBackupCleanup", "Preserves backup files after migration instead of automatically deleting them.\r\nUse this when you want to keep backups for additional restores or compliance requirements.", "", false, "false", "False", "" ], [ "NumberFiles", "Specifies how many backup files to create for each database backup to improve performance.\r\nDefault is 3 files, which provides good parallelism for most databases.\r\nIncrease for very large databases or high-performance storage systems.", "", false, "false", "3", "" ], [ "DetachAttach", "Uses detach/copy/attach method for database migration by moving physical database files.\r\nThis method is faster than backup/restore but requires same SQL Server versions and administrative share access.\r\nSource databases are automatically reattached if destination attachment fails.", "", true, "false", "False", "" ], [ "Reattach", "Reattaches databases to the source instance after successful detach/attach migration.\r\nRequired when using -DetachAttach with multiple destination servers to restore source functionality.", "", false, "false", "False", "" ], [ "SetSourceReadOnly", "Sets source databases to read-only before migration to prevent data changes during the process.\r\nUse this to ensure data consistency when databases must remain accessible at the source during migration.", "", false, "false", "False", "" ], [ "SetSourceOffline", "Sets source databases offline before migration to prevent any connections during the process.\r\nUse this to ensure complete isolation when databases must be completely inaccessible at the source during migration.\r\nWhen combined with -Reattach, databases are brought back online after being reattached to the source.", "", false, "false", "False", "" ], [ "ReuseSourceFolderStructure", "Maintains the exact file path structure from the source instance on the destination.\r\nUse this when destination servers have identical drive layouts or when preserving specific organizational folder structures.\r\nThe destination instance must have matching directory paths available.", "ReuseFolderStructure", false, "false", "False", "" ], [ "IncludeSupportDbs", "Migrates SQL Server feature databases including ReportServer, ReportServerTempDB, SSISDB, and distribution databases.\r\nUse this when migrating servers that host Reporting Services, Integration Services, or replication components.", "", false, "false", "False", "" ], [ "UseLastBackup", "Uses existing backups from backup history instead of creating new ones.\r\nThe most recent full, differential, and log backups must be accessible to all destination servers.\r\nUseful for migration scenarios where fresh backups already exist.", "", false, "false", "False", "" ], [ "Continue", "Continues restoration by applying transaction log backups to databases in RECOVERING or STANDBY states.\r\nUse this with -UseLastBackup when resuming interrupted restore operations or applying additional log backups.", "", false, "false", "False", "" ], [ "InputObject", "Accepts database objects piped from Get-DbaDatabase for migration.\r\nUse this to migrate databases filtered by specific criteria like size, compatibility level, or other properties.", "", false, "true (ByValue)", "", "" ], [ "NoCopyOnly", "Creates regular backups instead of copy-only backups, which affects the database\u0027s backup chain.\r\nOnly use this when you want migration backups to be part of the regular backup sequence.\r\nDefault copy-only behavior preserves existing backup chains and is recommended for migrations.", "", false, "false", "False", "" ], [ "KeepCDC", "Preserves Change Data Capture (CDC) configuration and data during migration.\r\nUse this when destination databases need to maintain CDC tracking for auditing or replication.", "", false, "false", "False", "" ], [ "KeepReplication", "Preserves replication configuration during database migration.\r\nUse this when migrating publisher or subscriber databases that participate in replication topologies.", "", false, "false", "False", "" ], [ "NewName", "Renames the database during migration when copying a single database.\r\nThe database name and physical file names are updated to use the new name.\r\nCannot be used with multiple databases or together with -Prefix parameter.", "", false, "false", "", "" ], [ "Prefix", "Adds a prefix to all migrated database names and their physical file names.\r\nUse this to distinguish migrated databases (e.g., \u0027DEV_\u0027 prefix for development copies).\r\nCannot be used together with -NewName parameter.", "", false, "false", "", "" ], [ "Force", "Forcibly overwrites existing databases at the destination and bypasses safety checks.\r\nBreaks database mirroring, removes databases from Availability Groups, and rolls back blocking transactions.\r\nUse with caution as this will permanently destroy existing destination databases.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Migration", "DataCollection" ], "CommandName": "Copy-DbaDataCollector", "Name": "Copy-DbaDataCollector", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Copy-DbaDataCollector [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-CollectionSet] \u003cObject[]\u003e] [[-ExcludeCollectionSet] \u003cObject[]\u003e] [-NoServerReconfig] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per collection set or configuration operation performed. Each object represents the result of copying a collection set or attempting to configure Data Collector settings on the \r\ndestination instance.\nProperties:\r\n- DateTime: The date and time the operation was performed (DbaDateTime type)\r\n- SourceServer: The name of the source SQL Server instance\r\n- DestinationServer: The name of the destination SQL Server instance\r\n- Name: The name of the collection set or configuration item being copied\r\n- Type: The type of object being copied (e.g., \"Collection Set\", \"Data Collection Server Config\")\r\n- Status: Result of the operation (Successful, Skipped, Failed, etc.)\r\n- Notes: Additional information about the operation, such as skip reasons or error details", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaDataCollector -Source sqlserver2014a -Destination sqlcluster\nCopies all Data Collector Objects and Configurations from sqlserver2014a to sqlcluster, using Windows credentials.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaDataCollector -Source sqlserver2014a -Destination sqlcluster -SourceSqlCredential $cred\nCopies all Data Collector Objects and Configurations from sqlserver2014a to sqlcluster, using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaDataCollector -Source sqlserver2014a -Destination sqlcluster -WhatIf\nShows what would happen if the command were executed.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eCopy-DbaDataCollector -Source sqlserver2014a -Destination sqlcluster -CollectionSet \u0027Server Activity\u0027, \u0027Table Usage Analysis\u0027\nCopies two Collection Sets, Server Activity and Table Usage Analysis, from sqlserver2014a to sqlcluster.", "Description": "Copies SQL Data Collector collection sets between SQL Server instances, allowing you to replicate performance monitoring configurations across your environment. This command scripts out the collection set definitions from the source instance and recreates them on the destination, preserving all collection items, schedules, and upload settings.\n\nBy default, all user-defined collection sets are migrated. If a collection set already exists on the destination, it will be skipped unless -Force is used to drop and recreate it. Collection sets that were running on the source will automatically be started on the destination after migration.\n\nThe -CollectionSet parameter is auto-populated for command-line completion and can be used to copy only specific collection sets. Note that Data Collector must already be configured and enabled on the destination instance before running this command.", "Links": "https://dbatools.io/Copy-DbaDataCollector", "Synopsis": "Copies SQL Data Collector collection sets from one instance to another", "Availability": "Windows only", "Params": [ [ "Source", "Source SQL Server instance containing the Data Collector collection sets to copy. Requires sysadmin access and SQL Server 2008 or higher.\r\nThe Data Collector feature must be configured on this instance for collection sets to exist.", "", true, "false", "", "" ], [ "SourceSqlCredential", "Login credentials for the source SQL Server instance. Accepts PowerShell credentials (Get-Credential).\r\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\r\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Destination", "Destination SQL Server instance(s) where collection sets will be created. Requires sysadmin access and SQL Server 2008 or higher.\r\nThe Data Collector feature must already be configured and enabled on the destination before running this command.", "", true, "false", "", "" ], [ "DestinationSqlCredential", "Login credentials for the destination SQL Server instance(s). Accepts PowerShell credentials (Get-Credential).\r\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\r\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "CollectionSet", "Specific collection set names to copy from the source instance. Supports tab completion with available collection sets.\r\nWhen omitted, all user-defined collection sets are copied (system collection sets are always excluded).", "", false, "false", "", "" ], [ "ExcludeCollectionSet", "Collection set names to exclude from the copy operation. Supports tab completion with available collection sets.\r\nUseful when you want to copy most collection sets but skip specific ones due to environment differences.", "", false, "false", "", "" ], [ "NoServerReconfig", "Reserved parameter for future Data Collector server configuration copying functionality.\r\nCurrently has no effect as server-level configuration copying is not yet implemented.", "", false, "false", "False", "" ], [ "Force", "Drops and recreates collection sets that already exist on the destination server.\r\nWithout this switch, existing collection sets are skipped to prevent accidental data loss.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "Shows what would happen if the command were to run. No actions are actually performed.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before executing any changing operations within the command.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Migration", "Assembly" ], "CommandName": "Copy-DbaDbAssembly", "Name": "Copy-DbaDbAssembly", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Copy-DbaDbAssembly [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-Assembly] \u003cObject[]\u003e] [[-ExcludeAssembly] \u003cObject[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "MigrationObject (PSCustomObject)\nReturns one object per assembly processed, documenting the copy operation result for each assembly migration attempt.\nDefault display properties (via Select-DefaultView):\r\n- DateTime: Timestamp when the operation was performed\r\n- SourceServer: Name of the source SQL Server instance\r\n- DestinationServer: Name of the destination SQL Server instance\r\n- Name: Name of the assembly being copied\r\n- Type: Always \"Database Assembly\" indicating the object type\r\n- Status: Result of the operation (Successful, Skipped, or Failed)\r\n- Notes: Additional information about why the operation was skipped or failed (null if successful)\nAdditional properties available:\r\n- SourceDatabase: Database name on the source server containing the assembly\r\n- SourceDatabaseID: Unique identifier of the source database\r\n- DestinationDatabase: Database name on the destination server\r\n- DestinationDatabaseID: Unique identifier of the destination database", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaDbAssembly -Source sqlserver2014a -Destination sqlcluster\nCopies all assemblies from sqlserver2014a to sqlcluster using Windows credentials. If assemblies with the same name exist on sqlcluster, they will be skipped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaDbAssembly -Source sqlserver2014a -Destination sqlcluster -Assembly dbname.assemblyname, dbname3.anotherassembly -SourceSqlCredential $cred -Force\nCopies two assemblies, the dbname.assemblyname and dbname3.anotherassembly from sqlserver2014a to sqlcluster using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster. If an \r\nassembly with the same name exists on sqlcluster, it will be dropped and recreated because -Force was used.\nIn this example, anotherassembly will be copied to the dbname3 database on the server sqlcluster.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaDbAssembly -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force\nShows what would happen if the command were executed using force.", "Description": "Migrates custom CLR assemblies from databases on a source SQL Server to corresponding databases on destination instances. This function scans all accessible databases for user-created assemblies and recreates them on the target servers, automatically handling security requirements like setting the TRUSTWORTHY property for external assemblies.\n\nDesigned for database migration scenarios where applications rely on custom .NET assemblies registered in SQL Server. If assemblies already exist on the destination, they\u0027re skipped unless you use -Force to drop and recreate them.\n\nThe function does not copy assembly dependencies or dependent objects like CLR stored procedures, functions, or user-defined types that reference the assemblies.", "Links": "https://dbatools.io/Copy-DbaDbAssembly", "Synopsis": "Copies CLR assemblies from source databases to destination SQL Server instances", "Availability": "Windows, Linux, macOS", "Params": [ [ "Source", "Source SQL Server instance containing the CLR assemblies to copy. Requires sysadmin access to scan all accessible databases for user-created assemblies.\r\nThe function will inventory all custom assemblies across every database on this instance for migration.", "", true, "false", "", "" ], [ "SourceSqlCredential", "Alternative credentials for connecting to the source SQL Server instance. Use this when your current Windows credentials don\u0027t have sysadmin access to the source server.\r\nAccepts PowerShell credential objects created with Get-Credential and supports SQL Server Authentication or Active Directory authentication methods.", "", false, "false", "", "" ], [ "Destination", "Target SQL Server instance(s) where CLR assemblies will be created. Accepts multiple destinations to copy assemblies to several servers simultaneously.\r\nRequires sysadmin access and corresponding databases must already exist on the destination for assembly migration to succeed.", "", true, "false", "", "" ], [ "DestinationSqlCredential", "Alternative credentials for connecting to the destination SQL Server instance(s). Use this when your current Windows credentials don\u0027t have sysadmin access to the target servers.\r\nAccepts PowerShell credential objects created with Get-Credential and supports SQL Server Authentication or Active Directory authentication methods.", "", false, "false", "", "" ], [ "Assembly", "Specific CLR assemblies to copy instead of migrating all assemblies. Use the format \u0027DatabaseName.AssemblyName\u0027 to target assemblies in specific databases.\r\nThis is useful when you only need to migrate certain assemblies rather than performing a full assembly migration across all databases.", "", false, "false", "", "" ], [ "ExcludeAssembly", "CLR assemblies to skip during the migration process. Use the format \u0027DatabaseName.AssemblyName\u0027 to exclude specific assemblies from specific databases.\r\nThis is helpful when you want to migrate most assemblies but need to skip problematic or obsolete ones that shouldn\u0027t be copied to the destination.", "", false, "false", "", "" ], [ "Force", "Drops existing assemblies on the destination before recreating them from the source. By default, assemblies that already exist are skipped.\r\nUse this when you need to overwrite destination assemblies with updated versions from the source, but be aware that assemblies with dependencies cannot be dropped.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Migration", "Certificate" ], "CommandName": "Copy-DbaDbCertificate", "Name": "Copy-DbaDbCertificate", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Copy-DbaDbCertificate [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-ExcludeDatabase] \u003cString[]\u003e] [[-Certificate] \u003cString[]\u003e] [[-ExcludeCertificate] \u003cString[]\u003e] [[-SharedPath] \u003cString\u003e] [[-MasterKeyPassword] \u003cSecureString\u003e] [[-EncryptionPassword] \u003cSecureString\u003e] [[-DecryptionPassword] \u003cSecureString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per certificate copy operation attempted, regardless of success or failure. Each object represents the result of copying a single certificate from a source database to a \r\ndestination database.\nDefault display properties (via Select-DefaultView with TypeName MigrationObject):\r\n- DateTime: The date and time when the copy operation occurred\r\n- SourceServer: The name of the source SQL Server instance\r\n- DestinationServer: The name of the destination SQL Server instance\r\n- Name: The name of the certificate being copied\r\n- Type: Always \"Database Certificate\" indicating the object type\r\n- Status: The result of the operation (Successful, Skipped, or Failed)\r\n- Notes: Additional information about the operation (reason for skipping, error details, etc.)\nAdditional properties available (not shown by default):\r\n- SourceDatabase: The name of the source database containing the certificate\r\n- SourceDatabaseID: The ID of the source database\r\n- DestinationDatabase: The name of the destination database where the certificate was restored\r\n- DestinationDatabaseID: The ID of the destination database\nAll properties from the PSCustomObject are accessible via Select-Object * even though only default properties display without explicitly using Select-Object.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaDbCertificate -Source sql01 -Destination sql02 -EncryptionPassword $cred.Password -MasterKeyPassword $cred.Password -SharedPath \\\\nas\\sql\\shared\nCopies database certificates for matching databases on sql02 and creates master keys if needed\nUses password from $cred object created by Get-Credential\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$params1 = @{\n\u003e\u003e Source = \"sql01\"\r\n\u003e\u003e Destination = \"sql02\"\r\n\u003e\u003e EncryptionPassword = $passwd\r\n\u003e\u003e MasterKeyPassword = $passwd\r\n\u003e\u003e SharedPath = \"\\\\nas\\sql\\shared\"\r\n\u003e\u003e }\r\nPS C:\\\u003e Copy-DbaDbCertificate @params1 -Confirm:$false -OutVariable results\nCopies database certificates for matching databases on sql02 and creates master keys if needed", "Description": "Transfers database certificates between SQL Server instances by backing them up from source databases and restoring them to matching databases on destination servers. This function handles the complex certificate migration process that\u0027s essential when moving databases with Transparent Data Encryption (TDE) or other certificate-based security features.\n\nThe function backs up each certificate with its private key to a shared network path accessible by both source and destination SQL Server service accounts. It automatically creates database master keys on the destination if they don\u0027t exist and you provide the MasterKeyPassword parameter. Existing certificates are skipped unless you use the Force parameter to overwrite them.\n\nThis is particularly useful for database migration projects, disaster recovery setup, and maintaining encryption consistency across environments where manual certificate management would be time-consuming and error-prone.", "Links": "https://dbatools.io/Copy-DbaDbCertificate", "Synopsis": "Copies database-level certificates from source SQL Server to destination servers, including private keys and master key dependencies.", "Availability": "Windows, Linux, macOS", "Params": [ [ "Source", "The source SQL Server instance containing the database certificates to copy. Requires sysadmin privileges to access certificate metadata and backup operations.\r\nUse this to specify where the certificates currently exist that need to be migrated to other servers.", "", true, "false", "", "" ], [ "SourceSqlCredential", "Alternative credentials for connecting to the source SQL Server instance. Use this when the current Windows user lacks sufficient privileges or when connecting with SQL authentication.\r\nEssential for cross-domain scenarios or when running under service accounts that don\u0027t have source server access.", "", false, "false", "", "" ], [ "Destination", "The destination SQL Server instance(s) where certificates will be restored. Accepts multiple servers for bulk certificate deployment.\r\nRequires sysadmin privileges to create master keys and restore certificates to matching databases.", "", true, "false", "", "" ], [ "DestinationSqlCredential", "Alternative credentials for connecting to destination SQL Server instance(s). Required when destination servers are in different domains or when using SQL authentication.\r\nMust have permissions to create database master keys and restore certificates in target databases.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to include when copying certificates. Only certificates from these databases will be migrated to matching databases on destination servers.\r\nUse this to limit certificate copying to specific databases rather than processing all databases with certificates.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific databases from certificate copying operations. Certificates in these databases will be skipped even if they exist on the source.\r\nUseful when you want to copy most database certificates but exclude system databases or specific application databases.", "", false, "false", "", "" ], [ "Certificate", "Specifies which certificates to copy by name. Only these named certificates will be processed across all included databases.\r\nUse this to migrate specific certificates like TDE certificates while leaving other database certificates untouched.", "", false, "false", "", "" ], [ "ExcludeCertificate", "Excludes specific certificates from the copying process by name. These certificates will be skipped in all databases.\r\nCommonly used to exclude system-generated certificates or certificates that should remain environment-specific.", "", false, "false", "", "" ], [ "SharedPath", "Network path where certificate backup files will be temporarily stored during the copy operation. Both source and destination SQL Server service accounts must have full access to this location.\r\nRequired because certificates cannot be directly transferred between instances and must be backed up to disk first.", "", false, "false", "", "" ], [ "MasterKeyPassword", "Password for creating database master keys on destination servers when they don\u0027t exist. Required for certificates that use master key encryption.\r\nEssential for TDE scenarios where certificates depend on database master keys for private key protection.", "", false, "false", "", "" ], [ "EncryptionPassword", "Secure password used to encrypt the private key during certificate backup operations. If not provided, a random password is generated automatically.\r\nSpecify this when you need consistent encryption passwords across multiple certificate operations or for compliance requirements.", "", false, "false", "", "" ], [ "DecryptionPassword", "Password required to decrypt the private key when restoring certificates to destination databases. Must match the password used when the certificate was originally backed up.\r\nUse this when copying certificates that were previously backed up with a specific encryption password.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Migration", "Mail" ], "CommandName": "Copy-DbaDbMail", "Name": "Copy-DbaDbMail", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Copy-DbaDbMail -Source \u003cDbaInstanceParameter\u003e [-SourceSqlCredential \u003cPSCredential\u003e] -Destination \u003cDbaInstanceParameter[]\u003e [-DestinationSqlCredential \u003cPSCredential\u003e] [-Credential \u003cPSCredential\u003e] [-ExcludePassword] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nCopy-DbaDbMail -Source \u003cDbaInstanceParameter\u003e [-SourceSqlCredential \u003cPSCredential\u003e] -Destination \u003cDbaInstanceParameter[]\u003e [-DestinationSqlCredential \u003cPSCredential\u003e] [-Credential \u003cPSCredential\u003e] [-Type \u003cString[]\u003e] [-ExcludePassword] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject (MigrationObject)\nReturns one object per Database Mail component migrated (configuration, profile, account, or mail server). Each object tracks the migration status of a single component.\nProperties:\r\n- DateTime: Timestamp when the migration operation was performed (Dataplat.Dbatools.Utility.DbaDateTime)\r\n- SourceServer: The source SQL Server instance name\r\n- DestinationServer: The destination SQL Server instance name\r\n- Name: The name of the Database Mail component being migrated (profile name, account name, server name, or \"Server Configuration\")\r\n- Type: Category of the component migrated - \"Mail Configuration\", \"Mail Profile\", \"Mail Account\", or \"Mail Server\"\r\n- Status: Migration result status - \"Successful\", \"Skipped\", or \"Failed\"\r\n- Notes: Additional details about the migration outcome (reason for skip, error message, etc.). Null if no additional notes.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaDbMail -Source sqlserver2014a -Destination sqlcluster\nCopies all database mail objects from sqlserver2014a to sqlcluster using Windows credentials. If database mail objects with the same name exist on sqlcluster, they will be skipped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaDbMail -Source sqlserver2014a -Destination sqlcluster -SourceSqlCredential $cred\nCopies all database mail objects from sqlserver2014a to sqlcluster using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaDbMail -Source sqlserver2014a -Destination sqlcluster -WhatIf\nShows what would happen if the command were executed.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eCopy-DbaDbMail -Source sqlserver2014a -Destination sqlcluster -EnableException\nPerforms execution of function, and will throw a terminating exception if something breaks", "Description": "Migrates the complete Database Mail setup from a source SQL Server to one or more destination servers. This includes mail profiles (which group accounts for specific purposes), mail accounts (SMTP configurations), mail servers (SMTP server details and credentials), and global configuration values like account retry attempts and maximum file size.\n\nDatabase Mail is commonly used for automated alerts, backup notifications, job failure reports, and maintenance notifications. This function saves significant manual configuration time when setting up new servers, standardizing mail configurations across environments, or migrating to new hardware.\n\nThe function preserves all SMTP authentication details including encrypted passwords, handles name conflicts with optional force replacement, and can enable Database Mail on the destination if it\u0027s enabled on the source. You can migrate specific component types or the entire configuration in one operation.", "Links": "https://dbatools.io/Copy-DbaDbMail", "Synopsis": "Copies Database Mail configuration including profiles, accounts, mail servers and settings between SQL Server instances.", "Availability": "Windows, Linux, macOS", "Params": [ [ "Source", "Specifies the source SQL Server instance containing the Database Mail configuration to copy. The function reads all mail profiles, accounts, mail servers, and configuration values from this instance.\r\nYou must have sysadmin privileges to access the MSDB database where Database Mail settings are stored.", "", true, "false", "", "" ], [ "SourceSqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Destination", "Specifies one or more destination SQL Server instances where the Database Mail configuration will be copied. Accepts an array to migrate to multiple servers simultaneously.\r\nYou must have sysadmin privileges on each destination to create mail profiles, accounts, and server configurations in MSDB.", "", true, "false", "", "" ], [ "DestinationSqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Credential", "Login to the target OS using alternative credentials. Accepts credential objects (Get-Credential)\nOnly used when passwords are being exported, as it requires access to the Windows OS via PowerShell remoting to decrypt the passwords.", "", false, "false", "", "" ], [ "Type", "Limits migration to specific Database Mail component types instead of copying everything. Choose \u0027ConfigurationValues\u0027 for global settings like retry attempts and file size limits, \u0027Profiles\u0027 for \r\nmail profile definitions, \u0027Accounts\u0027 for SMTP account configurations, or \u0027MailServers\u0027 for SMTP server details.\r\nUse this when you only need to sync specific components or when troubleshooting individual Database Mail layers.", "", false, "false", "", "ConfigurationValues,Profiles,Accounts,MailServers" ], [ "ExcludePassword", "Copies credential definitions without the actual password values.\r\nUse this in security-conscious environments where password decryption is restricted or when passwords should be manually reset after migration.", "", false, "false", "False", "" ], [ "Force", "Overwrites existing Database Mail objects on the destination that have matching names from the source. Without this switch, existing profiles, accounts, or mail servers are skipped to prevent \r\naccidental data loss.\r\nUse this when updating existing Database Mail configurations or when you need to replace outdated settings with current ones from the source server.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": "QueryStore", "CommandName": "Copy-DbaDbQueryStoreOption", "Name": "Copy-DbaDbQueryStoreOption", "Author": "Enrico van de Laar (@evdlaar) | Tracy Boggiano (@Tracy Boggiano)", "Syntax": "Copy-DbaDbQueryStoreOption [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-SourceDatabase] \u003cObject\u003e [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-DestinationDatabase] \u003cObject[]\u003e] [[-Exclude] \u003cObject[]\u003e] [-AllDatabases] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per destination database processed, representing the status of copying Query Store configuration to that database.\nDefault display properties (via Select-DefaultView):\r\n- DateTime: Timestamp of the operation (Dataplat.Dbatools.Utility.DbaDateTime)\r\n- SourceServer: Name of the source SQL Server instance\r\n- DestinationServer: Name of the destination SQL Server instance\r\n- Name: Name of the destination database receiving the configuration\r\n- Type: Always \"QueryStore Configuration\"\r\n- Status: Result of the operation (\"Skipped\", \"Successful\", or \"Failed\")\r\n- Notes: Error message if Status is \"Failed\", otherwise null\nAdditional properties available via Select-Object *:\r\n- SourceDatabase: Name of the source database containing the Query Store configuration to copy\r\n- SourceDatabaseID: Database ID of the source database\r\n- DestinationDatabaseID: Database ID of the destination database", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaDbQueryStoreOption -Source ServerA\\SQL -SourceDatabase AdventureWorks -Destination ServerB\\SQL -AllDatabases\nCopy the Query Store configuration of the AdventureWorks database in the ServerA\\SQL instance and apply it on all user databases in the ServerB\\SQL Instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaDbQueryStoreOption -Source ServerA\\SQL -SourceDatabase AdventureWorks -Destination ServerB\\SQL -DestinationDatabase WorldWideTraders\nCopy the Query Store configuration of the AdventureWorks database in the ServerA\\SQL instance and apply it to the WorldWideTraders database in the ServerB\\SQL Instance.", "Description": "Reads the complete Query Store configuration from a source database and applies those exact settings to specified destination databases. This lets you standardize Query Store behavior across your environment using proven configurations from production databases. The function handles version-specific settings automatically, supporting SQL Server 2016 through current versions with their respective Query Store features like wait statistics capture and custom capture policies.", "Links": "https://dbatools.io/Copy-DbaDbQueryStoreOption", "Synopsis": "Replicates Query Store configuration settings from one database to multiple target databases across instances.", "Availability": "Windows, Linux, macOS", "Params": [ [ "Source", "The SQL Server instance containing the database with Query Store configuration you want to copy from.\r\nYou must have sysadmin access and server version must be SQL Server 2016 or higher since Query Store was introduced in SQL Server 2016.", "", true, "true (ByValue)", "", "" ], [ "SourceSqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "SourceDatabase", "The database containing the Query Store configuration you want to replicate to other databases.\r\nThis database should have Query Store enabled with settings you\u0027ve tested and want to standardize across your environment.", "", true, "true (ByValue)", "", "" ], [ "Destination", "The SQL Server instance(s) where you want to apply the Query Store configuration to target databases.\r\nYou must have sysadmin access and the server must be SQL Server 2016 or higher. Supports multiple destination instances for bulk configuration deployment.", "", true, "true (ByValue)", "", "" ], [ "DestinationSqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "DestinationDatabase", "Specifies which specific databases should receive the Query Store configuration from the source database.\r\nUse this when you want to apply settings to selected databases rather than all databases on the destination instance.\r\nCannot be used together with AllDatabases parameter.", "", false, "false", "", "" ], [ "Exclude", "Databases to skip when copying Query Store configuration, useful when using AllDatabases but want to exclude specific databases.\r\nSystem databases are automatically excluded since Query Store cannot be enabled on them.\r\nCommonly used to exclude test databases or databases with special Query Store requirements.", "", false, "false", "", "" ], [ "AllDatabases", "Applies the Query Store configuration to all user databases on the destination instance.\r\nSystem databases are automatically excluded since Query Store is not supported on them.\r\nUse this for standardizing Query Store settings across an entire instance, optionally combined with Exclude parameter for exceptions.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Table", "Data" ], "CommandName": "Copy-DbaDbTableData", "Name": "Copy-DbaDbTableData", "Author": "Simone Bizzotto (@niphlod)", "Syntax": "Copy-DbaDbTableData [[-SqlInstance] \u003cDbaInstanceParameter\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Destination] \u003cDbaInstanceParameter[]\u003e] [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString\u003e] [[-DestinationDatabase] \u003cString\u003e] [[-Table] \u003cString[]\u003e] [[-View] \u003cString[]\u003e] [[-Query] \u003cString\u003e] [-ForceExplicitMapping] [-AutoCreateTable] [[-BatchSize] \u003cInt32\u003e] [[-NotifyAfter] \u003cInt32\u003e] [[-DestinationTable] \u003cString\u003e] [-NoTableLock] [-CheckConstraints] [-FireTriggers] [-KeepIdentity] [-KeepNulls] [-Truncate] [[-BulkCopyTimeout] \u003cInt32\u003e] [[-CommandTimeout] \u003cInt32\u003e] [-UseDefaultFileGroup] \r\n[[-ScriptingOptionsObject] \u003cScriptingOptions\u003e] [[-InputObject] \u003cTableViewBase[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per destination instance per source table copied. If copying one table to two destination instances, returns two objects. If piping multiple tables to one destination, returns one \r\nobject per table.\nProperties:\r\n- SourceInstance: The name of the source SQL Server instance\r\n- SourceDatabase: The name of the source database\r\n- SourceDatabaseID: The unique identifier (ID) of the source database\r\n- SourceSchema: The schema name of the source table or view\r\n- SourceTable: The name of the source table or view\r\n- DestinationInstance: The name of the destination SQL Server instance\r\n- DestinationDatabase: The name of the destination database\r\n- DestinationDatabaseID: The unique identifier (ID) of the destination database\r\n- DestinationSchema: The schema name of the destination table\r\n- DestinationTable: The name of the destination table\r\n- RowsCopied: The total number of rows that were successfully copied (Int64). Supports values greater than 2.1 billion rows.\r\n- Elapsed: The elapsed time as a TimeSpan object representing the duration of the copy operation", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaDbTableData -SqlInstance sql1 -Destination sql2 -Database dbatools_from -Table dbo.test_table\nCopies all the data from table dbo.test_table (2-part name) in database dbatools_from on sql1 to table test_table in database dbatools_from on sql2.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaDbTableData -SqlInstance sql1 -Destination sql2 -Database dbatools_from -DestinationDatabase dbatools_dest -Table [Schema].[test table]\nCopies all the data from table [Schema].[test table] (2-part name) in database dbatools_from on sql1 to table [Schema].[test table] in database dbatools_dest on sql2\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbTable -SqlInstance sql1 -Database tempdb -Table tb1, tb2 | Copy-DbaDbTableData -DestinationTable tb3\nCopies all data from tables tb1 and tb2 in tempdb on sql1 to tb3 in tempdb on sql1\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbTable -SqlInstance sql1 -Database tempdb -Table tb1, tb2 | Copy-DbaDbTableData -Destination sql2\nCopies data from tb1 and tb2 in tempdb on sql1 to the same table in tempdb on sql2\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eCopy-DbaDbTableData -SqlInstance sql1 -Destination sql2 -Database dbatools_from -Table test_table -KeepIdentity -Truncate\nCopies all the data in table test_table from sql1 to sql2, using the database dbatools_from, keeping identity columns and truncating the destination\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e$params = @{\n\u003e\u003e SqlInstance = \u0027sql1\u0027\r\n\u003e\u003e Destination = \u0027sql2\u0027\r\n\u003e\u003e Database = \u0027dbatools_from\u0027\r\n\u003e\u003e DestinationDatabase = \u0027dbatools_dest\u0027\r\n\u003e\u003e Table = \u0027[Schema].[Table]\u0027\r\n\u003e\u003e DestinationTable = \u0027[dbo].[Table.Copy]\u0027\r\n\u003e\u003e KeepIdentity = $true\r\n\u003e\u003e KeepNulls = $true\r\n\u003e\u003e Truncate = $true\r\n\u003e\u003e BatchSize = 10000\r\n\u003e\u003e }\r\n\u003e\u003e\r\nPS C:\\\u003e Copy-DbaDbTableData @params\nCopies all the data from table [Schema].[Table] (2-part name) in database dbatools_from on sql1 to table [dbo].[Table.Copy] in database dbatools_dest on sql2\r\nKeeps identity columns and Nulls, truncates the destination and processes in BatchSize of 10000.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003e$params = @{\n\u003e\u003e SqlInstance = \u0027server1\u0027\r\n\u003e\u003e Destination = \u0027server1\u0027\r\n\u003e\u003e Database = \u0027AdventureWorks2017\u0027\r\n\u003e\u003e DestinationDatabase = \u0027AdventureWorks2017\u0027\r\n\u003e\u003e DestinationTable = \u0027[AdventureWorks2017].[Person].[EmailPromotion]\u0027\r\n\u003e\u003e BatchSize = 10000\r\n\u003e\u003e Table = \u0027[OtherDb].[Person].[Person]\u0027\r\n\u003e\u003e Query = \"SELECT * FROM [OtherDb].[Person].[Person] where EmailPromotion = 1\"\r\n\u003e\u003e }\r\n\u003e\u003e\r\nPS C:\\\u003e Copy-DbaDbTableData @params\nCopies data returned from the query on server1 into the AdventureWorks2017 on server1, using a 3-part name for the DestinationTable parameter. Copy is processed in BatchSize of 10000 rows.\nSee the Query param documentation for more details.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eCopy-DbaDbTableData -SqlInstance sql1 -Database tempdb -View [tempdb].[dbo].[vw1] -DestinationTable [SampleDb].[SampleSchema].[SampleTable] -AutoCreateTable\nCopies all data from [tempdb].[dbo].[vw1] (3-part name) view on instance sql1 to an auto-created table [SampleDb].[SampleSchema].[SampleTable] on instance sql1\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003e$so = New-DbaScriptingOption\nPS C:\\\u003e $so.DriAll = $true\r\nPS C:\\\u003e $so.Indexes = $true\r\nPS C:\\\u003e $so.NoFileGroup = $true\r\nPS C:\\\u003e Copy-DbaDbTableData -SqlInstance sql1 -Destination sql2 -Database db1 -Table dbo.MyTable -AutoCreateTable -ScriptingOptionsObject $so\nCopies all data from dbo.MyTable in db1 on sql1 to an auto-created table on sql2, scripting the destination table with all constraints, indexes, and using the default filegroup.\n-------------------------- EXAMPLE 10 --------------------------\nPS C:\\\u003e$params = @{\n\u003e\u003e SqlInstance = \"SERVER001\"\r\n\u003e\u003e Database = \"MyDatabaseName\"\r\n\u003e\u003e View = \"sys.schemas\"\r\n\u003e\u003e Query = \"SELECT 0, DB_NAME(), [name] FROM sys.schemas\"\r\n\u003e\u003e Destination = \"SERVER002\"\r\n\u003e\u003e DestinationDatabase = \"MyOtherDatabaseName\"\r\n\u003e\u003e DestinationTable = \"syscollect.stage_map_schema_id\"\r\n\u003e\u003e }\r\n\u003e\u003e\r\nPS C:\\\u003e Copy-DbaDbTableData @params\nCopies schema data from sys.schemas to a table with an identity column.\r\nThe first SELECT column (0) is a placeholder for the destination\u0027s identity column.\r\nSince -KeepIdentity is not specified, the destination auto-generates identity values and ignores the placeholder.\r\nColumns are mapped by position: 0 → ID (ignored), DB_NAME() → database_name, [name] → schema_name.", "Description": "Copies data between SQL Server tables using SQL Bulk Copy for maximum performance and minimal memory usage.\nUnlike Invoke-DbaQuery and Write-DbaDbTableData which buffer entire table contents in memory, this function streams data directly from source to destination.\nThis approach prevents memory exhaustion when copying large tables and provides the fastest data transfer method available.\nSupports copying between different servers, databases, and schemas while preserving data integrity options like identity values, constraints, and triggers.\nCan automatically create destination tables based on source table structure, making it ideal for data migration, ETL processes, and table replication tasks.\n\nNote: System-versioned temporal tables require special handling. The -AutoCreateTable parameter does not support temporal table creation.\nWhen copying to an existing temporal table, use the -Query parameter to exclude GENERATED ALWAYS columns (e.g., ValidFrom, ValidTo).\nTemporal version history cannot be preserved as these values are system-managed.", "Links": "https://dbatools.io/Copy-DbaDbTableData", "Synopsis": "Streams table data between SQL Server instances using high-performance bulk copy operations.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "Source SQL Server.You must have sysadmin access and server version must be SQL Server version 2000 or greater.", "", false, "false", "", "" ], [ "SqlCredential", "Login to the source instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Destination", "Target SQL Server instance where table data will be copied to. Accepts one or more SQL Server instances.\r\nSpecify this when copying data to a different server than the source, or when doing cross-instance data transfers.", "", false, "false", "", "" ], [ "DestinationSqlCredential", "Alternative credentials for authenticating to the destination instance. Required when your current Windows credentials don\u0027t have access to the target server.\r\nUse this for cross-domain scenarios, SQL authentication, or when the destination requires different security context than the source.", "", false, "false", "", "" ], [ "Database", "Source database containing the table or view to copy data from. Required when not using pipeline input.\r\nMust exist on the source instance and your account must have read permissions on the specified objects.", "", false, "false", "", "" ], [ "DestinationDatabase", "Target database where copied data will be inserted. Defaults to the same database name as the source.\r\nUse this when copying data to a different database name on the destination instance or for cross-database copies within the same server.", "", false, "false", "", "" ], [ "Table", "Source table name to copy data from. Accepts 2-part ([schema].[table]) or 3-part ([database].[schema].[table]) names.\r\nUse square brackets for names with spaces or special characters. Cannot be used simultaneously with the View parameter.", "", false, "false", "", "" ], [ "View", "Source view name to copy data from. Accepts 2-part ([schema].[view]) or 3-part ([database].[schema].[view]) names.\r\nUse square brackets for names with spaces or special characters. Cannot be used simultaneously with the Table parameter.", "", false, "false", "", "" ], [ "Query", "Custom SQL SELECT query to use as the data source instead of copying the entire table or view. Supports 3 or 4-part object names.\r\nUse this when you need to filter rows, join multiple tables, or transform data during the copy operation. Still requires specifying a Table or View parameter for metadata purposes.\nNote: Columns are mapped by ordinal position. If the destination table has an identity column, include a placeholder value (e.g., 0) in your SELECT list at that position.\r\nThe placeholder will be ignored and the identity value auto-generated unless -KeepIdentity is specified.", "", false, "false", "", "" ], [ "ForceExplicitMapping", "When used together with Query parameter, force the use of explicit column mapping (name-based) instead of switching over to ordinal position mapping. Use with care if query contains aliases.\r\nDefault behaviour when using Query parameter is to use ordinal position mapping, due to the possibility of the query including aliases (SELECT x AS y) which could lead to column mismatching and data \r\nnot copying.\r\nThe downside of it automatically switching over to ordinal mapping is that it also tries to copy over computed columns, which will cause it to fail.", "", false, "false", "False", "" ], [ "AutoCreateTable", "Automatically creates the destination table if it doesn\u0027t exist, using the same structure as the source table.\r\nEssential for initial data migrations or when copying to new environments where destination tables haven\u0027t been created yet.\r\nAzure external source tables are created as ordinary destination tables containing only the source column names, data types, collations, and nullability.", "", false, "false", "False", "" ], [ "BatchSize", "Number of rows to process in each bulk copy batch. Defaults to 50000 rows.\r\nReduce this value for memory-constrained systems or increase it for faster transfers when copying large tables with sufficient memory.", "", false, "false", "50000", "" ], [ "NotifyAfter", "Number of rows to process before displaying progress updates. Defaults to 5000 rows.\r\nSet to a lower value for frequent updates on small tables or higher for less verbose output on large table copies.", "", false, "false", "5000", "" ], [ "DestinationTable", "Target table name where data will be inserted. Defaults to the same name as the source table.\r\nUse this when copying to a table with a different name or schema, or when specifying 3-part names for cross-database operations.", "", false, "false", "", "" ], [ "NoTableLock", "Disables the default table lock (TABLOCK) on the destination table during bulk copy operations.\r\nUse this when you need to allow concurrent read access to the destination table, though it may reduce bulk copy performance.", "", false, "false", "False", "" ], [ "CheckConstraints", "Enables constraint checking during bulk copy operations. By default, constraints are ignored for performance.\r\nUse this when data integrity validation is more important than copy speed, particularly when copying from untrusted sources.", "", false, "false", "False", "" ], [ "FireTriggers", "Enables INSERT triggers to fire during bulk copy operations. By default, triggers are bypassed for performance.\r\nUse this when you need audit trails, logging, or other trigger-based business logic to execute during the data copy.", "", false, "false", "False", "" ], [ "KeepIdentity", "Preserves the original identity column values from the source table. By default, the destination generates new identity values.\r\nEssential when copying reference tables or when you need to maintain exact ID relationships across systems.", "", false, "false", "False", "" ], [ "KeepNulls", "Preserves NULL values from the source data instead of replacing them with destination column defaults.\r\nUse this when you need exact source data reproduction, especially when NULL has specific business meaning versus default values.", "", false, "false", "False", "" ], [ "Truncate", "Removes all existing data from the destination table before copying new data. Prompts for confirmation unless -Force is used.\r\nEssential for refresh scenarios where you want to replace all destination data with current source data.", "", false, "false", "False", "" ], [ "BulkCopyTimeout", "Maximum time in seconds to wait for bulk copy operations to complete. Defaults to 5000 seconds (83 minutes).\r\nIncrease this value when copying very large tables that may take longer than the default timeout period.", "", false, "false", "5000", "" ], [ "CommandTimeout", "Maximum time in seconds to wait for the source query execution before timing out. Defaults to 0 (no timeout).\r\nSet this when querying large tables or complex views that may take longer to read than typical query timeouts allow.", "", false, "false", "0", "" ], [ "UseDefaultFileGroup", "Creates new tables using the destination database\u0027s default filegroup instead of matching the source table\u0027s filegroup name.\r\nUse this when the destination database has different filegroup configurations or when you want all copied tables in the PRIMARY filegroup.", "", false, "false", "False", "" ], [ "ScriptingOptionsObject", "A scripting options object created by New-DbaScriptingOption that controls how the destination table is scripted when -AutoCreateTable is used.\r\nUse this to control which table properties are included in the CREATE TABLE script, such as indexes, constraints, triggers, and extended properties.\r\nWhen specified, this takes precedence over -UseDefaultFileGroup. Use New-DbaScriptingOption to create the object and set the desired properties.", "", false, "false", "", "" ], [ "InputObject", "Accepts table or view objects from Get-DbaDbTable or Get-DbaDbView for pipeline operations.\r\nUse this to copy multiple tables efficiently by piping them from discovery commands.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Table", "Data" ], "CommandName": "Copy-DbaDbViewData", "Name": "Copy-DbaDbViewData", "Author": "Stephen Swan (@jaxnoth)", "Syntax": "Copy-DbaDbViewData [[-SqlInstance] \u003cDbaInstanceParameter\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Destination] \u003cDbaInstanceParameter[]\u003e] [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString\u003e] [[-DestinationDatabase] \u003cString\u003e] [[-View] \u003cString[]\u003e] [[-Query] \u003cString\u003e] [-AutoCreateTable] [[-BatchSize] \u003cInt32\u003e] [[-NotifyAfter] \u003cInt32\u003e] [[-DestinationTable] \u003cString\u003e] [-NoTableLock] [-CheckConstraints] [-FireTriggers] [-KeepIdentity] [-KeepNulls] [-Truncate] [[-BulkCopyTimeOut] \u003cInt32\u003e] [[-ScriptingOptionsObject] \u003cScriptingOptions\u003e] [[-InputObject] \u003cTableViewBase[]\u003e] [-EnableException] \r\n[-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per successful bulk copy operation, with details about the source and destination of the copied data.\nProperties:\r\n- SourceInstance: The name of the source SQL Server instance where the view data was read from\r\n- SourceDatabase: The name of the source database containing the view\r\n- SourceDatabaseID: The unique identifier of the source database\r\n- SourceSchema: The schema name of the source view (e.g., dbo)\r\n- SourceTable: The name of the source view being copied\r\n- DestinationInstance: The name of the destination SQL Server instance where data was written\r\n- DestinationDatabase: The name of the destination database where data was inserted\r\n- DestinationDatabaseID: The unique identifier of the destination database\r\n- DestinationSchema: The schema name of the destination table (e.g., dbo)\r\n- DestinationTable: The name of the destination table receiving the copied data\r\n- RowsCopied: The total number of rows successfully copied from the view to the destination table\r\n- Elapsed: The total elapsed time for the bulk copy operation (displayed as a formatted timespan, e.g., 00:01:23.456)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaDbViewData -SqlInstance sql1 -Destination sql2 -Database dbatools_from -View dbo.test_view\nCopies all the data from view dbo.test_view (2-part name) in database dbatools_from on sql1 to view test_view in database dbatools_from on sql2.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaDbViewData -SqlInstance sql1 -Destination sql2 -Database dbatools_from -DestinationDatabase dbatools_dest -DestinationTable [Schema].[test table]\nCopies all the data from view [Schema].[test view] (2-part name) in database dbatools_from on sql1 to table [Schema].[test table] in database dbatools_dest on sql2\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbView -SqlInstance sql1 -Database tempdb -View vw1, vw2 | Copy-DbaDbViewData -DestinationTable tb3\nCopies all data from Views vw1 and vw2 in tempdb on sql1 to tb3 in tempdb on sql1\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbView -SqlInstance sql1 -Database tempdb -View vw1, vw2 | Copy-DbaDbViewData -Destination sql2\nCopies data from tbl1 in tempdb on sql1 to tbl1 in tempdb on sql2\r\nthen\r\nCopies data from tbl2 in tempdb on sql1 to tbl2 in tempdb on sql2\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eCopy-DbaDbViewData -SqlInstance sql1 -Destination sql2 -Database dbatools_from -View test_view -KeepIdentity -Truncate\nCopies all the data in view test_view from sql1 to sql2, using the database dbatools_from, keeping identity columns and truncating the destination\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e$params = @{\n\u003e\u003e SqlInstance = \u0027sql1\u0027\r\n\u003e\u003e Destination = \u0027sql2\u0027\r\n\u003e\u003e Database = \u0027dbatools_from\u0027\r\n\u003e\u003e DestinationDatabase = \u0027dbatools_dest\u0027\r\n\u003e\u003e View = \u0027[Schema].[View]\u0027\r\n\u003e\u003e DestinationTable = \u0027[dbo].[View.Copy]\u0027\r\n\u003e\u003e KeepIdentity = $true\r\n\u003e\u003e KeepNulls = $true\r\n\u003e\u003e Truncate = $true\r\n\u003e\u003e BatchSize = 10000\r\n\u003e\u003e }\r\n\u003e\u003e\r\nPS C:\\\u003e Copy-DbaDbViewData @params\nCopies all the data from view [Schema].[View] in database dbatools_from on sql1 to table [dbo].[Table.Copy] in database dbatools_dest on sql2\r\nKeeps identity columns and Nulls, truncates the destination and processes in BatchSize of 10000.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003e$params = @{\n\u003e\u003e SqlInstance = \u0027server1\u0027\r\n\u003e\u003e Destination = \u0027server1\u0027\r\n\u003e\u003e Database = \u0027AdventureWorks2017\u0027\r\n\u003e\u003e DestinationDatabase = \u0027AdventureWorks2017\u0027\r\n\u003e\u003e View = \u0027[AdventureWorks2017].[Person].[EmailPromotion]\u0027\r\n\u003e\u003e BatchSize = 10000\r\n\u003e\u003e Query = \"SELECT * FROM [OtherDb].[Person].[Person] where EmailPromotion = 1\"\r\n\u003e\u003e }\r\n\u003e\u003e\r\nPS C:\\\u003e Copy-DbaDbViewData @params\nCopies data returned from the query on server1 into the AdventureWorks2017 on server1.\r\nThis query uses a 3-part name to reference the object in the query value, it will try to find the view named \"Person\" in the schema \"Person\" and database \"OtherDb\".\r\nCopy is processed in BatchSize of 10000 rows. See the -Query param documentation for more details.", "Description": "Extracts data from SQL Server views and bulk copies it to destination tables, either on the same instance or across different servers.\nUses SqlBulkCopy for optimal performance when migrating view data, materializing view results, or creating data snapshots from complex views.\nSupports custom queries against views, identity preservation, constraint checking, and automatic destination table creation.\nHandles large datasets efficiently with configurable batch sizes and minimal resource overhead compared to traditional INSERT statements.", "Links": "https://dbatools.io/Copy-DbaDbViewData", "Synopsis": "Copies data from SQL Server views to destination tables using high-performance bulk copy operations.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "Source SQL Server.You must have sysadmin access and server version must be SQL Server version 2000 or greater.", "", false, "false", "", "" ], [ "SqlCredential", "Login to the source instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Destination", "Target SQL Server instance where view data will be copied to. Accepts one or more SQL Server instances.\r\nSpecify this when copying view data to a different server than the source, or when doing cross-instance data transfers.", "", false, "false", "", "" ], [ "DestinationSqlCredential", "Alternative credentials for authenticating to the destination instance. Required when your current Windows credentials don\u0027t have access to the target server.\r\nUse this for cross-domain scenarios, SQL authentication, or when the destination requires different security context than the source.", "", false, "false", "", "" ], [ "Database", "Source database containing the view to copy data from. Required when not using pipeline input.\r\nMust exist on the source instance and your account must have read permissions on the specified view.", "", false, "false", "", "" ], [ "DestinationDatabase", "Target database where copied view data will be inserted. Defaults to the same database name as the source.\r\nUse this when copying data to a different database name on the destination instance or for cross-database copies within the same server.", "", false, "false", "", "" ], [ "View", "Source view name to copy data from. Accepts 2-part ([schema].[view]) or 3-part ([database].[schema].[view]) names.\r\nUse square brackets for names with spaces or special characters. Required to specify which view\u0027s data to extract and copy.", "", false, "false", "", "" ], [ "Query", "Custom SQL SELECT query to use as the data source instead of copying the entire view. Supports 3 or 4-part object names.\r\nUse this when you need to filter rows, join the view with other tables, or transform data during the copy operation. Still requires specifying a View parameter for metadata purposes.", "", false, "false", "", "" ], [ "AutoCreateTable", "Automatically creates the destination table if it doesn\u0027t exist, using the same structure as the source view.\r\nEssential for initial data migrations or when materializing view data into new tables where destination tables haven\u0027t been created yet.", "", false, "false", "False", "" ], [ "BatchSize", "Number of rows to process in each bulk copy batch. Defaults to 50000 rows.\r\nReduce this value for memory-constrained systems or increase it for faster transfers when copying large view result sets with sufficient memory.", "", false, "false", "50000", "" ], [ "NotifyAfter", "Number of rows to process before displaying progress updates. Defaults to 5000 rows.\r\nSet to a lower value for frequent updates on small view datasets or higher for less verbose output on large view copies.", "", false, "false", "5000", "" ], [ "DestinationTable", "Target table name where view data will be inserted. Defaults to the same name as the source view.\r\nUse this when copying to a table with a different name or schema, or when materializing view data into a permanent table structure.", "", false, "false", "", "" ], [ "NoTableLock", "Disables the default table lock (TABLOCK) on the destination table during bulk copy operations.\r\nUse this when you need to allow concurrent read access to the destination table, though it may reduce bulk copy performance.", "", false, "false", "False", "" ], [ "CheckConstraints", "Enables constraint checking during bulk copy operations. By default, constraints are ignored for performance.\r\nUse this when data integrity validation is more important than copy speed, particularly when copying view data to tables with strict business rules.", "", false, "false", "False", "" ], [ "FireTriggers", "Enables INSERT triggers to fire during bulk copy operations. By default, triggers are bypassed for performance.\r\nUse this when you need audit trails, logging, or other trigger-based business logic to execute during the view data copy.", "", false, "false", "False", "" ], [ "KeepIdentity", "Preserves the original identity column values from the source view. By default, the destination generates new identity values.\r\nEssential when copying view data that includes identity columns and you need to maintain exact ID relationships in the destination table.", "", false, "false", "False", "" ], [ "KeepNulls", "Preserves NULL values from the source view data instead of replacing them with destination column defaults.\r\nUse this when you need exact source data reproduction from the view, especially when NULL has specific business meaning versus default values.", "", false, "false", "False", "" ], [ "Truncate", "Removes all existing data from the destination table before copying new view data. Prompts for confirmation unless -Force is used.\r\nEssential for refresh scenarios where you want to replace all destination data with current view data.", "", false, "false", "False", "" ], [ "BulkCopyTimeOut", "Maximum time in seconds to wait for bulk copy operations to complete. Defaults to 5000 seconds (83 minutes).\r\nIncrease this value when copying very large view result sets that may take longer than the default timeout period.", "", false, "false", "5000", "" ], [ "ScriptingOptionsObject", "A scripting options object created by New-DbaScriptingOption that controls how the destination table is scripted when -AutoCreateTable is used.\r\nUse this to control which table properties are included in the CREATE TABLE script, such as indexes, constraints, triggers, and extended properties.", "", false, "false", "", "" ], [ "InputObject", "Accepts view objects from Get-DbaDbView for pipeline operations.\r\nUse this to copy data from multiple views by piping them from Get-DbaDbView, allowing batch processing of view data copies.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Migration", "Endpoint" ], "CommandName": "Copy-DbaEndpoint", "Name": "Copy-DbaEndpoint", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Copy-DbaEndpoint [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-Endpoint] \u003cObject[]\u003e] [[-ExcludeEndpoint] \u003cObject[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per endpoint copy operation with migration status information.\nDefault display properties (via Select-DefaultView):\r\n- DateTime: The date and time when the endpoint operation was performed\r\n- SourceServer: The name of the source SQL Server instance\r\n- DestinationServer: The name of the destination SQL Server instance\r\n- Name: The name of the endpoint being copied\r\n- Type: The type of object (always \"Endpoint\" for this command)\r\n- Status: The result of the operation (Successful, Skipped, or Failed)\r\n- Notes: Additional details about the operation result (e.g., reason for skipping or error message)\nAll properties are accessible using Select-Object * for advanced scripting scenarios.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaEndpoint -Source sqlserver2014a -Destination sqlcluster\nCopies all server endpoints from sqlserver2014a to sqlcluster, using Windows credentials. If endpoints with the same name exist on sqlcluster, they will be skipped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaEndpoint -Source sqlserver2014a -SourceSqlCredential $cred -Destination sqlcluster -Endpoint tg_noDbDrop -Force\nCopies only the tg_noDbDrop endpoint from sqlserver2014a to sqlcluster using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster. If an endpoint with the same name exists on \r\nsqlcluster, it will be dropped and recreated because -Force was used.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaEndpoint -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force\nShows what would happen if the command were executed using force.", "Description": "Migrates user-defined endpoints (excluding system endpoints) from a source SQL Server to one or more destination servers. This includes Service Broker, Database Mirroring, and Availability Group endpoints that are essential for high availability configurations.\n\nExisting endpoints on the destination are skipped by default to prevent conflicts, but can be overwritten using the -Force parameter. The function scripts the complete endpoint definition from the source and recreates it on each destination server.", "Links": "https://dbatools.io/Copy-DbaEndpoint", "Synopsis": "Copies SQL Server endpoints from source instance to destination instances for migration scenarios.", "Availability": "Windows, Linux, macOS", "Params": [ [ "Source", "Specifies the source SQL Server instance containing endpoints to copy. Must have sysadmin access to enumerate and script endpoint definitions.\r\nUse this to identify the server containing Service Broker, Database Mirroring, or Availability Group endpoints needed on other instances.", "", true, "false", "", "" ], [ "SourceSqlCredential", "Specifies alternative credentials for connecting to the source SQL Server instance. Required when Windows Authentication is not available or sufficient.\r\nUse this when the source server requires SQL authentication or when running under a service account that lacks access to the source instance.", "", false, "false", "", "" ], [ "Destination", "Specifies one or more destination SQL Server instances where endpoints will be created. Must have sysadmin access to create endpoint objects.\r\nUse this to deploy endpoints across multiple servers in Always On configurations or Service Broker scenarios requiring identical endpoint definitions.", "", true, "false", "", "" ], [ "DestinationSqlCredential", "Specifies alternative credentials for connecting to destination SQL Server instances. Applied to all destination servers when Windows Authentication is insufficient.\r\nUse this when destination servers require SQL authentication or when deploying endpoints across environments with different security contexts.", "", false, "false", "", "" ], [ "Endpoint", "Specifies which endpoints to copy from the source instance. Accepts endpoint names and supports wildcards for pattern matching.\r\nUse this when you need to migrate specific endpoints like Database Mirroring or Service Broker endpoints rather than copying all user-defined endpoints.", "", false, "false", "", "" ], [ "ExcludeEndpoint", "Specifies which endpoints to skip during the copy operation. Takes precedence over the Endpoint parameter when both are specified.\r\nUse this to exclude problematic or environment-specific endpoints while copying most other endpoints from the source instance.", "", false, "false", "", "" ], [ "Force", "Drops and recreates existing endpoints on destination instances when name conflicts occur. By default, existing endpoints are skipped to prevent disruption.\r\nUse this when updating endpoint configurations or when you need to overwrite outdated endpoint definitions on destination servers.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Migration", "ExtendedStoredProcedure", "XP" ], "CommandName": "Copy-DbaExtendedStoredProcedure", "Name": "Copy-DbaExtendedStoredProcedure", "Author": "the dbatools team + Claude", "Syntax": "Copy-DbaExtendedStoredProcedure [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-ExtendedProcedure] \u003cString[]\u003e] [[-ExcludeExtendedProcedure] \u003cString[]\u003e] [[-DestinationPath] \u003cString\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject (MigrationObject)\nReturns one object per Extended Stored Procedure processed. The object contains information about the success or failure of the copy operation.\nProperties:\r\n- DateTime: The date and time when the copy operation was processed (DbaDateTime)\r\n- SourceServer: The name of the source SQL Server instance (string)\r\n- DestinationServer: The name of the destination SQL Server instance (string)\r\n- Name: The name of the Extended Stored Procedure (string)\r\n- Type: Always \"Extended Stored Procedure\" (string)\r\n- Status: The result of the operation - Successful, Skipped, Failed, or \"Successful (DLL not copied)\" (string)\r\n- Notes: Additional information about the operation result, such as reason for skip, error message, or DLL copy status (string)\r\n- Schema: The schema in which the Extended Stored Procedure was created (string)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaExtendedStoredProcedure -Source sqlserver2014a -Destination sqlcluster\nCopies all custom Extended Stored Procedures from sqlserver2014a to sqlcluster using Windows credentials. If procedures with the same name exist on sqlcluster, they will be skipped. Attempts to copy \r\nassociated DLL files.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaExtendedStoredProcedure -Source sqlserver2014a -SourceSqlCredential $scred -Destination sqlcluster -DestinationSqlCredential $dcred -ExtendedProcedure xp_custom_proc -Force\nCopies only the Extended Stored Procedure xp_custom_proc from sqlserver2014a to sqlcluster using SQL credentials. If the procedure already exists on sqlcluster, it will be updated because -Force was \r\nused.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaExtendedStoredProcedure -Source sqlserver2014a -Destination sqlcluster -ExcludeExtendedProcedure xp_old_proc -Force\nCopies all custom Extended Stored Procedures found on sqlserver2014a except xp_old_proc to sqlcluster. If procedures with the same name exist on sqlcluster, they will be updated because -Force was \r\nused.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eCopy-DbaExtendedStoredProcedure -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force\nShows what would happen if the command were executed using force.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eCopy-DbaExtendedStoredProcedure -Source sqlserver2014a -Destination sqlcluster -DestinationPath \"C:\\CustomPath\"\nCopies all custom Extended Stored Procedures and attempts to copy DLL files to C:\\CustomPath on the destination server instead of the default Binn directory.", "Description": "Migrates custom Extended Stored Procedures from the source server to one or more destination servers. Extended Stored Procedures are DLL-based procedures that extend SQL Server functionality by calling external code, commonly used for custom server operations, legacy integrations, or specialized processing tasks.\n\nThis function identifies custom Extended Stored Procedures (excludes system XPs), copies their definitions to the destination, and attempts to copy the associated DLL files to the destination server\u0027s Binn directory. Due to OS and .NET version differences, DLLs may require recompilation when migrating between different Windows versions or SQL Server versions.\n\nBy default, all custom Extended Stored Procedures are copied. Use -ExtendedProcedure to copy specific procedures or -ExcludeExtendedProcedure to skip certain ones. Existing procedures on the destination are skipped unless -Force is used to overwrite them.\n\nWARNING: DLL files may not be compatible between different OS versions (e.g., Windows Server 2012 R2 to Windows Server 2019) due to .NET framework differences. The function will attempt to copy DLL files but will warn if the copy fails, allowing for manual intervention.", "Links": "https://dbatools.io/Copy-DbaExtendedStoredProcedure", "Synopsis": "Copies custom Extended Stored Procedures (XPs) and their associated DLL files between SQL Server instances", "Availability": "Windows, Linux, macOS", "Params": [ [ "Source", "The source SQL Server instance containing Extended Stored Procedures to copy. Requires sysadmin access to read procedure definitions and access to DLL files in the Binn directory.\r\nUse this to specify which server has the Extended Stored Procedures you want to migrate or standardize across your environment.", "", true, "false", "", "" ], [ "SourceSqlCredential", "Credentials for connecting to the source SQL Server instance when Windows authentication is not available or desired.\r\nUse this when you need to connect with specific SQL login credentials or when running under a service account that lacks access to the source server.", "", false, "false", "", "" ], [ "Destination", "The destination SQL Server instance(s) where Extended Stored Procedures will be copied. Requires sysadmin access to create procedures and file system access to copy DLL files.\r\nAccepts multiple destinations to deploy Extended Stored Procedures across several servers simultaneously for standardization.", "", true, "false", "", "" ], [ "DestinationSqlCredential", "Credentials for connecting to the destination SQL Server instance(s) when Windows authentication is not available or desired.\r\nUse this when deploying to servers that require different authentication credentials or when your current context lacks destination access.", "", false, "false", "", "" ], [ "ExtendedProcedure", "Specifies which Extended Stored Procedures to copy from the source server instead of copying all available custom XPs.\r\nUse this when you only need specific procedures migrated, such as copying just certain legacy integrations while leaving others behind.", "", false, "false", "", "" ], [ "ExcludeExtendedProcedure", "Specifies which Extended Stored Procedures to skip during the copy operation while processing all others from the source.\r\nUse this when most Extended Stored Procedures should be copied but specific ones need to remain server-specific or are problematic.", "", false, "false", "", "" ], [ "DestinationPath", "Specifies the destination path where DLL files should be copied. By default, uses the destination SQL Server\u0027s Binn directory.\r\nUse this when you need to copy DLLs to a non-standard location or when the destination Binn directory is not accessible.", "", false, "false", "", "" ], [ "Force", "Overwrites existing Extended Stored Procedures on the destination server instead of skipping them when name conflicts occur.\r\nUse this when updating existing procedures with newer versions or when you need to ensure destination procedures match the source exactly.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": "Migration", "CommandName": "Copy-DbaInstanceAudit", "Name": "Copy-DbaInstanceAudit", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Copy-DbaInstanceAudit [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-Audit] \u003cObject[]\u003e] [[-ExcludeAudit] \u003cObject[]\u003e] [[-Path] \u003cString\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per audit copied or encountered (regardless of success or failure status). The object represents the result of the copy operation for a single audit.\nDefault display properties (via Select-DefaultView):\r\n- DateTime: The timestamp when the copy operation was attempted\r\n- SourceServer: The name of the source SQL Server instance\r\n- DestinationServer: The name of the destination SQL Server instance\r\n- Name: The name of the server audit being copied\r\n- Type: Always \"Server Audit\" indicating the type of object being copied\r\n- Status: The result status of the copy operation (Successful, Skipped, or Failed)\r\n- Notes: Additional information about the copy operation (reason for skip, error details, etc.)\nThe object type is set to \"MigrationObject\" for proper display formatting. All properties are always available using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaInstanceAudit -Source sqlserver2014a -Destination sqlcluster\nCopies all server audits from sqlserver2014a to sqlcluster, using Windows credentials. If audits with the same name exist on sqlcluster, they will be skipped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaInstanceAudit -Source sqlserver2014a -Destination sqlcluster -Audit tg_noDbDrop -SourceSqlCredential $cred -Force\nCopies a single audit, the tg_noDbDrop audit from sqlserver2014a to sqlcluster, using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster. If an audit with the same name exists \r\non sqlcluster, it will be dropped and recreated because -Force was used.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaInstanceAudit -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force\nShows what would happen if the command were executed using force.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eCopy-DbaInstanceAudit -Source sqlserver-0 -Destination sqlserver-1 -Audit audit1 -Path \u0027C:\\audit1\u0027\nCopies audit audit1 from sqlserver-0 to sqlserver-1. The file path on sqlserver-1 will be set to \u0027C:\\audit1\u0027.", "Description": "Migrates SQL Server audit objects and their configurations from one instance to another, preserving audit settings and file paths. This function handles the complex task of recreating audit definitions on destination servers, making it essential for server migrations, disaster recovery scenarios, or standardizing auditing policies across multiple SQL Server instances. By default, all audits are copied, but you can specify individual audits to migrate. If an audit already exists on the destination, it will be skipped unless -Force is used to drop and recreate it.", "Links": "https://dbatools.io/Copy-DbaInstanceAudit", "Synopsis": "Copies SQL Server audit objects from source to destination instances", "Availability": "Windows, Linux, macOS", "Params": [ [ "Source", "Source SQL Server instance containing the audit objects to copy. Requires sysadmin access to read audit configurations and their associated file paths.\r\nMust be SQL Server 2008 or higher since server audits were introduced in SQL Server 2008.", "", true, "false", "", "" ], [ "SourceSqlCredential", "Login credentials for the source SQL Server instance. Use this when the current Windows user doesn\u0027t have sysadmin access to read audit objects.\r\nMust have sysadmin privileges since audit configurations require elevated permissions to access.\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Destination", "Destination SQL Server instance where audit objects will be created. Requires sysadmin access to create audits and potentially create audit file directories.\r\nMust be SQL Server 2008 or higher since server audits were introduced in SQL Server 2008.", "", true, "false", "", "" ], [ "DestinationSqlCredential", "Login credentials for the destination SQL Server instance. Use this when the current Windows user doesn\u0027t have sysadmin access to create audit objects.\r\nMust have sysadmin privileges since creating audits and directories requires elevated permissions.\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Audit", "Specifies which server audits to copy by name. Use this when you only need to migrate specific audits rather than all audits on the server.\r\nSupports tab completion with audit names from the source server. If not specified, all audits will be copied.", "", false, "false", "", "" ], [ "ExcludeAudit", "Specifies server audits to skip during the copy operation. Use this when you want to copy most audits but exclude specific ones that shouldn\u0027t be migrated.\r\nSupports tab completion with audit names from the source server. Cannot be used with the -Audit parameter.", "", false, "false", "", "" ], [ "Path", "Specifies the directory path where audit files will be created on the destination server. Use this when the original audit file path from the source doesn\u0027t exist on the destination.\r\nIf not specified, the function attempts to use the source audit\u0027s original file path, or falls back to the default data directory if the path doesn\u0027t exist.", "", false, "false", "", "" ], [ "Force", "Drops and recreates audits that already exist on the destination server. Also creates missing audit file directories if they don\u0027t exist.\r\nWithout this switch, existing audits are skipped and missing directories cause the operation to fail.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Migration", "ServerAudit", "AuditSpecification" ], "CommandName": "Copy-DbaInstanceAuditSpecification", "Name": "Copy-DbaInstanceAuditSpecification", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Copy-DbaInstanceAuditSpecification [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-AuditSpecification] \u003cObject[]\u003e] [[-ExcludeAuditSpecification] \u003cObject[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "MigrationObject\nReturns one object per audit specification processed, with the results of the copy operation for each specification.\nProperties:\r\n- DateTime: Timestamp when the copy operation was executed (DbaDateTime)\r\n- SourceServer: Name of the source SQL Server instance\r\n- DestinationServer: Name of the destination SQL Server instance\r\n- Name: Name of the audit specification that was copied or processed\r\n- Type: Always returns \"Server Audit Specification\"\r\n- Status: Result of the operation - \"Successful\", \"Skipped\", or \"Failed\"\r\n- Notes: Additional details about the operation result (e.g., why it was skipped or failure reason)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaInstanceAuditSpecification -Source sqlserver2014a -Destination sqlcluster\nCopies all server audits from sqlserver2014a to sqlcluster using Windows credentials to connect. If audits with the same name exist on sqlcluster, they will be skipped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaInstanceAuditSpecification -Source sqlserver2014a -Destination sqlcluster -AuditSpecification tg_noDbDrop -SourceSqlCredential $cred -Force\nCopies a single audit, the tg_noDbDrop audit from sqlserver2014a to sqlcluster using SQL credentials to connect to sqlserver2014a and Windows credentials to connect to sqlcluster. If an audit \r\nspecification with the same name exists on sqlcluster, it will be dropped and recreated because -Force was used.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaInstanceAuditSpecification -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force\nShows what would happen if the command were executed using force.", "Description": "Migrates server audit specifications between SQL Server instances, allowing DBAs to standardize audit configurations across environments or restore audit settings during disaster recovery. The function scripts existing audit specifications from the source server and recreates them on the destination, but only if the corresponding server audits already exist on the target instance.\n\nBy default, all audit specifications are copied, but you can target specific ones using the -AuditSpecification parameter. Existing specifications on the destination are skipped unless -Force is used to drop and recreate them. This prevents accidental overwrites while enabling intentional updates to audit configurations.", "Links": "https://dbatools.io/Copy-DbaInstanceAuditSpecification", "Synopsis": "Copies server audit specifications from one SQL Server instance to another for compliance standardization.", "Availability": "Windows, Linux, macOS", "Params": [ [ "Source", "Source SQL Server instance containing the server audit specifications to copy. Requires sysadmin access and SQL Server 2008 or higher.\r\nThe function will read all existing audit specifications from this instance to migrate to the destination.", "", true, "false", "", "" ], [ "SourceSqlCredential", "Credentials for connecting to the source SQL Server instance to read audit specifications. Use when Windows Authentication is not available.\r\nAccepts PowerShell credentials (Get-Credential) and supports SQL Server Authentication, Active Directory authentication modes.\r\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Destination", "Destination SQL Server instance where audit specifications will be created. Requires sysadmin access and SQL Server 2008 or higher.\r\nThe corresponding server audits must already exist on this instance before audit specifications can be successfully copied.", "", true, "false", "", "" ], [ "DestinationSqlCredential", "Credentials for connecting to the destination SQL Server instance to create audit specifications. Use when Windows Authentication is not available.\r\nAccepts PowerShell credentials (Get-Credential) and supports SQL Server Authentication, Active Directory authentication modes.\r\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "AuditSpecification", "Specifies which server audit specifications to copy by name. Accepts multiple specification names as an array.\r\nUse this when you need to migrate specific audit specifications rather than all specifications from the source instance.\r\nIf not specified, all audit specifications from the source will be processed.", "", false, "false", "", "" ], [ "ExcludeAuditSpecification", "Specifies which server audit specifications to skip during the copy operation. Accepts multiple specification names as an array.\r\nUse this to copy all audit specifications except those you want to exclude, such as environment-specific or test specifications.", "", false, "false", "", "" ], [ "Force", "Drops and recreates existing audit specifications on the destination instance instead of skipping them.\r\nUse this when you need to overwrite existing audit specifications with updated configurations from the source.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": "Migration", "CommandName": "Copy-DbaInstanceTrigger", "Name": "Copy-DbaInstanceTrigger", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Copy-DbaInstanceTrigger [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-ServerTrigger] \u003cObject[]\u003e] [[-ExcludeServerTrigger] \u003cObject[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject (MigrationObject)\nReturns one object per server trigger processed, showing the status of each trigger copy operation.\nProperties:\r\n- SourceServer: The name of the source SQL Server instance where the trigger was copied from\r\n- DestinationServer: The name of the destination SQL Server instance where the trigger was copied to\r\n- Name: The name of the server trigger\r\n- Type: Always \"Server Trigger\"\r\n- Status: The result of the copy operation (Successful, Skipped, or Failed)\r\n- Notes: Additional details about the operation (e.g., \"Already exists on destination\", error message if failed)\r\n- DateTime: The date and time when the copy operation was processed", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaInstanceTrigger -Source sqlserver2014a -Destination sqlcluster\nCopies all server triggers from sqlserver2014a to sqlcluster, using Windows credentials. If triggers with the same name exist on sqlcluster, they will be skipped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaInstanceTrigger -Source sqlserver2014a -Destination sqlcluster -ServerTrigger tg_noDbDrop -SourceSqlCredential $cred -Force\nCopies a single trigger, the tg_noDbDrop trigger from sqlserver2014a to sqlcluster, using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster. If a trigger with the same name \r\nexists on sqlcluster, it will be dropped and recreated because -Force was used.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaInstanceTrigger -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force\nShows what would happen if the command were executed using force.", "Description": "Migrates server-level triggers from a source SQL Server instance to one or more destination instances. This is essential during server migrations, disaster recovery setup, or when standardizing security and audit triggers across your environment.\n\nServer triggers fire in response to server-level events like logons, DDL changes, or server startup. This function scripts out the complete trigger definition from the source and recreates it on the destination, maintaining all trigger properties and logic.\n\nBy default, all server triggers are copied, but you can specify particular triggers with -ServerTrigger or exclude specific ones with -ExcludeServerTrigger. Existing triggers on the destination are skipped unless -Force is used to drop and recreate them.", "Links": "https://dbatools.io/Copy-DbaInstanceTrigger", "Synopsis": "Copies server-level triggers between SQL Server instances for migration or standardization", "Availability": "Windows, Linux, macOS", "Params": [ [ "Source", "Source SQL Server instance containing the server triggers to copy. Must be SQL Server 2005 or later.\r\nRequires sysadmin privileges to access server-level triggers and their definitions.", "", true, "false", "", "" ], [ "SourceSqlCredential", "Credentials for connecting to the source SQL Server instance when Windows Authentication is not available.\r\nUse this when copying triggers from instances in different domains or when using SQL Server authentication.", "", false, "false", "", "" ], [ "Destination", "Destination SQL Server instance(s) where server triggers will be created. Must be SQL Server 2005 or later.\r\nRequires sysadmin privileges to create server-level triggers and cannot be a lower version than the source.", "", true, "false", "", "" ], [ "DestinationSqlCredential", "Credentials for connecting to the destination SQL Server instance(s) when Windows Authentication is not available.\r\nUse this when copying triggers to instances in different domains or when using SQL Server authentication.", "", false, "false", "", "" ], [ "ServerTrigger", "Specific server trigger name(s) to copy from the source instance. Tab completion shows available triggers.\r\nUse this when you need to copy only specific triggers instead of all server triggers.", "", false, "false", "", "" ], [ "ExcludeServerTrigger", "Server trigger name(s) to skip during the copy operation. Tab completion shows available triggers.\r\nUse this when copying most triggers but need to exclude specific ones due to environment differences.", "", false, "false", "", "" ], [ "Force", "Drops and recreates server triggers that already exist on the destination instance.\r\nWithout this switch, existing triggers are skipped to prevent accidental overwrites.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "Shows what would happen if the command were to run. No actions are actually performed.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before executing any changing operations within the command.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "WSMan", "Migration", "LinkedServer" ], "CommandName": "Copy-DbaLinkedServer", "Name": "Copy-DbaLinkedServer", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Copy-DbaLinkedServer [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [[-LinkedServer] \u003cObject[]\u003e] [[-ExcludeLinkedServer] \u003cObject[]\u003e] [-UpgradeSqlClient] [-ExcludePassword] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per linked server processed. The object contains migration status information for each linked server and its logins that were copied from source to destination.\nDefault display properties (via Select-DefaultView):\r\n- DateTime: Timestamp when the linked server was processed (DbaDateTime object)\r\n- SourceServer: Name of the source SQL Server instance\r\n- DestinationServer: Name of the destination SQL Server instance\r\n- Name: Name of the linked server being migrated\r\n- Type: Initially \"Linked Server\", then set to the remote login identity being configured\r\n- Status: Status of the operation (Successful, Skipped, or Failed)\r\n- Notes: Provider name, or reason for skip/failure (e.g., \"Missing provider\", \"Already exists on destination\", or error message)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaLinkedServer -Source sqlserver2014a -Destination sqlcluster\nCopies all SQL Server Linked Servers on sqlserver2014a to sqlcluster. If Linked Server exists on destination, it will be skipped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaLinkedServer -Source sqlserver2014a -Destination sqlcluster -LinkedServer SQL2K5,SQL2k -Force\nCopies over two SQL Server Linked Servers (SQL2K and SQL2K2) from sqlserver to sqlcluster. If the credential already exists on the destination, it will be dropped.", "Description": "Migrates SQL Server linked servers including all authentication credentials and connection settings from a source instance to one or more destination instances. The function preserves usernames and passwords by using password decryption techniques, eliminating the need to manually recreate linked server configurations and re-enter sensitive credentials.\n\nThis is particularly useful during server migrations, disaster recovery scenarios, or when consolidating environments where maintaining external data connections is critical. The function handles various provider types and can optionally upgrade older SQL Client providers to current versions during migration.\n\nWhen upgrading from older versions to SQL Server 2025+, MSOLEDBSQL is changed to MSOLEDBSQL19 and provider string for encrypt and trustservercertificate settings is added if not already included to ensure compatibility with the breaking changes in the new driver.\n\nCredit: Password decryption techniques provided by Antti Rantasaari (NetSPI, 2014) - https://blog.netspi.com/decrypting-mssql-database-link-server-passwords/", "Links": "https://dbatools.io/Copy-DbaLinkedServer", "Synopsis": "Migrates linked servers and their authentication credentials from one SQL Server instance to another", "Availability": "Windows only", "Params": [ [ "Source", "Source SQL Server (2005 and above). You must have sysadmin access to both SQL Server and Windows.", "", true, "false", "", "" ], [ "SourceSqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Destination", "Destination SQL Server (2005 and above). You must have sysadmin access to both SQL Server and Windows.", "", true, "false", "", "" ], [ "DestinationSqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Credential", "Login to the target OS using alternative credentials. Accepts credential objects (Get-Credential)\nOnly used when passwords are being exported, as it requires access to the Windows OS via PowerShell remoting to decrypt the passwords.", "", false, "false", "", "" ], [ "LinkedServer", "Specifies which linked servers to copy from the source instance. Accepts an array of linked server names.\r\nUse this when you only need to migrate specific linked servers rather than all of them.\r\nIf omitted, all linked servers from the source will be copied to the destination.", "", false, "false", "", "" ], [ "ExcludeLinkedServer", "Specifies linked servers to skip during the copy operation. Accepts an array of linked server names.\r\nUse this when you want to copy most linked servers but exclude problematic ones or those that shouldn\u0027t be migrated.\r\nThis parameter is ignored if LinkedServer is specified.", "", false, "false", "", "" ], [ "UpgradeSqlClient", "Updates older SQL Server Native Client providers (SQLNCLI) to the newest version available on the destination server.\r\nUse this when migrating from older SQL Server versions to ensure linked servers use current client libraries.\r\nThe function automatically detects and upgrades to the highest numbered SQLNCLI provider found on the destination.", "", false, "false", "False", "" ], [ "ExcludePassword", "Copies linked server definitions without migrating stored passwords or sensitive authentication data.\r\nUse this in security-conscious environments where password decryption is restricted or when passwords should be manually reset after migration.\r\nLinked servers will be created but authentication credentials will need to be reconfigured.", "", false, "false", "False", "" ], [ "Force", "Drops and recreates linked servers that already exist on the destination instance.\r\nUse this when you need to overwrite existing linked server configurations with updated settings from the source.\r\nWithout this parameter, existing linked servers on the destination are skipped to prevent accidental overwrites.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "Shows what would happen if the command were to run. No actions are actually performed.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before executing any changing operations within the command.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Migration", "Login" ], "CommandName": "Copy-DbaLogin", "Name": "Copy-DbaLogin", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Copy-DbaLogin [-SourceSqlCredential \u003cPSCredential\u003e] [-DestinationSqlCredential \u003cPSCredential\u003e] [-Login \u003cObject[]\u003e] [-ExcludeLogin \u003cObject[]\u003e] [-ExcludeSystemLogins] [-LoginRenameHashtable \u003cHashtable\u003e] [-KillActiveConnection] [-NewSid] [-Force] [-ObjectLevel] [-ExcludePermissionSync] [-ExcludeDatabaseMapping] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nCopy-DbaLogin -Source \u003cDbaInstanceParameter\u003e [-SourceSqlCredential \u003cPSCredential\u003e] -Destination \u003cDbaInstanceParameter[]\u003e [-DestinationSqlCredential \u003cPSCredential\u003e] [-Login \u003cObject[]\u003e] [-ExcludeLogin \u003cObject[]\u003e] [-ExcludeSystemLogins] [-SyncSaName] [-LoginRenameHashtable \u003cHashtable\u003e] [-KillActiveConnection] [-NewSid] [-Force] [-ObjectLevel] [-ExcludePermissionSync] [-ExcludeDatabaseMapping] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nCopy-DbaLogin -Source \u003cDbaInstanceParameter\u003e [-SourceSqlCredential \u003cPSCredential\u003e] [-DestinationSqlCredential \u003cPSCredential\u003e] [-Login \u003cObject[]\u003e] [-ExcludeLogin \u003cObject[]\u003e] [-ExcludeSystemLogins] -OutFile \u003cString\u003e [-LoginRenameHashtable \u003cHashtable\u003e] [-KillActiveConnection] [-NewSid] [-Force] [-ObjectLevel] [-ExcludePermissionSync] [-ExcludeDatabaseMapping] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nCopy-DbaLogin [-SourceSqlCredential \u003cPSCredential\u003e] -Destination \u003cDbaInstanceParameter[]\u003e [-DestinationSqlCredential \u003cPSCredential\u003e] [-Login \u003cObject[]\u003e] [-ExcludeLogin \u003cObject[]\u003e] [-ExcludeSystemLogins] [-InputObject \u003cObject[]\u003e] [-LoginRenameHashtable \u003cHashtable\u003e] [-KillActiveConnection] [-NewSid] [-Force] [-ObjectLevel] [-ExcludePermissionSync] [-ExcludeDatabaseMapping] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nCopy-DbaLogin [-SourceSqlCredential \u003cPSCredential\u003e] [-DestinationSqlCredential \u003cPSCredential\u003e] [-Login \u003cObject[]\u003e] [-ExcludeLogin \u003cObject[]\u003e] [-ExcludeSystemLogins] [-SyncSaName] [-LoginRenameHashtable \u003cHashtable\u003e] [-KillActiveConnection] [-NewSid] [-Force] [-ObjectLevel] [-ExcludePermissionSync] [-ExcludeDatabaseMapping] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per login migration attempt. Each object represents the result of copying a single login to a destination instance.\nDefault display properties (via Select-DefaultView with TypeName MigrationObject):\r\n- DateTime: Timestamp when the migration operation occurred (DbaDateTime)\r\n- SourceServer: Name of the source SQL Server instance\r\n- DestinationServer: Name of the destination SQL Server instance\r\n- Name: Login name that was copied (or renamed login name if -LoginRenameHashtable was used)\r\n- Type: Login type (e.g., \"Login - SqlLogin\", \"Login - WindowsUser\", \"Login - WindowsGroup\")\r\n- Status: Result of the migration attempt (Successful, Skipped, or Failed)\r\n- Notes: Additional details about the operation or reason for skipping/failure\nAll properties available on the returned object:\r\n- SourceServer: Name of the source SQL Server instance\r\n- DestinationServer: Name of the destination SQL Server instance\r\n- Type: Login type classification\r\n- Name: Destination login name (post-rename if applicable)\r\n- DestinationLogin: Destination login name (same as Name)\r\n- SourceLogin: Original login name from source server\r\n- Status: Operation result\r\n- Notes: Operation details or error message\r\n- DateTime: Operation timestamp\nSystem.String (when -OutFile is specified)\nWhen exporting login scripts to a file using -OutFile, the function returns the file path where the T-SQL scripts were written.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaLogin -Source sqlserver2014a -Destination sqlcluster -Force\nCopies all logins from Source Destination. If a SQL Login on Source exists on the Destination, the Login on Destination will be dropped and recreated.\nIf active connections are found for a login, the copy of that Login will fail as it cannot be dropped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaLogin -Source sqlserver2014a -Destination sqlcluster -Force -KillActiveConnection\nCopies all logins from Source Destination. If a SQL Login on Source exists on the Destination, the Login on Destination will be dropped and recreated.\nIf any active connections are found they will be killed.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaLogin -Source sqlserver2014a -Destination sqlcluster -ExcludeLogin realcajun -SourceSqlCredential $scred -DestinationSqlCredential $dcred\nCopies all Logins from Source to Destination except for realcajun using SQL Authentication to connect to both instances.\nIf a Login already exists on the destination, it will not be migrated.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eCopy-DbaLogin -Source sqlserver2014a -Destination sqlcluster -Login realcajun, netnerds -force\nCopies ONLY Logins netnerds and realcajun. If Login realcajun or netnerds exists on Destination, the existing Login(s) will be dropped and recreated.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eCopy-DbaLogin -LoginRenameHashtable @{ \"PreviousUser\" = \"newlogin\" } -Source $Sql01 -Destination Localhost -SourceSqlCredential $sqlcred -Login PreviousUser\nCopies PreviousUser as newlogin.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eCopy-DbaLogin -LoginRenameHashtable @{ OldLogin = \"NewLogin\" } -Source Sql01 -Destination Sql01 -Login ORG\\OldLogin -ObjectLevel -NewSid\nClones OldLogin as NewLogin onto the same server, generating a new SID for the login. Also clones object-level permissions.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eGet-DbaLogin -SqlInstance sql2016 | Out-GridView -Passthru | Copy-DbaLogin -Destination sql2017\nDisplays all available logins on sql2016 in a grid view, then copies all selected logins to sql2017.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003e$loginSplat = @{\n\u003e\u003e Source = $Sql01\r\n\u003e\u003e Destination = \"Localhost\"\r\n\u003e\u003e SourceSqlCredential = $sqlcred\r\n\u003e\u003e Login = \u0027ReadUserP\u0027, \u0027ReadWriteUserP\u0027, \u0027AdminP\u0027\r\n\u003e\u003e LoginRenameHashtable = @{\r\n\u003e\u003e \"ReadUserP\" = \"ReadUserT\"\r\n\u003e\u003e \"ReadWriteUserP\" = \"ReadWriteUserT\"\r\n\u003e\u003e \"AdminP\" = \"AdminT\"\r\n\u003e\u003e }\r\n\u003e\u003e }\r\nPS C:\\\u003e Copy-DbaLogin @loginSplat\nCopies the three specified logins to \u0027localhost\u0027 and renames them according to the LoginRenameHashTable.", "Description": "Transfers SQL Server logins from one instance to another while preserving authentication details and security context. Essential for server migrations, disaster recovery setups, and environment synchronization where you need users to maintain the same access without recreating accounts manually.\n\nHandles both SQL Server and Windows Authentication logins, copying passwords (with original SIDs to prevent orphaned users), server roles, database permissions, and login properties like password policy enforcement. Includes smart conflict resolution - can drop and recreate existing logins, rename logins during copy, or generate new SIDs when copying to the same server.\n\nVersion compatibility: SQL Server 2000-2008 R2 logins copy to any version, but SQL Server 2012+ logins (due to hash algorithm changes) only copy to SQL Server 2012 and newer. Automatically handles version-specific features and validates compatibility before attempting migration.", "Links": "https://dbatools.io/Copy-DbaLogin", "Synopsis": "Copies SQL Server logins between instances with passwords, permissions, and role memberships intact", "Availability": "Windows, Linux, macOS", "Params": [ [ "Source", "Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.", "", true, "false", "", "" ], [ "SourceSqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Destination", "Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.", "", true, "false", "", "" ], [ "DestinationSqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Login", "Specifies which SQL Server logins to copy from the source instance. Accepts wildcards and arrays of login names.\r\nUse this when you need to copy specific logins rather than all logins, such as during application migrations or when setting up users for specific databases.", "", false, "false", "", "" ], [ "ExcludeLogin", "Specifies which logins to skip during the copy operation. Accepts wildcards and arrays of login names.\r\nUseful for excluding test accounts, service accounts that should remain environment-specific, or logins that already exist on the destination with different configurations.", "", false, "false", "", "" ], [ "ExcludeSystemLogins", "Excludes NT SERVICE accounts and other system-generated logins from the copy operation.\r\nUse this during server migrations when you don\u0027t want to copy OS-level service accounts that may differ between environments.", "", false, "false", "False", "" ], [ "SyncSaName", "Renames the destination sa account to match the source sa account name if they differ.\r\nUse this during migrations when your organization has renamed the sa account for security purposes and you need consistent naming across instances.", "", false, "false", "False", "" ], [ "OutFile", "Exports login creation scripts to a T-SQL file instead of copying directly to a destination instance.\r\nUse this to generate scripts for manual review, version control, or deployment through automated processes rather than performing immediate migration.", "", true, "false", "", "" ], [ "InputObject", "Accepts login objects from Get-DbaLogin or other dbatools commands through the pipeline.\r\nUse this when you want to filter or manipulate login objects before copying, such as selecting logins through Out-GridView or combining multiple sources.", "", false, "true (ByValue)", "", "" ], [ "LoginRenameHashtable", "Renames logins during copy using a hashtable with old names as keys and new names as values.\r\nUse this for login consolidation, environment-specific naming conventions, or when resolving naming conflicts during migrations.", "", false, "false", "", "" ], [ "KillActiveConnection", "Terminates active sessions for logins being replaced when using -Force, allowing the drop and recreate operation to proceed.\r\nUse this during maintenance windows when you need to force login replacement despite active connections, but ensure users are notified of potential disruption.", "", false, "false", "False", "" ], [ "NewSid", "Forces generation of new Security Identifiers (SIDs) for copied logins instead of preserving original SIDs.\r\nUse this when copying logins to the same instance (login cloning) or when SID conflicts exist on the destination server.", "", false, "false", "False", "" ], [ "Force", "Drops and recreates existing logins on the destination server, transferring ownership of databases and SQL Agent jobs to \u0027sa\u0027 first.\r\nUse this when you need to update login passwords or properties that can\u0027t be modified in place, but ensure job ownership changes are acceptable.", "", false, "false", "False", "" ], [ "ObjectLevel", "Copies granular object-level permissions (table, view, procedure permissions) in addition to database and server roles.\r\nUse this for complete security replication when applications rely on specific object permissions rather than just role memberships.", "", false, "false", "False", "" ], [ "ExcludePermissionSync", "Skips copying server roles, database permissions, and security mappings for the login accounts.\r\nUse this when you only need the login accounts created but plan to configure permissions separately, or when copying logins for testing purposes.", "", false, "false", "False", "" ], [ "ExcludeDatabaseMapping", "Skips copying database-level permissions and role memberships, syncing only server-level roles and securables.\r\nUse this when you want to sync server permissions (sysadmin membership, server securables, etc.) without iterating through all databases, which significantly improves performance on instances with \r\nmany databases. When used with -OutFile, generated scripts also exclude database user mappings and permissions.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": "Migration", "CommandName": "Copy-DbaPolicyManagement", "Name": "Copy-DbaPolicyManagement", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Copy-DbaPolicyManagement [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-Policy] \u003cObject[]\u003e] [[-ExcludePolicy] \u003cObject[]\u003e] [[-Condition] \u003cObject[]\u003e] [[-ExcludeCondition] \u003cObject[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per policy category, condition, object set, and policy successfully copied or skipped. All objects use a common schema with the following properties:\nDefault display properties (via Select-DefaultView):\r\n- DateTime: Timestamp of when the copy operation was attempted (DbaDateTime)\r\n- SourceServer: The source SQL Server instance name where the object was copied from\r\n- DestinationServer: The destination SQL Server instance name where the object was copied to\r\n- Name: The name of the policy category, condition, object set, or policy that was processed\r\n- Type: The type of object being copied - one of \"Policy Category\", \"Policy Condition\", \"Policy ObjectSet\", or \"Policy\"\r\n- Status: The result of the operation - \"Successful\", \"Skipped\", or \"Failed\"\r\n- Notes: Additional information about the operation result, such as \"Already exists on destination\" or error details", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaPolicyManagement -Source sqlserver2014a -Destination sqlcluster\nCopies all policies and conditions from sqlserver2014a to sqlcluster, using Windows credentials.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaPolicyManagement -Source sqlserver2014a -Destination sqlcluster -SourceSqlCredential $cred\nCopies all policies and conditions from sqlserver2014a to sqlcluster, using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaPolicyManagement -Source sqlserver2014a -Destination sqlcluster -WhatIf\nShows what would happen if the command were executed.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eCopy-DbaPolicyManagement -Source sqlserver2014a -Destination sqlcluster -Policy \u0027xp_cmdshell must be disabled\u0027\nCopies only one policy, \u0027xp_cmdshell must be disabled\u0027 from sqlserver2014a to sqlcluster. No conditions are migrated.", "Description": "Transfers your entire Policy-Based Management framework from one SQL Server instance to another, including custom policies, conditions, object sets, and categories. This streamlines environment standardization and disaster recovery scenarios where you need identical compliance policies across multiple servers.\n\nBy default, all non-system policies, conditions, and object sets are copied. Object sets are migrated after conditions and before policies to ensure policy dependencies are satisfied. Existing objects on the destination are skipped unless -Force is used to overwrite them. You can selectively copy specific policies or conditions using the include/exclude parameters, which provide auto-completion from the source server.", "Links": "https://dbatools.io/Copy-DbaPolicyManagement", "Synopsis": "Copies Policy-Based Management policies, conditions, and categories between SQL Server instances", "Availability": "Windows only", "Params": [ [ "Source", "Specifies the source SQL Server instance containing the Policy-Based Management objects to copy. Must be SQL Server 2008 or higher with sysadmin access.\r\nUse this to identify which server contains your existing policies, conditions, and categories that need to be replicated to other instances.", "", true, "false", "", "" ], [ "SourceSqlCredential", "Alternative credentials for connecting to the source SQL Server instance. Use when the current Windows credentials don\u0027t have access to the source.\r\nCommonly needed when copying from production servers that require SQL Authentication or different Active Directory accounts.", "", false, "false", "", "" ], [ "Destination", "Specifies one or more destination SQL Server instances where Policy-Based Management objects will be created. Must be SQL Server 2008 or higher with sysadmin access.\r\nUse this when standardizing compliance policies across multiple environments like development, staging, and production servers.", "", true, "false", "", "" ], [ "DestinationSqlCredential", "Alternative credentials for connecting to the destination SQL Server instances. Use when the current Windows credentials don\u0027t have access to the destination servers.\r\nParticularly useful when copying to servers in different domains or when using SQL Authentication on destination instances.", "", false, "false", "", "" ], [ "Policy", "Specifies which policies to copy by name, with auto-completion from the source server. Only the specified policies and their dependent conditions are copied.\r\nUse this when you need to copy specific compliance policies rather than the entire Policy-Based Management framework, such as copying only security-related policies.", "", false, "false", "", "" ], [ "ExcludePolicy", "Specifies which policies to skip during the copy operation, with auto-completion from the source server. All other policies will be copied.\r\nUse this to exclude environment-specific policies or policies that shouldn\u0027t be replicated, such as development-only or deprecated policies.", "", false, "false", "", "" ], [ "Condition", "Specifies which conditions to copy by name, with auto-completion from the source server. Only the specified conditions are copied without their associated policies.\r\nUse this when you need to copy reusable conditions that can be referenced by multiple policies, such as server configuration or database naming conditions.", "", false, "false", "", "" ], [ "ExcludeCondition", "Specifies which conditions to skip during the copy operation, with auto-completion from the source server. All other conditions will be copied.\r\nUse this to exclude conditions that are environment-specific or no longer needed, while copying the rest of your condition library.", "", false, "false", "", "" ], [ "Force", "Overwrites existing policies and conditions on the destination server by dropping and recreating them. Without this switch, existing objects are skipped.\r\nUse this when updating existing Policy-Based Management objects or when you need to ensure destination objects match the source exactly.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "Shows what would happen if the command were to run. No actions are actually performed.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before executing any changing operations within the command.", "cf", false, "false", "", "" ] ] }, { "Tags": "Migration", "CommandName": "Copy-DbaRegServer", "Name": "Copy-DbaRegServer", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Copy-DbaRegServer [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-Group] \u003cString[]\u003e] [-SwitchServerName] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per migration action (group creation, instance addition, etc.). The command returns multiple objects representing the status of different CMS components being migrated.\nProperties:\r\n- DateTime: The timestamp when the migration action occurred (DbaDateTime object)\r\n- SourceServer: Name of the source SQL Server instance from which items are being copied\r\n- DestinationServer: Name of the destination SQL Server instance to which items are being copied\r\n- Name: The name of the CMS group or registered server instance that was migrated\r\n- Type: The type of object migrated - one of \"CMS Destination Group\", \"CMS Group\", or \"CMS Instance\"\r\n- Status: Result of the migration action (\"Successful\", \"Skipped\", or \"Failed\")\r\n- Notes: Additional information about the migration result, typically explains why an action was skipped or the error message if failed", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaRegServer -Source sqlserver2014a -Destination sqlcluster\nAll groups, subgroups, and server instances are copied from sqlserver2014a CMS to sqlcluster CMS.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaRegServer -Source sqlserver2014a -Destination sqlcluster -Group Group1,Group3\nTop-level groups Group1 and Group3 along with their subgroups and server instances are copied from sqlserver to sqlcluster.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaRegServer -Source sqlserver2014a -Destination sqlcluster -Group Group1,Group3 -SwitchServerName -SourceSqlCredential $SourceSqlCredential -DestinationSqlCredential \r\n$DestinationSqlCredential\nTop-level groups Group1 and Group3 along with their subgroups and server instances are copied from sqlserver to sqlcluster. When adding sql instances to sqlcluster, if the server name of the \r\nmigrating instance is \"sqlcluster\", it will be switched to \"sqlserver\".\nIf SwitchServerName is not specified, \"sqlcluster\" will be skipped.", "Description": "Migrates registered servers and server groups from a source Central Management Server to a destination CMS, preserving the hierarchical structure of groups and subgroups. This eliminates the need to manually recreate complex server organization structures when setting up new environments or consolidating server management. The function handles conflicts by either skipping existing items or dropping and recreating them when Force is specified.", "Links": "https://dbatools.io/Copy-DbaRegServer", "Synopsis": "Copies Central Management Server groups and registered server instances between SQL Server instances.", "Availability": "Windows, Linux, macOS", "Params": [ [ "Source", "Source SQL Server instance containing the Central Management Server to copy from. You must have sysadmin access and server version must be SQL Server version 2000 or higher.\r\nThis is where your existing CMS groups and registered servers are currently stored.", "", true, "false", "", "" ], [ "SourceSqlCredential", "Credentials for connecting to the source SQL Server instance when Windows Authentication is not available. Accepts PowerShell credentials (Get-Credential).\r\nUse this when the source server requires SQL Authentication or different Windows credentials than your current session.", "", false, "false", "", "" ], [ "Destination", "Destination SQL Server instance where CMS groups and registered servers will be copied to. You must have sysadmin access and the server must be SQL Server 2000 or higher.\r\nThis instance will become the new Central Management Server containing the migrated server registrations.", "", true, "false", "", "" ], [ "DestinationSqlCredential", "Credentials for connecting to the destination SQL Server instance when Windows Authentication is not available. Accepts PowerShell credentials (Get-Credential).\r\nUse this when the destination server requires SQL Authentication or different Windows credentials than your current session.", "", false, "false", "", "" ], [ "Group", "Specifies which top-level CMS groups to copy from the source server. Accepts one or more group names as an array.\r\nWhen omitted, all groups and their registered servers are copied. Use this to selectively migrate specific environments like \u0027Production\u0027 or \u0027Development\u0027 groups.", "CMSGroup", false, "false", "", "" ], [ "SwitchServerName", "Replaces source server name references with the destination server name during migration.\r\nUse this when the source CMS server itself is registered within the groups and you want it renamed to the destination server name. Prevents conflicts since CMS cannot register itself as a managed \r\nserver.", "", false, "false", "False", "" ], [ "Force", "Drops and recreates existing groups and registered servers at the destination instead of skipping them.\r\nUse this to overwrite conflicting CMS configurations when consolidating multiple Central Management Servers or updating existing registrations.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Migration", "ResourceGovernor" ], "CommandName": "Copy-DbaResourceGovernor", "Name": "Copy-DbaResourceGovernor", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Copy-DbaResourceGovernor [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-ResourcePool] \u003cObject[]\u003e] [[-ExcludeResourcePool] \u003cObject[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject (MigrationObject)\nReturns one object per item migrated (Resource Governor settings, pools, workload groups, and classifier functions). Each object represents the migration status of a single component.\nProperties:\r\n- DateTime: Timestamp when the object was created (DbaDateTime)\r\n- SourceServer: The name of the source SQL Server instance (string)\r\n- DestinationServer: The name of the destination SQL Server instance (string)\r\n- Name: The name of the object being migrated (string) - examples: \"Classifier Function\", \"PoolName\", \"WorkgroupName\", \"Reconfigure Resource Governor\"\r\n- Type: The type of object being migrated (string) - one of: \"Resource Governor Settings\", \"Resource Governor Pool\", \"Resource Governor Pool Workgroup\", \"Reconfigure Resource Governor\"\r\n- Status: The migration status (string) - one of: \"Successful\", \"Skipped\", \"Failed\", or $null\r\n- Notes: Additional details about the operation (string) - examples: \"Already exists on destination\", \"The new classifier function has been created\", error messages for failures, or $null\nAll properties are displayed by default through Select-DefaultView.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaResourceGovernor -Source sqlserver2014a -Destination sqlcluster\nCopies all all non-system resource pools from sqlserver2014a to sqlcluster using Windows credentials to connect to the SQL Server instances..\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaResourceGovernor -Source sqlserver2014a -Destination sqlcluster -SourceSqlCredential $cred\nCopies all all non-system resource pools from sqlserver2014a to sqlcluster using SQL credentials to connect to sqlserver2014a and Windows credentials to connect to sqlcluster.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaResourceGovernor -Source sqlserver2014a -Destination sqlcluster -WhatIf\nShows what would happen if the command were executed.", "Description": "Migrates your entire SQL Server Resource Governor setup from one instance to another, including custom resource pools, workload groups, and classifier functions. This saves you from manually recreating complex Resource Governor configurations when setting up new servers or during migrations.\n\nThe function copies all non-system resource pools (excludes the built-in \"internal\" and \"default\" pools) along with their associated workload groups and settings. It also migrates any custom classifier function you\u0027ve configured to automatically assign incoming requests to appropriate resource pools.\n\nIf a resource pool already exists on the destination server, it will be skipped unless you use -Force to overwrite it. Resource Governor will be properly reconfigured after the migration to ensure all changes take effect.\n\nNote that Resource Governor is only available in Enterprise, Datacenter, and Developer editions of SQL Server. The -ResourcePool parameter is auto-populated for command-line completion and can be used to copy only specific objects.", "Links": "https://dbatools.io/Copy-DbaResourceGovernor", "Synopsis": "Copies SQL Server Resource Governor configuration including pools, workload groups, and classifier functions between instances", "Availability": "Windows, Linux, macOS", "Params": [ [ "Source", "Specifies the source SQL Server instance containing the Resource Governor configuration to copy. Must have sysadmin privileges and be SQL Server 2008 or later.\r\nUse this to identify which server contains the Resource Governor setup you want to migrate to other instances.", "", true, "false", "", "" ], [ "SourceSqlCredential", "Provides alternative credentials for connecting to the source SQL Server instance. Accepts PowerShell credential objects from Get-Credential.\r\nUse this when your current Windows credentials don\u0027t have access to the source server or when you need to use SQL Server authentication.", "", false, "false", "", "" ], [ "Destination", "Specifies the destination SQL Server instance(s) where the Resource Governor configuration will be copied. Accepts multiple instances and requires sysadmin privileges on each.\r\nUse this to define which servers should receive the migrated Resource Governor pools, workload groups, and classifier functions.", "", true, "false", "", "" ], [ "DestinationSqlCredential", "Provides alternative credentials for connecting to the destination SQL Server instance(s). Accepts PowerShell credential objects from Get-Credential.\r\nUse this when your current Windows credentials don\u0027t have access to the destination servers or when you need to use SQL Server authentication.", "", false, "false", "", "" ], [ "ResourcePool", "Specifies which resource pools to copy by name. Supports tab completion with pools from the source server and accepts multiple pool names.\r\nUse this when you only want to migrate specific resource pools rather than the entire Resource Governor configuration. Excludes system pools (internal, default) automatically.", "", false, "false", "", "" ], [ "ExcludeResourcePool", "Specifies which resource pools to skip during the copy operation. Supports tab completion and accepts multiple pool names.\r\nUse this when you want to migrate most of your Resource Governor configuration but exclude certain pools that shouldn\u0027t be copied to the destination.", "", false, "false", "", "" ], [ "Force", "Drops and recreates existing resource pools, workload groups, and classifier functions on the destination server.\r\nUse this when you need to overwrite existing Resource Governor objects that would otherwise be skipped due to name conflicts.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Migration", "ServerRole", "Security" ], "CommandName": "Copy-DbaServerRole", "Name": "Copy-DbaServerRole", "Author": "the dbatools team + Claude", "Syntax": "Copy-DbaServerRole [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-ServerRole] \u003cObject[]\u003e] [[-ExcludeServerRole] \u003cObject[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject (MigrationObject)\nReturns one object per server role processed. The object contains the result of attempting to copy each role from the source to the destination server.\nProperties:\r\n- DateTime: Timestamp when the role copy operation was executed (DbaDateTime)\r\n- SourceServer: Name of the source SQL Server instance\r\n- DestinationServer: Name of the destination SQL Server instance\r\n- Name: Name of the server role being copied\r\n- Type: Always \"Server Role\"\r\n- Status: Result of the copy operation (Successful, Skipped, or Failed)\r\n- Notes: Additional details about the operation or error message if the status is Failed", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaServerRole -Source sqlserver2014a -Destination sqlcluster\nCopies all custom server roles from sqlserver2014a to sqlcluster using Windows credentials. If roles with the same name exist on sqlcluster, they will be skipped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaServerRole -Source sqlserver2014a -SourceSqlCredential $scred -Destination sqlcluster -DestinationSqlCredential $dcred -ServerRole \"CustomRole1\" -Force\nCopies only the custom server role named \"CustomRole1\" from sqlserver2014a to sqlcluster using SQL credentials. If the role exists on sqlcluster, it will be dropped and recreated because -Force was \r\nused.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaServerRole -Source sqlserver2014a -Destination sqlcluster -ExcludeServerRole \"TestRole\" -Force\nCopies all custom server roles found on sqlserver2014a except \"TestRole\" to sqlcluster. If roles with the same name exist on sqlcluster, they will be updated because -Force was used.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eCopy-DbaServerRole -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force\nShows what would happen if the command were executed using force.", "Description": "Copies user-defined server roles from the source server to one or more destination servers. This is essential when migrating SQL Server instances that use custom server roles for granular permission management, or when standardizing security configurations across multiple environments.\n\nOnly custom (user-defined) server roles are copied by default. Fixed server roles like sysadmin, serveradmin, etc. are built into SQL Server and cannot be created or dropped. Use -IncludeFixedRole to also synchronize memberships for fixed roles.\n\nServer role permissions and memberships are migrated along with the role definition. This includes server-level permissions granted to the role (like CONNECT ANY DATABASE, VIEW ANY DATABASE) and login memberships in the role.\n\nBy default, existing server roles on the destination are skipped to prevent conflicts. Use -Force to drop and recreate existing roles, which will also reapply all permissions and memberships.", "Links": "https://dbatools.io/Copy-DbaServerRole", "Synopsis": "Migrates custom server roles and their permissions between SQL Server instances", "Availability": "Windows, Linux, macOS", "Params": [ [ "Source", "Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2012 or higher.", "", true, "false", "", "" ], [ "SourceSqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Destination", "Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2012 or higher.", "", true, "false", "", "" ], [ "DestinationSqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "ServerRole", "Specifies which server roles to migrate from the source server. Only the specified roles will be copied to the destination.\r\nUse this when you need to migrate specific custom roles rather than all of them, such as when standardizing only certain security roles across environments.", "", false, "false", "", "" ], [ "ExcludeServerRole", "Specifies which server roles to skip during migration. All custom server roles except the excluded ones will be copied.\r\nUse this when you want to migrate most roles but exclude problematic ones, or when certain roles are environment-specific and shouldn\u0027t be copied.", "", false, "false", "", "" ], [ "Force", "Drops and recreates existing custom server roles on the destination server, reapplying all permissions and memberships from the source.\r\nUse this when you need to update server role permissions that have changed on the source, or when synchronizing role definitions across environments.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Migration", "Configure", "SpConfigure" ], "CommandName": "Copy-DbaSpConfigure", "Name": "Copy-DbaSpConfigure", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Copy-DbaSpConfigure [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-ConfigName] \u003cObject[]\u003e] [[-ExcludeConfigName] \u003cObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per sp_configure setting processed, regardless of whether the setting was updated, skipped, or failed.\nProperties:\r\n- DateTime: Timestamp when the operation was performed (DbaDateTime object)\r\n- SourceServer: Name of the source SQL Server instance\r\n- DestinationServer: Name of the destination SQL Server instance\r\n- Name: The name of the sp_configure setting that was copied\r\n- Type: Always \"Configuration Value\"\r\n- Status: The result of the operation - either \"Skipped\", \"Successful\", or \"Failed\"\r\n- Notes: Additional details about the operation (e.g., \"Configuration does not exist on destination\", \"Requires restart\", or error message if failed)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaSpConfigure -Source sqlserver2014a -Destination sqlcluster\nCopies all sp_configure settings from sqlserver2014a to sqlcluster\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaSpConfigure -Source sqlserver2014a -Destination sqlcluster -ConfigName DefaultBackupCompression, IsSqlClrEnabled -SourceSqlCredential $cred\nCopies the values for IsSqlClrEnabled and DefaultBackupCompression from sqlserver2014a to sqlcluster using SQL credentials to authenticate to sqlserver2014a and Windows credentials to authenticate to \r\nsqlcluster.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaSpConfigure -Source sqlserver2014a -Destination sqlcluster -ExcludeConfigName DefaultBackupCompression, IsSqlClrEnabled\nCopies all configs except for IsSqlClrEnabled and DefaultBackupCompression, from sqlserver2014a to sqlcluster.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eCopy-DbaSpConfigure -Source sqlserver2014a -Destination sqlcluster -WhatIf\nShows what would happen if the command were executed.", "Description": "This function retrieves all sp_configure settings from the source SQL Server and applies them to one or more destination instances, ensuring consistent configuration across your environment. Only settings that differ between source and destination are updated, making it safe for standardizing existing servers. The function automatically handles settings that require a restart and provides detailed reporting of which configurations were changed, skipped, or failed. Use this when building new servers to match production standards, migrating instances, or ensuring consistent configuration across development and testing environments.", "Links": "https://dbatools.io/Copy-DbaSpConfigure", "Synopsis": "Copies SQL Server configuration settings (sp_configure values) from source to destination instances.", "Availability": "Windows, Linux, macOS", "Params": [ [ "Source", "The source SQL Server instance from which sp_configure settings will be copied. Must have sysadmin access to read configuration values.\r\nUse this as your template server when standardizing configurations across multiple instances or when setting up new servers to match production standards.", "", true, "false", "", "" ], [ "SourceSqlCredential", "Credentials for connecting to the source SQL Server instance. Accepts PowerShell credentials (Get-Credential).\r\nUse this when the source server requires different authentication than your current Windows session, such as SQL Server authentication or domain service accounts.\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Destination", "One or more destination SQL Server instances where sp_configure settings will be applied. Must have sysadmin access to modify configuration values.\r\nAccepts multiple instances for bulk configuration updates across your environment.", "", true, "false", "", "" ], [ "DestinationSqlCredential", "Credentials for connecting to the destination SQL Server instances. Accepts PowerShell credentials (Get-Credential).\r\nUse this when destination servers require different authentication than your current Windows session, such as SQL Server authentication or domain service accounts.\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "ConfigName", "Specifies which sp_configure settings to copy from source to destination. Accepts one or more configuration names such as \u0027max server memory (MB)\u0027 or \u0027backup compression default\u0027.\r\nUse this when you need to update only specific settings rather than copying all configurations, particularly useful for targeted changes like memory settings or backup options.", "", false, "false", "", "" ], [ "ExcludeConfigName", "Specifies which sp_configure settings to skip during the copy operation. Accepts one or more configuration names to exclude from processing.\r\nUse this when copying most settings but need to preserve specific destination values, such as excluding \u0027max server memory (MB)\u0027 when servers have different hardware specifications.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Migration", "SSIS" ], "CommandName": "Copy-DbaSsisCatalog", "Name": "Copy-DbaSsisCatalog", "Author": "Phil Schwartz (philschwartz.me, @pschwartzzz), the dbatools team + Claude", "Syntax": "Copy-DbaSsisCatalog [-Source] \u003cDbaInstanceParameter\u003e [-Destination] \u003cDbaInstanceParameter[]\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-Project] \u003cString\u003e] [[-Folder] \u003cString\u003e] [[-Environment] \u003cString\u003e] [[-CreateCatalogPassword] \u003cSecureString\u003e] [-EnableSqlClr] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per migration operation attempt. Each object represents the result of copying a single folder, project, or environment to a destination instance.\nDefault display properties (via Select-DefaultView with TypeName MigrationObject):\r\n- DateTime: Timestamp when the migration operation occurred (DbaDateTime)\r\n- SourceServer: Name of the source SQL Server instance\r\n- DestinationServer: Name of the destination SQL Server instance\r\n- Name: Name of the object that was copied (folder, project, or environment name)\r\n- Type: Object type (Folder, Project, or Environment)\r\n- Status: Result of the migration attempt (Successful, Skipped, or Failed)\r\n- Notes: Additional details about the operation or reason for skipping/failure", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaSsisCatalog -Source sqlserver2014a -Destination sqlcluster\nCopies all folders, environments and SSIS Projects from sqlserver2014a to sqlcluster, using Windows credentials to authenticate to both instances. If folders with the same name exist on the \r\ndestination they will be skipped, but projects will be redeployed.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaSsisCatalog -Source sqlserver2014a -Destination sqlcluster -Project Archive_Tables -SourceSqlCredential $cred -Force\nCopies a single Project, the Archive_Tables Project, from sqlserver2014a to sqlcluster using SQL credentials to authenticate to sqlserver2014a and Windows credentials to authenticate to sqlcluster. \r\nIf a Project with the same name exists on sqlcluster, it will be deleted and recreated because -Force was used.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaSsisCatalog -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force\nShows what would happen if the command were executed using force.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$SecurePW = Read-Host \"Enter password\" -AsSecureString\nPS C:\\\u003e Copy-DbaSsisCatalog -Source sqlserver2014a -Destination sqlcluster -CreateCatalogPassword $SecurePW\nDeploy entire SSIS catalog to an instance without a destination catalog. User prompts for creating the catalog on Destination will be bypassed.", "Description": "Copies the complete SSISDB catalog structure from a source SQL Server to one or more destination instances. This function handles server migrations, environment promotions, and disaster recovery scenarios where you need to replicate your Integration Services deployments.\n\nBy default, all folders, projects, and environments are copied. You can use -Project, -Folder, or -Environment parameters to migrate specific components instead of the entire catalog. The function will create the SSISDB catalog on the destination if it doesn\u0027t exist, and automatically enable SQL CLR if required.\n\nThe parameters work hierarchically - specifying -Folder will only deploy projects and environments from within that folder, while -Project will deploy just that specific project from whichever folder contains it.", "Links": "https://dbatools.io/Copy-DbaSsisCatalog", "Synopsis": "Migrates SSIS catalogs including folders, projects, and environments between SQL Server instances.", "Availability": "Windows only", "Params": [ [ "Source", "Source SQL Server instance containing the SSISDB catalog to copy from. Requires sysadmin privileges and SQL Server 2012 or higher.\r\nThis instance must have Integration Services installed with an existing SSISDB catalog containing the folders, projects, and environments you want to migrate.", "", true, "false", "", "" ], [ "Destination", "Destination SQL Server instances where the SSISDB catalog will be copied to. Requires sysadmin privileges and SQL Server 2012 or higher.\r\nIf SSISDB doesn\u0027t exist on the destination, the function will offer to create it automatically including enabling CLR integration if needed.", "", true, "false", "", "" ], [ "SourceSqlCredential", "Credentials for connecting to the source SQL Server instance. Use this when you need to connect with different credentials than your current Windows identity.\r\nAccepts PowerShell credential objects created with Get-Credential and supports SQL Authentication, Windows Authentication, and Active Directory authentication modes.", "", false, "false", "", "" ], [ "DestinationSqlCredential", "Credentials for connecting to the destination SQL Server instances. Use this when you need to connect with different credentials than your current Windows identity.\r\nAccepts PowerShell credential objects created with Get-Credential and supports SQL Authentication, Windows Authentication, and Active Directory authentication modes.", "", false, "false", "", "" ], [ "Project", "Specifies a single SSIS project name to copy instead of migrating all projects. The project will be deployed from whichever source folder contains it.\r\nUse this when you only need to migrate a specific Integration Services project rather than the entire catalog structure.", "", false, "false", "", "" ], [ "Folder", "Specifies a single SSISDB catalog folder to copy instead of migrating all folders. Only projects and environments from within this folder will be copied.\r\nUse this to limit the migration scope when you only need to move contents of a specific organizational folder.", "", false, "false", "", "" ], [ "Environment", "Specifies a single SSIS environment to copy instead of migrating all environments. The environment will be deployed from whichever source folder contains it.\r\nUse this when you only need to migrate specific environment configurations that contain your parameter values and connection strings.", "", false, "false", "", "" ], [ "CreateCatalogPassword", "Password for creating a new SSISDB catalog on the destination as a SecureString object. Required when the destination doesn\u0027t have an existing SSISDB catalog.\r\nUse this in automated scripts to avoid interactive password prompts during catalog creation. The password encrypts sensitive data within the SSISDB catalog.", "", false, "false", "", "" ], [ "EnableSqlClr", "Automatically enables CLR integration on the destination without prompting for confirmation. CLR integration is required for SSISDB catalog functionality.\r\nUse this in automated scenarios where you want to avoid interactive prompts when the destination server doesn\u0027t have CLR enabled.", "", false, "false", "False", "" ], [ "Force", "Drops and recreates existing folders, projects, and environments at the destination instead of skipping them. Use this when you need to overwrite existing SSIS objects during migrations.\r\nWithout this parameter, the function will skip objects that already exist at the destination and display warning messages.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Migration", "Procedure", "Startup", "StartupProcedure" ], "CommandName": "Copy-DbaStartupProcedure", "Name": "Copy-DbaStartupProcedure", "Author": "Shawn Melton (@wsmelton), wsmelton.github.io", "Syntax": "Copy-DbaStartupProcedure [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-Procedure] \u003cString[]\u003e] [[-ExcludeProcedure] \u003cString[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per startup procedure copy operation. The object represents the outcome of copying a single startup procedure from source to destination.\nDefault display properties (via Select-DefaultView):\r\n- DateTime: Timestamp when the copy operation occurred\r\n- SourceServer: Name of the source SQL Server instance\r\n- DestinationServer: Name of the destination SQL Server instance\r\n- Name: Name of the startup procedure\r\n- Type: Type of object being copied (always \"Startup Stored Procedure\")\r\n- Status: Result of the copy operation (Successful, Skipped, or Failed)\r\n- Notes: Additional information or error message if applicable\nAdditional properties available:\r\n- Schema: Schema that the stored procedure belongs to in the master database", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaStartupProcedure -Source sqlserver2014a -Destination sqlcluster\nCopies all startup procedures from sqlserver2014a to sqlcluster using Windows credentials. If procedure(s) with the same name exists in the master database on sqlcluster, they will be skipped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaStartupProcedure -Source sqlserver2014a -SourceSqlCredential $scred -Destination sqlcluster -DestinationSqlCredential $dcred -Procedure logstartup -Force\nCopies only the startup procedure, logstartup, from sqlserver2014a to sqlcluster using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster. If the procedure already exists on \r\nsqlcluster, it will be updated because -Force was used.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaStartupProcedure -Source sqlserver2014a -Destination sqlcluster -ExcludeProcedure logstartup -Force\nCopies all the startup procedures found on sqlserver2014a except logstartup to sqlcluster. If a startup procedure with the same name exists on sqlcluster, it will be updated because -Force was used.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eCopy-DbaStartupProcedure -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force\nShows what would happen if the command were executed using force.", "Description": "Migrates user-defined startup procedures stored in the master database from source to destination SQL Server instances. Startup procedures are stored procedures that automatically execute when SQL Server starts up, commonly used for server initialization tasks, custom monitoring setup, or configuration validation.\n\nThis function identifies procedures flagged with the startup option using sp_procoption, copies their definitions to the destination master database, and configures them as startup procedures. This is essential during server migrations, disaster recovery setup, or when standardizing startup configurations across multiple SQL Server environments.\n\nBy default, all startup procedures are copied. Use -Procedure to copy specific procedures or -ExcludeProcedure to skip certain ones. Existing procedures on the destination are skipped unless -Force is used to overwrite them.", "Links": "https://dbatools.io/Copy-DbaStartupProcedure", "Synopsis": "Copies startup procedures from master database between SQL Server instances", "Availability": "Windows, Linux, macOS", "Params": [ [ "Source", "The source SQL Server instance containing startup procedures to copy from the master database. Requires sysadmin access to read stored procedure definitions and startup configuration.\r\nUse this to specify which server has the startup procedures you want to migrate or standardize across your environment.", "", true, "false", "", "" ], [ "SourceSqlCredential", "Credentials for connecting to the source SQL Server instance when Windows authentication is not available or desired.\r\nUse this when you need to connect with specific SQL login credentials or when running under a service account that lacks access to the source server.", "", false, "false", "", "" ], [ "Destination", "The destination SQL Server instance(s) where startup procedures will be copied to the master database. Requires sysadmin access to create procedures and modify startup configuration.\r\nAccepts multiple destinations to deploy startup procedures across several servers simultaneously for standardization.", "", true, "false", "", "" ], [ "DestinationSqlCredential", "Credentials for connecting to the destination SQL Server instance(s) when Windows authentication is not available or desired.\r\nUse this when deploying to servers that require different authentication credentials or when your current context lacks destination access.", "", false, "false", "", "" ], [ "Procedure", "Specifies which startup procedures to copy from the source server instead of copying all available startup procedures.\r\nUse this when you only need specific procedures migrated, such as copying just monitoring or initialization procedures while leaving others behind.", "", false, "false", "", "" ], [ "ExcludeProcedure", "Specifies which startup procedures to skip during the copy operation while processing all others from the source.\r\nUse this when most startup procedures should be copied but specific ones need to remain server-specific or are problematic.", "", false, "false", "", "" ], [ "Force", "Overwrites existing startup procedures on the destination server instead of skipping them when name conflicts occur.\r\nUse this when updating existing startup procedures with newer versions or when you need to ensure destination procedures match the source exactly.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Migration", "SystemDatabase", "UserObject" ], "CommandName": "Copy-DbaSystemDbUserObject", "Name": "Copy-DbaSystemDbUserObject", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Copy-DbaSystemDbUserObject [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [-Force] [-Classic] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "Copy-DbaSysDbUserObject", "Outputs": "PSCustomObject (default when -Classic is not specified)\nReturns one object per user-defined object (schema, table, view, function, trigger, etc.) copied from system databases. The Classic mode returns no output.\nProperties:\r\n- DateTime: The date and time the operation completed (DbaDateTime)\r\n- SourceServer: The name of the source SQL Server instance\r\n- DestinationServer: The name of the destination SQL Server instance\r\n- Name: The name of the object copied (schema name, table name, or fully qualified object name with schema)\r\n- Type: The type of object and system database (e.g., \"User schema in master\", \"User table in msdb\", \"User stored procedure in master\")\r\n- Status: The result of the copy operation (Successful, Skipped, or Failed)\r\n- Notes: Additional context about the operation result (e.g., \"Already exists on destination\", \"May have also created dependencies\", error details)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaSystemDbUserObject -Source sqlserver2014a -Destination sqlcluster\nCopies user objects found in system databases master, msdb and model from sqlserver2014a instance to the sqlcluster instance.", "Description": "Migrates custom database objects that DBAs commonly store in system databases like maintenance procedures, monitoring tables, custom triggers, and backup utilities from master and msdb. Also transfers objects from the model database that will be included in new databases created on the destination instance.\n\nThis function handles schemas, tables, views, stored procedures, functions, triggers, and other user-defined objects while preserving dependencies and permissions. It\u0027s particularly valuable during server migrations or when standardizing DBA tooling across multiple instances.", "Links": "https://dbatools.io/Copy-DbaSystemDbUserObject", "Synopsis": "Copies user-created objects from system databases (master, msdb, model) between SQL Server instances.", "Availability": "Windows, Linux, macOS", "Params": [ [ "Source", "Specifies the source SQL Server instance containing the user objects to copy from system databases.\r\nRequires sysadmin permissions to access master, msdb, and model databases for object extraction.", "", true, "false", "", "" ], [ "SourceSqlCredential", "Specifies credentials for connecting to the source SQL Server instance when Windows Authentication is not available.\r\nRequired when accessing source instances across domains or using SQL Server Authentication.", "", false, "false", "", "" ], [ "Destination", "Specifies one or more destination SQL Server instances where the user objects will be copied to.\r\nRequires sysadmin permissions to modify master, msdb, and model databases on the destination servers.", "", true, "false", "", "" ], [ "DestinationSqlCredential", "Specifies credentials for connecting to destination SQL Server instances when Windows Authentication is not available.\r\nRequired when accessing destination instances across domains or using SQL Server Authentication.", "", false, "false", "", "" ], [ "Force", "Drops existing objects on destination instances before creating new ones to resolve naming conflicts.\r\nOnly works with the default modern method, not with Classic mode, and may fail with objects that have dependencies.", "", false, "false", "False", "" ], [ "Classic", "Uses the legacy migration method that copies all object types in bulk using SQL Server Management Objects Transfer class.\r\nThe default modern method provides better error handling and granular object control but this option may resolve compatibility issues with older SQL Server versions.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Migration", "ExtendedEvent", "XEvent" ], "CommandName": "Copy-DbaXESession", "Name": "Copy-DbaXESession", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Copy-DbaXESession [-Source] \u003cDbaInstanceParameter\u003e [-Destination] \u003cDbaInstanceParameter[]\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-XeSession] \u003cObject[]\u003e] [[-ExcludeXeSession] \u003cObject[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject (with TypeName: MigrationObject)\nReturns one object per Extended Event session processed, documenting the migration status for each session copy attempt.\nProperties:\r\n- DateTime: Timestamp (DbaDateTime) when the migration operation occurred\r\n- SourceServer: Name of the source SQL Server instance from which the session was copied\r\n- DestinationServer: Name of the destination SQL Server instance where the session was copied to\r\n- Name: Name of the Extended Event session being migrated\r\n- Type: Always \"Extended Event\" indicating the object type being migrated\r\n- Status: Migration result (Successful, Skipped, or Failed)\r\n- Notes: Additional information; null for successful migrations, error message for failed operations or \"Already exists on destination\" for skipped sessions", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaXESession -Source sqlserver2014a -Destination sqlcluster\nCopies all Extended Event sessions from sqlserver2014a to sqlcluster using Windows credentials.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaXESession -Source sqlserver2014a -Destination sqlcluster -SourceSqlCredential $cred\nCopies all Extended Event sessions from sqlserver2014a to sqlcluster using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eCopy-DbaXESession -Source sqlserver2014a -Destination sqlcluster -WhatIf\nShows what would happen if the command were executed.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eCopy-DbaXESession -Source sqlserver2014a -Destination sqlcluster -XeSession CheckQueries, MonitorUserDefinedException\nCopies only the Extended Events named CheckQueries and MonitorUserDefinedException from sqlserver2014a to sqlcluster.", "Description": "Copies custom Extended Event sessions between SQL Server instances while preserving their configuration and running state. This function scripts out the session definitions from the source server and recreates them on the destination, making it essential for server migrations, standardizing monitoring across environments, or setting up disaster recovery instances.\n\nSystem sessions (AlwaysOn_health and system_health) are automatically excluded since they\u0027re managed by SQL Server itself. If a session was running on the source, it will be started on the destination after creation. Existing sessions with the same name on the destination will be skipped unless you use the Force parameter to overwrite them.\n\nPerfect for migrating your custom monitoring, auditing, and troubleshooting Extended Event sessions when moving databases between servers or ensuring consistent monitoring across your SQL Server estate.", "Links": "https://dbatools.io/Copy-DbaXESession", "Synopsis": "Copies Extended Event sessions from one SQL Server instance to another, excluding system sessions.", "Availability": "Windows, Linux, macOS", "Params": [ [ "Source", "The source SQL Server instance containing the Extended Event sessions to copy. Requires sysadmin privileges and SQL Server 2012 or higher.\r\nThis is typically your production server or template instance where you\u0027ve configured custom monitoring and auditing sessions.", "", true, "false", "", "" ], [ "Destination", "One or more destination SQL Server instances where Extended Event sessions will be recreated. Accepts arrays for bulk deployment to multiple servers.\r\nCommon scenarios include disaster recovery sites, development environments, or new production servers that need the same monitoring configuration.", "", true, "false", "", "" ], [ "SourceSqlCredential", "SQL Server authentication credentials for connecting to the source instance. Required when Windows authentication is disabled or unavailable.\r\nUse Get-Credential to securely prompt for credentials or pass an existing PSCredential object for automated scripts.", "", false, "false", "", "" ], [ "DestinationSqlCredential", "SQL Server authentication credentials for connecting to all destination instances. Used when destination servers require different authentication than the source.\r\nSingle credential object applies to all destinations - use separate commands if different destinations need different credentials.", "", false, "false", "", "" ], [ "XeSession", "Specific Extended Event session names to copy instead of all custom sessions. Accepts arrays of session names for selective migration.\r\nUse this when you only need specific monitoring sessions, such as copying just audit-related sessions to a compliance server or performance sessions to development.", "", false, "false", "", "" ], [ "ExcludeXeSession", "Extended Event session names to exclude from the copy operation. Use this to skip sessions inappropriate for the destination environment.\r\nCommon use cases include excluding production-specific auditing sessions when copying to development or excluding resource-intensive sessions on smaller test servers.", "", false, "false", "", "" ], [ "Force", "Drops and recreates existing Extended Event sessions with matching names on the destination servers. Without this parameter, existing sessions are skipped.\r\nUse this when you need to update session configurations or when consolidating monitoring setups from multiple sources requires overwriting existing sessions.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "ExtendedEvent", "XE", "XEvent" ], "CommandName": "Copy-DbaXESessionTemplate", "Name": "Copy-DbaXESessionTemplate", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Copy-DbaXESessionTemplate [[-Path] \u003cString[]\u003e] [[-Destination] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "None\nThis command copies Extended Event session template files to the destination directory but does not return any objects to the pipeline. Template files are copied based on the filtering criteria \r\n(non-Microsoft templates only by default). Use Write-Message output or monitoring the destination directory to confirm successful completion.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eCopy-DbaXESessionTemplate\nCopies non-Microsoft templates from the dbatools template repository (/bin/XEtemplates/) to $home\\Documents\\SQL Server Management Studio\\Templates\\XEventTemplates.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eCopy-DbaXESessionTemplate -Path C:\\temp\\XEtemplates\nCopies your templates from C:\\temp\\XEtemplates to $home\\Documents\\SQL Server Management Studio\\Templates\\XEventTemplates.", "Description": "Installs curated Extended Event session templates into SQL Server Management Studio\u0027s template directory so you can access them through the SSMS GUI.\nThe templates include common monitoring scenarios like deadlock detection, query performance tracking, connection monitoring, and database health checks.\nOnly copies non-Microsoft templates, preserving any custom templates already in your SSMS directory while adding the community-contributed ones from the dbatools collection.", "Links": "https://dbatools.io/Copy-DbaXESessionTemplate", "Synopsis": "Copies Extended Event session templates from dbatools repository to SSMS template directory for GUI access.", "Availability": "Windows, Linux, macOS", "Params": [ [ "Path", "Specifies the directory containing Extended Event session template files to copy from. Defaults to the dbatools template repository (/bin/XEtemplates/).\r\nUse this when you want to copy templates from a custom directory instead of the built-in dbatools collection, such as organization-specific templates or downloaded templates from other sources.", "", false, "false", "\"$script:PSModuleRoot\\bin\\XEtemplates\"", "" ], [ "Destination", "Specifies the target directory where Extended Event templates will be installed for SSMS access. Defaults to $home\\Documents\\SQL Server Management Studio\\Templates\\XEventTemplates.\r\nUse this when you need to install templates to a different SSMS profile or custom template location, such as when SSMS is installed in a non-standard directory or for shared template repositories.", "", false, "false", "\"$home\\Documents\\SQL Server Management Studio\\Templates\\XEventTemplates\"", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "AG", "HA" ], "CommandName": "Disable-DbaAgHadr", "Name": "Disable-DbaAgHadr", "Author": "Shawn Melton (@wsmelton), wsmelton.github.io", "Syntax": "Disable-DbaAgHadr [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-Credential] \u003cPSCredential\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per successfully processed instance, containing the following properties:\n- ComputerName: The name of the computer hosting the SQL Server instance\r\n- InstanceName: The name of the SQL Server instance (e.g., MSSQLSERVER or named instance)\r\n- SqlInstance: The full SQL Server instance identifier in the format ComputerName\\InstanceName\r\n- IsHadrEnabled: Boolean value indicating the HADR status (always $false for successful disable operations)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eDisable-DbaAgHadr -SqlInstance sql2016\nSets Hadr service to disabled for the instance sql2016 but changes will not be applied until the next time the server restarts.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eDisable-DbaAgHadr -SqlInstance sql2016 -Force\nSets Hadr service to disabled for the instance sql2016, and restart the service to apply the change.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eDisable-DbaAgHadr -SqlInstance sql2012\\dev1 -Force\nSets Hadr service to disabled for the instance dev1 on sq2012, and restart the service to apply the change.", "Description": "Disables the HADR service setting at the SQL Server instance level, effectively removing the instance\u0027s ability to participate in Availability Groups. This is commonly needed when decommissioning servers from AGs, troubleshooting AG setup issues, or converting instances back to standalone operation after removing them from Availability Groups.\n\nThe function modifies the HADR setting through WMI but requires a SQL Server service restart to take effect. Use the -Force parameter to automatically restart both SQL Server and SQL Agent services immediately, or manually restart later to apply the change.", "Links": "https://dbatools.io/Disable-DbaAgHadr", "Synopsis": "Disables High Availability Disaster Recovery (HADR) capability on SQL Server instances.", "Availability": "Windows only", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "Credential", "Credential object used to connect to the Windows server as a different user", "", false, "false", "", "" ], [ "Force", "Automatically restarts both SQL Server and SQL Server Agent services to immediately apply the HADR setting change. Without this switch, the HADR disable setting is changed but requires manual service \r\nrestart to take effect.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "Shows what would happen if the command were to run. No actions are actually performed.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before executing any changing operations within the command.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Certificate", "Security" ], "CommandName": "Disable-DbaDbEncryption", "Name": "Disable-DbaDbEncryption", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Disable-DbaDbEncryption [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-NoEncryptionKeyDrop] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Database\nReturns one Database object for each database where encryption was disabled. The object reflects the database state after TDE was disabled.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The name of the computer where the SQL Server instance is running\r\n- InstanceName: The name of the SQL Server instance\r\n- SqlInstance: The full SQL Server instance name (ComputerName\\InstanceName)\r\n- DatabaseName: The name of the database where encryption was disabled (aliased from Name property)\r\n- EncryptionEnabled: Boolean indicating whether Transparent Data Encryption is enabled (will be $false after execution)\nAdditional properties available from the SMO Database object include all standard database properties such as Owner, Collation, CompatibilityLevel, RecoveryModel, Status, Size, and many others. \r\nAccess these using Select-Object * if needed.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eDisable-DbaDbEncryption -SqlInstance sql2017, sql2016 -Database pubs\nDisables database encryption on the pubs database on sql2017 and sql2016\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eDisable-DbaDbEncryption -SqlInstance sql2017 -Database db1 -Confirm:$false\nSuppresses all prompts to disable database encryption on the db1 database on sql2017\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2017 -Database db1 | Disable-DbaDbEncryption -Confirm:$false\nSuppresses all prompts to disable database encryption on the db1 database on sql2017 (using piping)", "Description": "Disables Transparent Data Encryption (TDE) on specified databases by setting EncryptionEnabled to false and monitoring the decryption process until completion. Since TDE is not fully disabled until the Database Encryption Key (DEK) is removed, this command drops the encryption key by default to complete the decryption process.\n\nThis is commonly used when decommissioning databases that no longer require encryption, migrating databases to environments without TDE requirements, or troubleshooting TDE-related performance issues. The function monitors the decryption state and waits for the database to reach an \"Unencrypted\" state before proceeding with key removal.\n\nUse the -NoEncryptionKeyDrop parameter if you want to disable TDE but retain the encryption key for future use, though the database will remain in a partially encrypted state until the key is manually dropped.", "Links": "https://dbatools.io/Disable-DbaDbEncryption", "Synopsis": "Disables Transparent Data Encryption (TDE) on SQL Server databases and removes encryption keys", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to disable TDE encryption on. Accepts multiple database names as an array.\r\nRequired when using SqlInstance parameter to target specific databases instead of processing all encrypted databases on the instance.", "", false, "false", "", "" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase for pipeline processing. This allows you to filter databases using Get-DbaDatabase criteria before disabling TDE.\r\nUseful when you need to disable encryption on databases that match specific conditions like owner, compatibility level, or encryption status.", "", false, "true (ByValue)", "", "" ], [ "NoEncryptionKeyDrop", "Prevents the Database Encryption Key (DEK) from being automatically dropped after disabling TDE. By default, the function removes the DEK to complete the decryption process.\r\nUse this switch when you need to retain the encryption key for future re-encryption or compliance requirements, though the database will remain in a partially encrypted state until the key is \r\nmanually removed.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "Shows what would happen if the command were to run. No actions are actually performed.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before executing any changing operations within the command.", "cf", false, "false", "", "" ] ] }, { "Tags": "Filestream", "CommandName": "Disable-DbaFilestream", "Name": "Disable-DbaFilestream", "Author": "Stuart Moore (@napalmgram) | Chrissy LeMaire (@cl)", "Syntax": "Disable-DbaFilestream [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL instance showing the FileStream configuration status after the disabling operation completes.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- InstanceAccess: Description of FileStream access level at the instance (should be \"Disabled\" after successful execution)\r\n- ServiceAccess: Description of FileStream access level at the service level (should be \"Disabled\" after successful execution)\r\n- ServiceShareName: The Windows share name used for FileStream data access (if configured)\nAdditional properties available (use Select-Object *):\r\n- InstanceAccessLevel: Numeric instance-level FileStream access level (0 = Disabled, 1 = T-SQL access, 2 = Full access)\r\n- ServiceAccessLevel: Numeric service-level FileStream access level (0 = Disabled, 1 = T-SQL access, 2 = T-SQL and IO streaming, 3 = T-SQL, IO streaming, and remote clients)\r\n- Credential: The Windows credential used to access the server\r\n- SqlCredential: The SQL Server credential used for the connection", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eDisable-DbaFilestream -SqlInstance server1\\instance2\nPrompts for confirmation. Disables filestream on the service and instance levels.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eDisable-DbaFilestream -SqlInstance server1\\instance2 -Confirm:$false\nDoes not prompt for confirmation. Disables filestream on the service and instance levels.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaFilestream -SqlInstance server1\\instance2, server5\\instance5, prod\\hr | Where-Object InstanceAccessLevel -gt 0 | Disable-DbaFilestream -Force\nUsing this pipeline you can scan a range of SQL instances and disable filestream on only those on which it\u0027s enabled.", "Description": "Disables the FileStream feature completely by setting the FilestreamAccessLevel configuration to 0 (disabled) and modifying the corresponding Windows service settings. This is useful when FileStream was previously enabled but is no longer needed, during security hardening, or when troubleshooting FileStream-related issues.\n\nThe function handles both standalone and clustered SQL Server instances, automatically detecting cluster nodes and applying changes across all nodes. Since disabling FileStream requires changes at both the SQL instance configuration level and the Windows service level, a SQL Server service restart is required for the changes to take effect.\n\nBy default, the function will prompt for confirmation before making changes due to the high impact nature of this operation. Use -Force to bypass confirmation and automatically restart the SQL Server service, or run without -Force to make the configuration changes and restart manually later.", "Links": "https://dbatools.io/Disable-DbaFilestream", "Synopsis": "Disables SQL Server FileStream functionality at both the service and instance levels", "Availability": "Windows only", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. Defaults to localhost.", "", true, "true (ByPropertyName)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "true (ByPropertyName)", "", "" ], [ "Credential", "Login to the target server using alternative credentials.", "", false, "true (ByPropertyName)", "", "" ], [ "Force", "Bypasses confirmation prompts and automatically restarts the SQL Server service to apply FileStream configuration changes immediately.\r\nWithout this parameter, the function makes configuration changes but requires you to manually restart the SQL service later for changes to take effect.\r\nUse with caution in production environments as it causes service downtime during the restart.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "Shows what would happen if the command runs. The command is not run unless Force is specified.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before running the command.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Certificate", "Security" ], "CommandName": "Disable-DbaForceNetworkEncryption", "Name": "Disable-DbaForceNetworkEncryption", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Disable-DbaForceNetworkEncryption [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance processed, indicating whether Force Network Encryption was successfully disabled.\nProperties:\r\n- ComputerName: The name of the computer where the SQL Server instance is running\r\n- InstanceName: The name of the SQL Server instance (e.g., MSSQLSERVER, SQL2008R2SP2)\r\n- SqlInstance: The full SQL Server instance identifier in the format ComputerName\\InstanceName\r\n- ForceEncryption: Boolean indicating the current state of Force Encryption setting after the operation (False indicates encryption is not forced)\r\n- CertificateThumbprint: The thumbprint of the certificate assigned to the SQL Server instance for network encryption", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eDisable-DbaForceNetworkEncryption\nDisables Force Encryption on the default (MSSQLSERVER) instance on localhost - requires (and checks for) RunAs admin.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eDisable-DbaForceNetworkEncryption -SqlInstance sql01\\SQL2008R2SP2\nDisables Force Network Encryption for the SQL2008R2SP2 on sql01. Uses Windows Credentials to both login and modify the registry.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eDisable-DbaForceNetworkEncryption -SqlInstance sql01\\SQL2008R2SP2 -WhatIf\nShows what would happen if the command were executed.", "Description": "Modifies the Windows registry to disable Force Network Encryption for SQL Server instances, allowing unencrypted client connections. This is useful when troubleshooting connectivity issues, working with legacy applications that don\u0027t support encryption, or when encryption is handled at the network level. Requires Windows administrator access to the target server and PowerShell remoting. SQL Server service must be restarted for changes to take effect.", "Links": "https://dbatools.io/Disable-DbaForceNetworkEncryption", "Synopsis": "Disables Force Network Encryption setting in SQL Server Configuration Manager", "Availability": "Windows only", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances where Force Network Encryption will be disabled in the Windows registry.\r\nUse this to specify which SQL Server instances need their encryption requirements modified, typically for troubleshooting connectivity issues or supporting legacy applications that don\u0027t support \r\nencrypted connections.\r\nDefaults to localhost.", "", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Specifies Windows credentials for connecting to the target computer to modify registry settings.\r\nThe account must have local administrator privileges on the target server since this function modifies the Windows registry and uses PowerShell remoting.\r\nUse this when your current credentials don\u0027t have the required administrative access to the target machine.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Instance", "Security" ], "CommandName": "Disable-DbaHideInstance", "Name": "Disable-DbaHideInstance", "Author": "Gareth Newman (@gazeranco), ifexists.blog", "Syntax": "Disable-DbaHideInstance [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per instance successfully modified. The object contains the results of disabling the Hide Instance setting.\nProperties:\r\n- ComputerName: The name of the computer where the HideInstance setting was modified\r\n- InstanceName: The SQL Server instance name (e.g., \u0027PROD\u0027, \u0027SQL2008R2SP2\u0027)\r\n- SqlInstance: The full SQL Server instance identifier (computer\\instancename format)\r\n- HideInstance: Boolean indicating if the instance is now hidden ($true) or visible ($false)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eDisable-DbaHideInstance\nDisables Hide Instance of SQL Engine on the default (MSSQLSERVER) instance on localhost. Requires (and checks for) RunAs admin.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eDisable-DbaHideInstance -SqlInstance sql01\\SQL2008R2SP2\nDisables Hide Instance of SQL Engine for the SQL2008R2SP2 on sql01. Uses Windows Credentials to both connect and modify the registry.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eDisable-DbaHideInstance -SqlInstance sql01\\SQL2008R2SP2 -WhatIf\nShows what would happen if the command were executed.", "Description": "Modifies the Windows registry to disable the Hide Instance setting, making SQL Server instances visible to the SQL Server Browser service and network discovery tools. When Hide Instance is enabled, the instance won\u0027t respond to browse requests, which is often used for security hardening but makes instances harder to locate.\n\nThis function directly modifies the HideInstance registry value in HKEY_LOCAL_MACHINE, so you need Windows administrative access to the target server (not SQL Server login credentials). The change takes effect immediately for new connections without requiring a service restart.\n\nThis requires access to the Windows Server and not the SQL Server instance. The setting is found in SQL Server Configuration Manager under the properties of SQL Server Network Configuration \u003e Protocols for \"InstanceName\".", "Links": "https://dbatools.io/Disable-DbaHideInstance", "Synopsis": "Makes SQL Server instances visible to network discovery by disabling the Hide Instance registry setting.", "Availability": "Windows only", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances to make visible to network discovery.\r\nSpecify the server name and instance name (e.g., \u0027SQL01\\PROD\u0027) to unhide specific named instances, or just the server name for default instances.\r\nAccepts multiple instances for bulk operations across your environment.", "", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Windows credentials for accessing the target computer\u0027s registry remotely.\r\nRequired when your current Windows account lacks administrative access to modify the HideInstance registry setting on the remote server.\r\nNote this is for Windows authentication, not SQL Server login credentials, since this function modifies the Windows registry.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "repl", "Replication" ], "CommandName": "Disable-DbaReplDistributor", "Name": "Disable-DbaReplDistributor", "Author": "Jess Pomfret (@jpomfret), jesspomfret.com", "Syntax": "Disable-DbaReplDistributor [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Replication.ReplicationServer\nReturns one ReplicationServer object showing the final state of the distributor after removal is complete. Output is only returned when the target instance is currently configured as a distributor; \r\nif it is not, a terminating error is raised instead.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The name of the computer running the SQL Server instance\r\n- InstanceName: The name of the SQL Server instance\r\n- SqlInstance: The fully qualified SQL Server instance name (ComputerName\\InstanceName)\r\n- IsDistributor: Boolean indicating whether the instance is configured as a distributor (False after successful removal)\r\n- IsPublisher: Boolean indicating whether the instance is configured as a publisher\r\n- DistributionServer: The name of the distribution server (if configured)\r\n- DistributionDatabase: The name of the distribution database (if configured)\nAdditional properties available (from SMO ReplicationServer object):\r\n- AgentCheckupInterval: Interval in seconds for replication agent health checks\r\n- DisruptiveAdministrativeAction: Indicates if a disruptive administrative action was performed\r\n- DistributionDatabases: Collection of distribution databases\r\n- DistributionServerName: Name of the distribution server\r\n- DistributionTables: Collection of distribution tables\r\n- EnabledReplicationAgentProfile: Name of the enabled replication agent profile\r\n- DistributionRetention: Number of days distribution data is retained\r\n- MaxDistributionRetention: Maximum distribution retention in days\r\n- MinDistributionRetention: Minimum distribution retention in days\r\n- PublisherName: Name of the publisher\r\n- SubscriptionCleanupInterval: Interval in seconds for subscription cleanup\nAll properties from the base ReplicationServer object are accessible via Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eDisable-DbaReplDistributor -SqlInstance mssql1\nDisables replication distribution for the mssql1 instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Disable-DbaReplDistributor -SqlInstance mssql1, mssql2 -SqlCredential $cred -Force\nDisables replication distribution for the mssql1 and mssql2 instances using a sql login. Specifies force so the publishing and Distributor configuration at the current server is uninstalled \r\nregardless of whether or not dependent publishing and distribution objects are uninstalled.", "Description": "Removes the distribution database and configuration from SQL Server instances currently acting as replication distributors. This command terminates active connections to distribution databases and uninstalls the distributor role completely. Use this when decommissioning replication, troubleshooting distribution issues, or reconfiguring your replication topology. The Force parameter allows removal even when dependent objects or remote publishers cannot be contacted.", "Links": "https://dbatools.io/Disable-DbaReplDistributor", "Synopsis": "Removes SQL Server replication distribution configuration from target instances.", "Availability": "Windows only", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Force", "Forces removal of the distributor configuration even when dependent replication objects exist or remote publishers cannot be contacted.\r\nUse this when decommissioning a distributor that has orphaned publications or when network connectivity to remote publishers is unavailable.\r\nWithout Force, the command will fail if any local databases are enabled for publishing or if publisher/distribution databases haven\u0027t been cleanly removed first.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "repl", "Replication" ], "CommandName": "Disable-DbaReplPublishing", "Name": "Disable-DbaReplPublishing", "Author": "Jess Pomfret (@jpomfret), jesspomfret.com", "Syntax": "Disable-DbaReplPublishing [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Replication.ReplicationServer\nReturns the ReplicationServer object for each instance after disabling publishing. The instance is returned with its publisher configuration removed from the distributor.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- IsDistributor: Boolean indicating whether this instance is configured as a distributor\r\n- IsPublisher: Boolean indicating whether this instance is configured as a publisher (will be False after successful execution)\r\n- DistributionServer: The name of the server hosting the distribution database\r\n- DistributionDatabase: The name of the distribution database\nAdditional properties available on the ReplicationServer object (accessible via Select-Object *):\r\n- DistributionDatabases: Collection of distribution databases on this distributor\r\n- DistributionPublishers: Collection of publishers registered with this distributor\r\n- Subscribers: Collection of subscribers connected to this distributor\r\n- PublisherDatabases: Collection of databases published from this instance\r\n- SubscriptionServers: Collection of subscription servers\r\n- ConnectionContext: The server connection context used for RMO operations", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eDisable-DbaReplPublishing -SqlInstance mssql1\nDisables replication distribution for the mssql1 instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Disable-DbaReplPublishing -SqlInstance mssql1, mssql2 -SqlCredential $cred -Force\nDisables replication distribution for the mssql1 and mssql2 instances using a sql login.\nSpecifies force so all the replication objects associated with the Publisher are dropped even\r\nif the Publisher is on a remote server that cannot be reached.", "Description": "Removes the publisher role from SQL Server instances that are currently configured for replication publishing. This function safely dismantles the publishing configuration by removing the publisher from the distributor, which stops all publication activity on the target instance. Use this when decommissioning replication setups or troubleshooting publisher configuration issues that require a clean restart.", "Links": "https://dbatools.io/Disable-DbaReplPublishing", "Synopsis": "Disables replication publishing on SQL Server instances and removes publisher configuration.", "Availability": "Windows only", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Force", "Forces the removal of publisher configuration without verifying the distributor connection status.\r\nUse this when the distributor server is unreachable or when you need to forcibly clean up orphaned replication objects.\r\nWithout this switch, the function will fail if it cannot communicate with the distributor to perform proper cleanup verification.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Procedure", "Startup", "StartupProcedure" ], "CommandName": "Disable-DbaStartupProcedure", "Name": "Disable-DbaStartupProcedure", "Author": "Patrick Flynn (@sqllensman)", "Syntax": "Disable-DbaStartupProcedure [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-StartupProcedure] \u003cString[]\u003e] [[-InputObject] \u003cObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.StoredProcedure\nReturns one StoredProcedure object per procedure that was processed, with the Startup property updated and additional status properties added.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: The database containing the stored procedure (always \u0027master\u0027)\r\n- Schema: The schema containing the stored procedure\r\n- Name: The name of the stored procedure\r\n- Startup: Boolean indicating if the procedure will run at SQL Server startup (always $false after successful disable)\r\n- Action: The action performed (\u0027Disable\u0027)\r\n- Status: Boolean indicating if the disable operation succeeded ($true for success, $false for skipped or failed)\r\n- Note: A string message describing the result (\u0027Action Disable already performed\u0027, \u0027Disable succeeded\u0027, \u0027Disable skipped\u0027, or \u0027Disable failed\u0027)\nAdditional properties available (from SMO StoredProcedure object):\r\n- IsSystemObject: Boolean indicating if this is a system object\r\n- CreateDate: DateTime when the procedure was created\r\n- DateLastModified: DateTime when the procedure was last modified\r\n- Text: The T-SQL source code of the stored procedure\r\n- Parent: The Database object containing the procedure\nAll properties from the base SMO StoredProcedure object are accessible via Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eDisable-DbaStartupProcedure -SqlInstance SqlBox1\\Instance2 -StartupProcedure \u0027[dbo].[StartUpProc1]\u0027\nAttempts to clear the automatic execution of the procedure \u0027[dbo].[StartUpProc1]\u0027 in the master database of SqlBox1\\Instance2 when the instance is started.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Disable-DbaStartupProcedure -SqlInstance winserver\\sqlexpress, sql2016 -SqlCredential $cred -StartupProcedure \u0027[dbo].[StartUpProc1]\u0027\nAttempts to clear the automatic execution of the procedure \u0027[dbo].[StartUpProc1]\u0027 in the master database of winserver\\sqlexpress and sql2016 when the instance is started. Connects using sqladmin \r\ncredential\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaStartupProcedure -SqlInstance sql2016 | Disable-DbaStartupProcedure\nGet all startup procedures for the sql2016 instance and disables them by piping to Disable-DbaStartupProcedure", "Description": "Prevents stored procedures from automatically executing when the SQL Server service starts by clearing their startup designation in the master database.\nThis is essential when troubleshooting startup issues or removing procedures that were previously configured to run at service startup.\nEquivalent to running sp_procoption with @OptionValue = off, but provides object-based management with detailed status reporting.\nReturns enhanced SMO StoredProcedure objects showing the action results and current startup status.", "Links": "https://dbatools.io/Disable-DbaStartupProcedure", "Synopsis": "Removes stored procedures from SQL Server\u0027s automatic startup execution list", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "StartupProcedure", "Specifies the stored procedure names to remove from automatic startup execution. Accepts schema-qualified names like \u0027[dbo].[MyStartupProc]\u0027.\r\nUse this when you know the specific procedure names that need their startup designation disabled.", "", false, "false", "", "" ], [ "InputObject", "Accepts stored procedure objects from Get-DbaStartupProcedure via pipeline input.\r\nUse this when working with the results of Get-DbaStartupProcedure to disable multiple startup procedures at once.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Diagnostic", "TraceFlag", "DBCC" ], "CommandName": "Disable-DbaTraceFlag", "Name": "Disable-DbaTraceFlag", "Author": "Garry Bargsley (@gbargsley), blog.garrybargsley.com", "Syntax": "Disable-DbaTraceFlag [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-TraceFlag] \u003cInt32[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per trace flag that was processed. The object contains the status and result of the disable operation.\nProperties:\r\n- SourceServer: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance format)\r\n- TraceFlag: The trace flag number that was disabled or skipped\r\n- Status: The result of the operation (Successful, Skipped, or Failed)\r\n- Notes: Additional details about the operation result or error message\r\n- DateTime: Timestamp of when the operation was executed", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eDisable-DbaTraceFlag -SqlInstance sql2016 -TraceFlag 3226\nDisable the globally running trace flag 3226 on SQL Server instance sql2016", "Description": "Turns off trace flags that are currently enabled globally across SQL Server instances using DBCC TRACEOFF.\nUseful when you need to disable diagnostic trace flags that were enabled for troubleshooting or testing without requiring a restart.\nOnly affects flags currently running in memory - does not modify startup parameters or persistent trace flag settings.\nUse Set-DbaStartupParameter to manage trace flags that persist after restarts.", "Links": "https://dbatools.io/Disable-DbaTraceFlag", "Synopsis": "Disables globally running trace flags on SQL Server instances", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "TraceFlag", "Specifies the trace flag numbers to disable globally across all sessions on the SQL Server instance.\r\nOnly trace flags that are currently running will be disabled - flags not currently active are skipped with a warning.\r\nSupports multiple trace flag numbers to disable several flags in a single operation.", "", true, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "Shows what would happen if the command were to run. No actions are actually performed.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before executing any changing operations within the command.", "cf", false, "false", "", "" ] ] }, { "Tags": "Connection", "CommandName": "Disconnect-DbaInstance", "Name": "Disconnect-DbaInstance", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Disconnect-DbaInstance [[-InputObject] \u003cPSObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per connection successfully disconnected. Contains the following properties:\nDefault display properties (via Select-DefaultView):\r\n- SqlInstance: The name of the SQL Server instance that was disconnected\r\n- ConnectionType: The full type name of the connection object (e.g., Microsoft.SqlServer.Management.Smo.Server or System.Data.SqlClient.SqlConnection)\r\n- State: The state of the connection after disconnection (Disconnected or Closed)\nAdditional properties available:\r\n- ConnectionString: The masked/hidden connection string used for the connection", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaConnectedInstance | Disconnect-DbaInstance\nDisconnects all connected instances\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaConnectedInstance | Out-GridView -Passthru | Disconnect-DbaInstance\nDisconnects selected SQL Server instances\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$server = Connect-DbaInstance -SqlInstance sql01\nPS C:\\\u003e $server | Disconnect-DbaInstance\nDisconnects the $server connection", "Description": "Properly closes SQL Server connections created by dbatools commands like Connect-DbaInstance, preventing connection leaks and freeing up server connection limits. This function handles both SMO server objects and raw SqlConnection objects, ensuring clean disconnection and removing connections from the internal connection hash. Use this in scripts to explicitly manage connection lifecycle, especially when working with multiple instances or in long-running automation where connection limits matter.\n\nTo clear all of your connection pools, use Clear-DbaConnectionPool", "Links": "https://dbatools.io/Disconnect-DbaInstance", "Synopsis": "Closes active SQL Server connections and removes them from the dbatools connection cache", "Availability": "Windows, Linux, macOS", "Params": [ [ "InputObject", "Specifies the SQL Server connection object(s) to disconnect, such as SMO Server objects or SqlConnection objects from Connect-DbaInstance. Accepts pipeline input from Get-DbaConnectedInstance to \r\ndisconnect multiple connections at once.\r\nUse this to explicitly close specific connections rather than letting them time out, which helps prevent connection pool exhaustion and reduces load on SQL Server instances.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "Shows what would happen if the command were to run. No actions are actually performed.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before executing any changing operations within the command.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Detach", "Database" ], "CommandName": "Dismount-DbaDatabase", "Name": "Dismount-DbaDatabase", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Dismount-DbaDatabase [-SqlCredential \u003cPSCredential\u003e] [-UpdateStatistics] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nDismount-DbaDatabase -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] -Database \u003cString[]\u003e [-UpdateStatistics] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nDismount-DbaDatabase [-SqlCredential \u003cPSCredential\u003e] -InputObject \u003cDatabase[]\u003e [-UpdateStatistics] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "Detach-DbaDatabase", "Outputs": "PSCustomObject\nReturns one object per successfully detached database with the following properties:\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance format)\r\n- Database: The name of the database that was detached\r\n- DatabaseID: The unique identifier of the detached database\r\n- DetachResult: Status of the detach operation (Success)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eDetach-DbaDatabase -SqlInstance sql2016b -Database SharePoint_Config, WSS_Logging\nDetaches SharePoint_Config and WSS_Logging from sql2016b\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2016b -Database \u0027PerformancePoint Service Application_10032db0fa0041df8f913f558a5dc0d4\u0027 | Detach-DbaDatabase -Force\nDetaches \u0027PerformancePoint Service Application_10032db0fa0041df8f913f558a5dc0d4\u0027 from sql2016b. Since Force was specified, if the database is part of mirror, the mirror will be broken prior to \r\ndetaching.\nIf the database is part of an Availability Group, it will first be dropped prior to detachment.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2016b -Database WSS_Logging | Detach-DbaDatabase -Force -WhatIf\nShows what would happen if the command were to execute (without actually executing the detach/break/remove commands).", "Description": "Safely detaches databases from SQL Server instances while performing comprehensive validation checks before detachment. This function automatically validates that databases aren\u0027t system databases, replicated, or have active snapshots, preventing common detachment failures. When databases are part of mirroring or Availability Groups, the -Force parameter allows automatic cleanup by breaking mirrors and removing databases from AGs before detaching. Active user connections can also be forcibly terminated when needed. This command is essential for database migration scenarios, decommissioning databases, or moving databases between instances without using backup/restore methods.", "Links": "https://dbatools.io/Dismount-DbaDatabase", "Synopsis": "Detaches one or more databases from a SQL Server instance with built-in safety checks and validation.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies the name(s) of databases to detach from the SQL Server instance. Accepts wildcards for pattern matching.\r\nUse this when you need to detach specific databases by name rather than passing database objects through the pipeline.", "", true, "false", "", "" ], [ "InputObject", "Accepts database objects from the pipeline for detachment operations. Typically used with Get-DbaDatabase output.\r\nThis allows you to filter and select databases using Get-DbaDatabase before detaching them, providing more control over the selection process.", "", true, "true (ByValue)", "", "" ], [ "UpdateStatistics", "Updates database statistics before detaching the database to ensure optimal performance if the database is later reattached.\r\nUse this when you plan to reattach the database later and want to maintain current statistics for query optimization.", "", false, "false", "False", "" ], [ "Force", "Bypasses safety checks and handles blocking conditions that prevent database detachment. Automatically breaks database mirroring, removes databases from Availability Groups, and terminates active \r\nuser connections.\r\nUse this when you need to detach databases that are part of high availability configurations or have active connections that cannot be closed gracefully.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "AG", "HA" ], "CommandName": "Enable-DbaAgHadr", "Name": "Enable-DbaAgHadr", "Author": "Shawn Melton (@wsmelton), wsmelton.github.io", "Syntax": "Enable-DbaAgHadr [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-Credential] \u003cPSCredential\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance with the status of the HADR setting after the operation.\nProperties:\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance or instance for default)\r\n- IsHadrEnabled: Boolean indicating if HADR is now enabled (always $true on successful completion)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eEnable-DbaAgHadr -SqlInstance sql2016\nSets Hadr service to enabled for the instance sql2016 but changes will not be applied until the next time the server restarts.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eEnable-DbaAgHadr -SqlInstance sql2016 -Force\nSets Hadr service to enabled for the instance sql2016, and restart the service to apply the change.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eEnable-DbaAgHadr -SqlInstance sql2012\\dev1 -Force\nSets Hadr service to disabled for the instance dev1 on sq2012, and restart the service to apply the change.", "Description": "Configures the High Availability Disaster Recovery (HADR) service setting on SQL Server instances, which is a required prerequisite before you can create Availability Groups. This setting must be enabled at the instance level and requires a service restart to take effect. Use this command when preparing SQL Server instances for Availability Group participation after your Windows Server Failover Cluster is already configured.", "Links": "https://dbatools.io/Enable-DbaAgHadr", "Synopsis": "Enables HADR service setting on SQL Server instances to allow Availability Group creation.", "Availability": "Windows only", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "Credential", "Windows credential object used to connect to the target server with different authentication context.\r\nRequired when the current user lacks administrative privileges on the SQL Server host or when connecting across domain boundaries.", "", false, "false", "", "" ], [ "Force", "Automatically restarts the SQL Server Database Engine and SQL Server Agent services to immediately apply the HADR setting change.\r\nWithout this parameter, the HADR setting change requires a manual service restart before Availability Groups can be created.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "Shows what would happen if the command were to run. No actions are actually performed.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before executing any changing operations within the command.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Certificate", "Security" ], "CommandName": "Enable-DbaDbEncryption", "Name": "Enable-DbaDbEncryption", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Enable-DbaDbEncryption [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-EncryptorName] \u003cString\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Database\nReturns one Database object per database where encryption was enabled successfully.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- DatabaseName: The name of the database where encryption was enabled (Name property aliased)\r\n- EncryptionEnabled: Boolean indicating whether Transparent Data Encryption is now enabled on the database\nAdditional properties available (from SMO Database object):\r\n- CreateDate: DateTime when the database was created\r\n- LastBackupDate: DateTime of the last database backup\r\n- Owner: Database owner/principal name\r\n- RecoveryModel: Database recovery model (Simple, Full, BulkLogged)\r\n- Status: Current database status\r\n- Size: Database size in megabytes\r\n- DatabaseEncryptionKey: The Database Encryption Key object containing encryption details\r\n- EncryptionAlgorithm: The algorithm used for encryption (AES_128, AES_192, AES_256)\nAll properties from the base SMO Database object are accessible even though only default properties are displayed without using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eEnable-DbaDbEncryption -SqlInstance sql2017, sql2016 -Database pubs\nEnables database encryption on the pubs database on sql2017 and sql2016\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eEnable-DbaDbEncryption -SqlInstance sql2017 -Database db1 -Confirm:$false\nSuppresses all prompts to enable database encryption on the db1 database on sql2017\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2017 -Database db1 | Enable-DbaDbEncryption -Confirm:$false\nSuppresses all prompts to enable database encryption on the db1 database on sql2017", "Description": "Enables Transparent Data Encryption (TDE) on specified databases to protect data at rest. This is essential for compliance with regulations like HIPAA, PCI-DSS, and organizational security policies. The function automatically creates a Database Encryption Key (DEK) if one doesn\u0027t exist, using a certificate from the master database to encrypt it. By default, it verifies that the certificate has been backed up before proceeding, helping prevent data loss scenarios.", "Links": "https://dbatools.io/Enable-DbaDbEncryption", "Synopsis": "Enables Transparent Data Encryption (TDE) on SQL Server databases", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to enable Transparent Data Encryption (TDE) on. Accepts multiple database names.\r\nUse this when you need to enable encryption on specific databases rather than all databases on the instance.", "", false, "false", "", "" ], [ "EncryptorName", "Specifies the certificate name in the master database to use for encrypting the Database Encryption Key (DEK).\r\nIf not specified, the function will attempt to find an existing certificate. Use this when you have multiple certificates and need to specify which one to use for TDE.\r\nThe certificate must exist in the master database and should be backed up to prevent data loss.", "Certificate,CertificateName", false, "false", "", "" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase through the pipeline.\r\nUse this when you want to filter databases first with Get-DbaDatabase and then enable TDE on the results.", "", false, "true (ByValue)", "", "" ], [ "Force", "Bypasses the certificate backup verification check and enables TDE even if the certificate hasn\u0027t been backed up.\r\nUse with extreme caution as this could lead to data loss if the certificate is lost without a backup.\r\nOnly use this in development environments or when you have confirmed the certificate is backed up through other means.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "Shows what would happen if the command were to run. No actions are actually performed.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before executing any changing operations within the command.", "cf", false, "false", "", "" ] ] }, { "Tags": "Filestream", "CommandName": "Enable-DbaFilestream", "Name": "Enable-DbaFilestream", "Author": "Stuart Moore (@napalmgram) | Chrissy LeMaire (@cl)", "Syntax": "Enable-DbaFilestream [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [[-FileStreamLevel] \u003cString\u003e] [[-ShareName] \u003cString\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance with the current FILESTREAM configuration status after the configuration change is applied (or would be applied with -WhatIf).\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The name of the computer hosting the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance identifier (ComputerName\\InstanceName)\r\n- InstanceAccess: Human-readable description of the instance-level FILESTREAM access level (Disabled, T-SQL access enabled, or Full access enabled)\r\n- ServiceAccess: Human-readable description of the service-level FILESTREAM access level (Disabled, FileStream enabled for T-SQL access, FileStream enabled for T-SQL and IO streaming access, or \r\nFileStream enabled for T-SQL, IO streaming, and remote clients)\r\n- ServiceShareName: The Windows file share name used for FILESTREAM remote client access, if configured\nAdditional properties available (not displayed by default):\r\n- InstanceAccessLevel: Numeric value representing instance-level access (0 = Disabled, 1 = T-SQL access enabled, 2 = Full access enabled)\r\n- ServiceAccessLevel: Numeric value representing service-level access (0 = Disabled, 1 = T-SQL only, 2 = T-SQL and IO streaming, 3 = T-SQL, IO streaming, and remote clients)\r\n- SqlCredential: The SQL Server credentials used for the connection\r\n- Credential: The Windows credentials used for the connection\nAll properties are accessible via Select-Object * if needed beyond the default display.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eEnable-DbaFilestream -SqlInstance server1\\instance2 -FileStreamLevel TSql\nPS C:\\\u003e Enable-DbaFilestream -SqlInstance server1\\instance2 -FileStreamLevel 1\nThese commands are functionally equivalent, both will set Filestream level on server1\\instance2 to T-Sql Only\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaFilestream -SqlInstance server1\\instance2, server5\\instance5, prod\\hr | Where-Object InstanceAccessLevel -eq 0 | Enable-DbaFilestream -FileStreamLevel TSqlIoStreamingRemoteClient -Force\nUsing this pipeline you can scan a range of SQL instances and enable filestream on only those on which it\u0027s disabled.", "Description": "Configures SQL Server\u0027s FILESTREAM feature by setting the FilestreamAccessLevel at the instance level and enabling the Windows service component at the server level. The function supports three access levels: T-SQL only, T-SQL with I/O streaming, or T-SQL with I/O streaming and remote client access. FILESTREAM allows storing large binary data like documents, images, and videos directly on the file system while maintaining transactional consistency with the database. SQL Server requires a restart after enabling FILESTREAM, and the function will prompt for confirmation unless the -Force parameter is used.", "Links": "https://dbatools.io/Enable-DbaFilestream", "Synopsis": "Configures FILESTREAM feature at both instance and server levels on SQL Server", "Availability": "Windows only", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. Defaults to localhost.", "", true, "true (ByPropertyName)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "true (ByPropertyName)", "", "" ], [ "Credential", "Login to the target server using alternative credentials.", "", false, "true (ByPropertyName)", "", "" ], [ "FileStreamLevel", "Specifies the access level for FILESTREAM functionality on the SQL Server instance. Controls how applications can access FILESTREAM data stored on the file system.\r\nUse level 1 (TSql) for basic database operations, level 2 (TSqlIoStreaming) when applications need direct file system access, or level 3 (TSqlIoStreamingRemoteClient) for remote client access \r\nscenarios.\r\nAccepts numeric values (1, 2, 3) or string equivalents (TSql, TSqlIoStreaming, TSqlIoStreamingRemoteClient). Defaults to level 1.", "", false, "false", "1", "TSql,TSqlIoStreaming,TSqlIoStreamingRemoteClient,1,2,3" ], [ "ShareName", "Specifies the Windows file share name used by remote clients to access FILESTREAM data over the network. Only applies when FileStreamLevel is set to 2 or 3.\r\nUse this when you need to customize the share name for organizational standards or security requirements. If not specified, SQL Server uses the default instance name as the share name.", "", false, "false", "", "" ], [ "Force", "Automatically restarts the SQL Server service after enabling FILESTREAM without prompting for confirmation. Required for FILESTREAM changes to take effect immediately.\r\nUse with caution in production environments as it will cause brief service interruption. Without this parameter, you must manually restart SQL Server for changes to apply.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "Shows what would happen if the command runs. The command is not run unless Force is specified.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before running the command.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Certificate", "Encryption", "Security" ], "CommandName": "Enable-DbaForceNetworkEncryption", "Name": "Enable-DbaForceNetworkEncryption", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Enable-DbaForceNetworkEncryption [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance where Force Encryption was enabled.\nProperties:\r\n- ComputerName: The name of the computer where the SQL Server instance is running\r\n- InstanceName: The SQL Server instance name (e.g., SQL2008R2SP2)\r\n- SqlInstance: The full SQL Server instance identifier (computer\\instance format)\r\n- ForceEncryption: Boolean indicating whether Force Encryption was successfully enabled (will be $true on successful execution)\r\n- CertificateThumbprint: The thumbprint of the SSL certificate configured for the instance, or $null if no certificate is configured", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eEnable-DbaForceNetworkEncryption\nEnables Force Encryption on the default (MSSQLSERVER) instance on localhost. Requires (and checks for) RunAs admin.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eEnable-DbaForceNetworkEncryption -SqlInstance sql01\\SQL2008R2SP2\nEnables Force Network Encryption for the SQL2008R2SP2 on sql01. Uses Windows Credentials to both connect and modify the registry.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eEnable-DbaForceNetworkEncryption -SqlInstance sql01\\SQL2008R2SP2 -WhatIf\nShows what would happen if the command were executed.", "Description": "Modifies the Windows registry to force all client connections to SQL Server to use encryption, regardless of the client\u0027s encryption settings. This security feature ensures that all data transmitted between clients and SQL Server is encrypted, protecting against network eavesdropping and man-in-the-middle attacks.\n\nThis function operates at the Windows level by updating the ForceEncryption registry value in the SQL Server network configuration, which normally requires manual changes through SQL Server Configuration Manager. The setting applies to all protocols and client connections to the specified instance.\n\nImportant: You must restart the SQL Server service after running this command for the encryption requirement to take effect. Requires Windows administrator privileges on the target server, not SQL Server permissions.", "Links": "https://dbatools.io/Enable-DbaForceNetworkEncryption", "Synopsis": "Configures SQL Server to require encrypted connections from all clients by modifying the Windows registry", "Availability": "Windows only", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Windows credentials for connecting to the remote computer to modify registry settings. Required when the current user lacks administrative access to the target server.\r\nThis is used for Windows authentication to the computer, not SQL Server login credentials.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Instance", "Security" ], "CommandName": "Enable-DbaHideInstance", "Name": "Enable-DbaHideInstance", "Author": "Gareth Newman (@gazeranco), ifexists.blog", "Syntax": "Enable-DbaHideInstance [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance processed, with information about the Hide Instance setting change.\nProperties:\r\n- ComputerName: The name of the computer where the registry change was made\r\n- InstanceName: The SQL Server instance name (e.g., MSSQLSERVER, SQL2008R2SP2)\r\n- SqlInstance: The full SQL Server instance identifier (computer\\instance format)\r\n- HideInstance: Boolean indicating whether the Hide Instance setting was successfully enabled (true) or not (false)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eEnable-DbaHideInstance\nEnables Hide Instance of SQL Engine on the default (MSSQLSERVER) instance on localhost. Requires (and checks for) RunAs admin.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eEnable-DbaHideInstance -SqlInstance sql01\\SQL2008R2SP2\nEnables Hide Instance of SQL Engine for the SQL2008R2SP2 on sql01. Uses Windows Credentials to both connect and modify the registry.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eEnable-DbaHideInstance -SqlInstance sql01\\SQL2008R2SP2 -WhatIf\nShows what would happen if the command were executed.", "Description": "Enables the Hide Instance setting in the SQL Server network configuration registry, which prevents the instance from responding to SQL Server Browser service enumeration requests. This security setting makes the instance invisible to network discovery tools and requires clients to specify the exact port number or use a SQL Server alias to connect.\n\nThe function modifies the HideInstance registry value in HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft SQL Server\\[InstanceName]\\MSSQLServer\\SuperSocketNetLib. This is commonly used in security-hardened environments to reduce the attack surface by hiding instance details from network scanning tools.\n\nThis setting requires Windows administrative access to modify the registry and does not require SQL Server permissions. The change takes effect immediately for new connections, but existing connections remain unaffected.", "Links": "https://dbatools.io/Enable-DbaHideInstance", "Synopsis": "Enables the Hide Instance setting to prevent SQL Server Browser service from advertising the instance.", "Availability": "Windows only", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances where you want to enable the Hide Instance setting.\r\nThis parameter accepts server names, server\\instance combinations, or fully qualified domain names.\r\nWhen not specified, defaults to the local computer\u0027s default instance (MSSQLSERVER).", "", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Windows credentials used to connect to the target computer and modify the registry settings.\r\nThis is required when running against remote servers where your current Windows account lacks administrative access.\r\nNote that this connects to the Windows computer, not the SQL Server instance itself.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "repl", "Replication" ], "CommandName": "Enable-DbaReplDistributor", "Name": "Enable-DbaReplDistributor", "Author": "Jess Pomfret (@jpomfret), jesspomfret.com", "Syntax": "Enable-DbaReplDistributor [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-DistributionDatabase] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Replication.ReplicationServer\nReturns one ReplicationServer object per instance configured as a distributor. The object shows the distributor configuration and replication server role details after enabling distribution.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- IsDistributor: Boolean indicating whether the instance is configured as a distributor\r\n- IsPublisher: Boolean indicating whether the instance is configured as a publisher\r\n- DistributionServer: Name of the distribution server\r\n- DistributionDatabase: Name of the distribution database that stores replication metadata\nAdditional properties available (from SMO ReplicationServer object):\r\n- DistributionDatabases: Collection of distribution databases configured on the distributor\r\n- DistributorSecurity: Distribution agent credentials and security settings\r\n- LocalPublisher: Boolean indicating if this server can function as a local publisher\r\n- PublisherIdentity: Identity of the publisher\r\n- ReplicationDatabases: Collection of databases enabled for replication on this instance\r\n- SubscriptionServers: List of subscription servers\r\n- ThirdPartySubscribers: Information about non-SQL Server subscribers\nAll properties from the base SMO ReplicationServer object are accessible even though only default properties are displayed without using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eEnable-DbaReplDistributor -SqlInstance mssql1\nEnables distribution for the mssql1 instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eEnable-DbaReplDistributor -SqlInstance mssql1 -DistributionDatabase repDatabase\nEnables distribution for the mssql1 instance and names the distribution database repDatabase.", "Description": "Configures the specified SQL Server instance to act as a replication distributor by creating the distribution database and installing the distributor role. This is the first step in setting up SQL Server replication, as the distributor manages the flow of replicated transactions between publishers and subscribers. Once configured, the instance can store replication metadata, track publication and subscription information, and coordinate data movement for transactional and snapshot replication scenarios.", "Links": "https://dbatools.io/Enable-DbaReplDistributor", "Synopsis": "Configures a SQL Server instance as a replication distributor with distribution database", "Availability": "Windows only", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "DistributionDatabase", "Specifies the name of the distribution database that will be created to store replication metadata and transaction logs.\r\nThis database holds subscription information, publication details, and queued transactions for distribution to subscribers.\r\nDefaults to \u0027distribution\u0027 if not specified, which is the standard convention for most replication configurations.", "", false, "false", "distribution", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "repl", "Replication" ], "CommandName": "Enable-DbaReplPublishing", "Name": "Enable-DbaReplPublishing", "Author": "Jess Pomfret (@jpomfret), jesspomfret.com", "Syntax": "Enable-DbaReplPublishing [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-SnapshotShare] \u003cString\u003e] [[-PublisherSqlLogin] \u003cPSCredential\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Replication.ReplicationServer\nReturns one ReplicationServer object per instance specified, representing the publisher configuration. The object is refreshed after the publishing configuration is created, reflecting the updated \r\nreplication state.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The name of the computer hosting the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- IsDistributor: Boolean indicating whether this instance is configured as a distributor\r\n- IsPublisher: Boolean indicating whether this instance is configured as a publisher (should be True after this command completes)\r\n- DistributionServer: The name of the server configured as the distributor\r\n- DistributionDatabase: The name of the distribution database\nAdditional properties available (from SMO ReplicationServer object):\r\n- DistributionDatabases: Collection of distribution databases configured on the instance\r\n- PublisherConnections: Collection of publishers configured on the distributor\r\n- Distributors: Collection of distributors configured on this instance\r\n- RegisteredSubscribers: Collection of registered subscribers\r\n- Publishers: Collection of publishers configured on the distributor\nAll properties from the base SMO ReplicationServer object are accessible through Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eEnable-DbaReplPublishing -SqlInstance SqlBox1\\Instance2\nEnables replication publishing for instance SqlBox1\\Instance2 using Windows Auth and the default InstallDataDirectory\\ReplData as the snapshot folder", "Description": "Configures a SQL Server instance to publish data for replication by creating the necessary publisher configuration on an existing distributor. This is typically the second step in setting up SQL Server replication, after the distributor has been configured with Enable-DbaReplDistributor. The function sets up the snapshot working directory, configures publisher security authentication, and registers the instance as a publisher with the distribution database. The target instance must already be configured as a distributor before running this command.", "Links": "https://dbatools.io/Enable-DbaReplPublishing", "Synopsis": "Configures a SQL Server instance as a replication publisher on an existing distributor.", "Availability": "Windows only", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "SnapshotShare", "Specifies the network share path where replication snapshot files will be stored and accessed by subscribers.\r\nUse this when you need snapshot files in a specific location for network access or storage requirements.\r\nDefaults to InstallDataDirectory\\ReplData if not specified.", "", false, "false", "", "" ], [ "PublisherSqlLogin", "SQL Server login credentials to use for publisher security authentication instead of Windows Authentication.\r\nUse this when the distributor and publisher are in different domains or when Windows Authentication is not available.\r\nWindows Authentication is used by default and is the recommended method for security.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Procedure", "Startup", "StartupProcedure" ], "CommandName": "Enable-DbaStartupProcedure", "Name": "Enable-DbaStartupProcedure", "Author": "Patrick Flynn (@sqllensman)", "Syntax": "Enable-DbaStartupProcedure [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-StartupProcedure] \u003cObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.StoredProcedure\nReturns one StoredProcedure object per procedure that was processed, with the Startup property updated and additional status properties added.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: The database containing the stored procedure (always \u0027master\u0027)\r\n- Schema: The schema containing the stored procedure\r\n- Name: The name of the stored procedure\r\n- Startup: Boolean indicating if the procedure will run at SQL Server startup (always $true after successful enable)\r\n- Action: The action performed (\u0027Enable\u0027)\r\n- Status: Boolean indicating if the enable operation succeeded ($true for success, $false for skipped or failed)\r\n- Note: A string message describing the result (\u0027Action Enable already performed\u0027, \u0027Enable succeeded\u0027, \u0027Enable skipped\u0027, or \u0027Enable failed\u0027)\nAdditional properties available (from SMO StoredProcedure object):\r\n- IsSystemObject: Boolean indicating if this is a system object\r\n- CreateDate: DateTime when the procedure was created\r\n- DateLastModified: DateTime when the procedure was last modified\r\n- Text: The T-SQL source code of the stored procedure\r\n- Parent: The Database object containing the procedure\nAll properties from the base SMO StoredProcedure object are accessible via Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eEnable-DbaStartupProcedure -SqlInstance SqlBox1\\Instance2 -StartupProcedure \u0027[dbo].[StartUpProc1]\u0027\nAttempts to set the procedure \u0027[dbo].[StartUpProc1]\u0027 in the master database of SqlBox1\\Instance2 for automatic execution when the instance is started.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Enable-DbaStartupProcedure -SqlInstance winserver\\sqlexpress, sql2016 -SqlCredential $cred -StartupProcedure \u0027[dbo].[StartUpProc1]\u0027\nAttempts to set the procedure \u0027[dbo].[StartUpProc1]\u0027 in the master database of winserver\\sqlexpress and sql2016 for automatic execution when the instance is started. Connects using sqladmin credential", "Description": "Marks stored procedures in the master database for automatic execution during SQL Server startup, eliminating the need to manually run initialization scripts after service restarts.\nThis is essential for DBAs who need to ensure critical maintenance procedures, monitoring setup, or custom configurations are applied consistently every time the instance starts.\nThe function modifies the procedure\u0027s Startup property using SMO, which is equivalent to running sp_procoption with @OptionValue = \u0027on\u0027.\nReturns detailed information about each procedure processed, including success status and any error conditions encountered.", "Links": "https://dbatools.io/Enable-DbaStartupProcedure", "Synopsis": "Configures stored procedures in the master database to execute automatically when SQL Server service starts", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "StartupProcedure", "Specifies the stored procedure(s) in the master database to enable for automatic startup execution. Accepts schema-qualified names like \u0027[dbo].[MyStartupProc]\u0027 or simple names.\r\nUse this when you need specific procedures to run automatically after SQL Server service restarts, such as initialization scripts, monitoring setup, or custom configuration procedures.\r\nMultiple procedures can be specified as an array to enable several startup procedures in a single operation.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Diagnostic", "TraceFlag", "DBCC" ], "CommandName": "Enable-DbaTraceFlag", "Name": "Enable-DbaTraceFlag", "Author": "Garry Bargsley (@gbargsley), blog.garrybargsley.com", "Syntax": "Enable-DbaTraceFlag [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-TraceFlag] \u003cInt32[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per trace flag operation, indicating the result of enabling each trace flag.\nProperties:\r\n- SourceServer: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name (service name)\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- TraceFlag: The trace flag number that was enabled or attempted\r\n- Status: The operation status (Successful, Skipped, or Failed)\r\n - Successful: Trace flag was successfully enabled\r\n - Skipped: Trace flag was already enabled globally\r\n - Failed: An error occurred while enabling the trace flag\r\n- Notes: Additional information about the operation result or error message\r\n- DateTime: Timestamp when the operation was executed", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eEnable-DbaTraceFlag -SqlInstance sql2016 -TraceFlag 3226\nEnable the trace flag 3226 on SQL Server instance sql2016\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eEnable-DbaTraceFlag -SqlInstance sql2016 -TraceFlag 1117, 1118\nEnable multiple trace flags on SQL Server instance sql2016", "Description": "Activates trace flags at the global level using DBCC TRACEON, affecting all connections and sessions on the target SQL Server instances.\nCommonly used for troubleshooting performance issues, enabling specific SQL Server behaviors, or applying recommended trace flags for your environment.\nChanges take effect immediately but are lost after a SQL Server restart - use Set-DbaStartupParameter to make trace flags persistent across restarts.\nThe function automatically checks for already-enabled trace flags to prevent duplicate operations.", "Links": "https://dbatools.io/Enable-DbaTraceFlag", "Synopsis": "Enables one or more trace flags globally on SQL Server instances", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "TraceFlag", "Specifies one or more trace flag numbers to enable globally across all sessions on the SQL Server instance.\r\nUse specific trace flag numbers like 3226 (suppress backup log messages), 1117/1118 (tempdb optimization), or 4199 (query optimizer fixes).\r\nMultiple trace flags can be specified as an array to enable several flags in a single operation.", "", true, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "Shows what would happen if the command were to run. No actions are actually performed.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before executing any changing operations within the command.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Storage", "LogFile" ], "CommandName": "Expand-DbaDbLogFile", "Name": "Expand-DbaDbLogFile", "Author": "Claudio Silva (@ClaudioESSilva)", "Syntax": "Expand-DbaDbLogFile [-SqlInstance] \u003cDbaInstanceParameter\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-TargetLogSize] \u003cInt32\u003e [[-IncrementSize] \u003cInt32\u003e] [-TargetVlfCount \u003cInt32\u003e] [[-LogFileId] \u003cInt32\u003e] [-ExcludeDiskSpaceValidation] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nExpand-DbaDbLogFile [-SqlInstance] \u003cDbaInstanceParameter\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-TargetLogSize] \u003cInt32\u003e [[-IncrementSize] \u003cInt32\u003e] [-TargetVlfCount \u003cInt32\u003e] [[-LogFileId] \u003cInt32\u003e] [-ShrinkLogFile] [-ShrinkSize] \u003cInt32\u003e [[-BackupDirectory] \u003cString\u003e] [-ExcludeDiskSpaceValidation] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database processed containing the results of the log file expansion operation.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (ComputerName\\InstanceName)\r\n- Database: The name of the database whose log file was expanded\r\n- DatabaseID: The unique identifier of the database\r\n- ID: The file ID of the transaction log file\r\n- Name: The logical name of the transaction log file\r\n- InitialSize: The size of the log file at the start of the operation (displayed as formatted size)\r\n- CurrentSize: The size of the log file after expansion to target size (displayed as formatted size)\r\n- InitialVLFCount: The number of Virtual Log Files (VLFs) before the expansion operation\r\n- CurrentVLFCount: The number of Virtual Log Files (VLFs) after the expansion operation\nAdditional properties available:\r\n- LogFileCount: The total number of log files for the database (available with Select-Object *)\nAll properties are accessible via Select-Object * or by accessing individual properties on the returned object.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eExpand-DbaDbLogFile -SqlInstance sqlcluster -Database db1 -TargetLogSize 50000\nGrows the transaction log for database db1 on sqlcluster to 50000 MB and calculates the increment size.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eExpand-DbaDbLogFile -SqlInstance sqlcluster -Database db1, db2 -TargetLogSize 10000 -IncrementSize 200\nGrows the transaction logs for databases db1 and db2 on sqlcluster to 1000MB and sets the growth increment to 200MB.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eExpand-DbaDbLogFile -SqlInstance sqlcluster -Database db1 -TargetLogSize 10000 -LogFileId 9\nGrows the transaction log file with FileId 9 of the db1 database on sqlcluster instance to 10000MB.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eExpand-DbaDbLogFile -SqlInstance sqlcluster -Database (Get-Content D:\\DBs.txt) -TargetLogSize 50000\nGrows the transaction log of the databases specified in the file \u0027D:\\DBs.txt\u0027 on sqlcluster instance to 50000MB.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eExpand-DbaDbLogFile -SqlInstance SqlInstance -Database db1,db2 -TargetLogSize 100 -IncrementSize 10 -ShrinkLogFile -ShrinkSize 10 -BackupDirectory R:\\MSSQL\\Backup\nGrows the transaction logs for databases db1 and db2 on SQL server SQLInstance to 100MB, sets the incremental growth to 10MB, shrinks the transaction log to 10MB and uses the directory \r\nR:\\MSSQL\\Backup for the required backups.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eExpand-DbaDbLogFile -SqlInstance sqlcluster -Database db1 -TargetLogSize 10000 -TargetVlfCount 16\nGrows the transaction log for database db1 on sqlcluster to 10000MB and automatically calculates an increment size that keeps the total VLF count at or below 16.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eExpand-DbaDbLogFile -SqlInstance sqlcluster -Database db1 -TargetLogSize 10000 -ShrinkLogFile -ShrinkSize 10 -BackupDirectory R:\\MSSQL\\Backup -TargetVlfCount 8\nShrinks the transaction log for db1 to 10MB, then re-grows it to 10000MB using an increment size calculated to keep the final VLF count at or below 8.", "Description": "This function intelligently grows transaction log files to target sizes while minimizing Virtual Log File (VLF) fragmentation. It calculates optimal increment sizes based on your SQL Server version and target log size, then grows the log in controlled chunks instead of letting autogrowth create excessive VLFs.\n\nToo many VLFs create serious performance problems: slow transaction log backups, delayed database recovery during startup, and in extreme cases, degraded insert/update/delete performance. This command helps you proactively size your log files or fix existing VLF fragmentation issues.\n\nReferences:\nhttp://www.sqlskills.com/blogs/kimberly/transaction-log-vlfs-too-many-or-too-few/\nhttp://blogs.msdn.com/b/saponsqlserver/archive/2012/02/22/too-many-virtual-log-files-vlfs-can-cause-slow-database-recovery.aspx\nhttp://www.brentozar.com/blitz/high-virtual-log-file-vlf-count/\n\nIn order to get rid of this fragmentation we need to grow the file taking the following into consideration:\n- How many VLFs are created when we perform a grow operation or when an auto-grow is invoked?\n\nNote: In SQL Server 2014 this algorithm has changed (http://www.sqlskills.com/blogs/paul/important-change-vlf-creation-algorithm-sql-server-2014/)\n\nAttention:\nWe are growing in MB instead of GB because of known issue prior to SQL 2012:\nMore detail here:\nhttp://www.sqlskills.com/BLOGS/PAUL/post/Bug-log-file-growth-broken-for-multiples-of-4GB.aspx\nand\nhttp://connect.microsoft.com/SqlInstance/feedback/details/481594/log-growth-not-working-properly-with-specific-growth-sizes-vlfs-also-not-created-appropriately\nor\nhttps://connect.microsoft.com/SqlInstance/feedback/details/357502/transaction-log-file-size-will-not-grow-exactly-4gb-when-filegrowth-4gb\n\nUnderstanding related problems:\nhttp://www.sqlskills.com/blogs/kimberly/transaction-log-vlfs-too-many-or-too-few/\nhttp://blogs.msdn.com/b/saponsqlserver/archive/2012/02/22/too-many-virtual-log-files-vlfs-can-cause-slow-database-recovery.aspx\nhttp://www.brentozar.com/blitz/high-virtual-log-file-vlf-count/\n\nKnown bug before SQL Server 2012\nhttp://www.sqlskills.com/BLOGS/PAUL/post/Bug-log-file-growth-broken-for-multiples-of-4GB.aspx\nhttp://connect.microsoft.com/SqlInstance/feedback/details/481594/log-growth-not-working-properly-with-specific-growth-sizes-vlfs-also-not-created-appropriately\nhttps://connect.microsoft.com/SqlInstance/feedback/details/357502/transaction-log-file-size-will-not-grow-exactly-4gb-when-filegrowth-4gb\n\nHow it works?\nThe transaction log will grow in chunks until it reaches the desired size.\nExample: If you have a log file with 8192MB and you say that the target size is 81920MB (80GB) it will grow in chunks of 8192MB until it reaches 81920MB. 8192 -\u003e 16384 -\u003e 24576 ... 73728 -\u003e 81920", "Links": "https://dbatools.io/Expand-DbaDbLogFile", "Synopsis": "Grows transaction log files using calculated increment sizes to prevent excessive Virtual Log File (VLF) fragmentation.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to expand transaction log files for. Accepts wildcards for pattern matching.\r\nIf not specified, all accessible databases on the instance will be processed. Use this when you need to target specific databases instead of processing the entire instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies databases to skip during the expansion process when processing all databases on an instance.\r\nUse this to exclude system databases, read-only databases, or databases with specific requirements from batch log file expansion operations.", "", false, "false", "", "" ], [ "TargetLogSize", "Sets the final size you want the transaction log to reach, specified in megabytes.\r\nThis should be large enough to handle your typical transaction volume plus growth buffer. Common values range from 1GB (1024MB) for smaller databases to 10GB+ for high-transaction systems.", "", true, "false", "0", "" ], [ "IncrementSize", "Controls the size of each growth operation in megabytes during the expansion process.\r\nIf not specified, the function calculates an optimal increment size based on your target size and SQL Server version to minimize VLF fragmentation. Only specify this if you need to override the \r\nintelligent defaults.", "", false, "false", "-1", "" ], [ "TargetVlfCount", "Sets the desired maximum number of Virtual Log Files (VLFs) after the expansion completes.\r\nWhen specified, the function calculates the optimal increment size to keep total VLFs at or below this value. If the current VLF count already meets or exceeds this target, a warning is issued and \r\nthe database is skipped — use -ShrinkLogFile to first reduce the VLF count. If the target is mathematically impossible given the required growth, a warning is issued and the database is skipped.", "", false, "false", "-1", "" ], [ "LogFileId", "Targets a specific transaction log file by its file ID number when databases have multiple log files.\r\nUse this when you need to expand secondary log files instead of the primary log file. Get the file ID from sys.database_files or SSMS properties.", "", false, "false", "-1", "" ], [ "ShrinkLogFile", "Shrinks the transaction log to the ShrinkSize before expanding it to the target size.\r\nThis removes excessive VLF fragmentation by first reducing the log, then growing it with optimal increment sizes. Requires transaction log backups and cannot be used with Simple recovery model \r\ndatabases.", "", true, "false", "False", "" ], [ "ShrinkSize", "Sets the intermediate size in megabytes to shrink the log file to before re-expanding.\r\nThis should be small enough to remove VLF fragmentation but large enough to handle active transactions. Typical values are 10-100MB depending on transaction activity.", "", true, "false", "0", "" ], [ "BackupDirectory", "Sets the directory path where transaction log backups will be created during the shrink process.\r\nTransaction log backups are required to shrink log files, so this directory must be accessible to the SQL Server service account. Defaults to the instance\u0027s default backup directory if not specified.", "", false, "false", "", "" ], [ "ExcludeDiskSpaceValidation", "Skips the automatic disk space validation that normally ensures sufficient free space exists before expanding log files.\r\nUse this when you\u0027re confident about available disk space but PowerShell remoting isn\u0027t available to check drive capacity, or when working with network storage that may not report correctly.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Migration", "Backup", "Export" ], "CommandName": "Export-DbaBinaryFile", "Name": "Export-DbaBinaryFile", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Export-DbaBinaryFile [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-Table] \u003cString[]\u003e] [[-Schema] \u003cString[]\u003e] [[-FileNameColumn] \u003cString\u003e] [[-BinaryColumn] \u003cString\u003e] [[-Path] \u003cString\u003e] [[-Query] \u003cString\u003e] [[-FilePath] \u003cString\u003e] [[-InputObject] \u003cTable[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.IO.FileInfo\nReturns one FileInfo object for each binary file successfully exported to the filesystem.\nProperties:\r\n- FullName: The complete path to the exported file\r\n- Name: The filename of the exported file (without path)\r\n- DirectoryName: The directory path where the file was exported\r\n- Directory: DirectoryInfo object for the parent directory\r\n- Extension: The file extension (e.g., .jpg, .pdf)\r\n- Length: Size of the file in bytes\r\n- CreationTime: When the file was created on disk\r\n- LastWriteTime: When the file was last written\r\n- Attributes: File attributes (Archive, ReadOnly, etc.)\nFiles are written with the original filename from the FileNameColumn if using -Path, or with the specified filename if using -FilePath. Only successfully exported files are returned.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eExport-DbaBinaryFile -SqlInstance sqlcs -Database test -Path C:\\temp\\exports\nExports all binary files from the test database on sqlcs to C:\\temp\\exports. Guesses the columns based on datatype and column name.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eExport-DbaBinaryFile -SqlInstance sqlcs -Database employees -Table photos -Path C:\\temp\\exports\nExports all binary files from the photos table in the employees database on sqlcs to C:\\temp\\exports. Guesses the columns based on datatype and column name.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eExport-DbaBinaryFile -SqlInstance sqlcs -Database employees -Table photos -FileNameColumn fname -BinaryColumn data -Path C:\\temp\\exports\nExports all binary files from the photos table in the employees database on sqlcs to C:\\temp\\exports. Uses the fname and data columns for the filename and binary data.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eExport-DbaBinaryFile -SqlInstance sqlcs -Database employees -Table photos -Query \"SELECT [FileName], [Data] FROM [employees].[dbo].[photos] WHERE FirstName = \u0027Potato\u0027 and LastName = \r\n\u0027Qualitee\u0027\" -FilePath C:\\temp\\PotatoQualitee.jpg\nExports the binary file from the photos table in the employees database on sqlcs to C:\\temp\\PotatoQualitee.jpg. Uses the query to determine the filename and binary data.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaBinaryFileTable -SqlInstance sqlcs -Database test | Out-GridView -Passthru | Export-DbaBinaryFile -Path C:\\temp\nAllows you to pick tables with columns to be exported by Export-DbaBinaryFile", "Description": "Retrieves binary data stored in SQL Server tables and writes it as files to the filesystem. This is useful for extracting documents, images, or other files that have been stored in database columns using binary, varbinary, or image datatypes.\n\nThe function automatically detects filename and binary data columns based on column names and datatypes, but you can specify custom columns if needed. It supports streaming large files efficiently and can process multiple tables or databases in a single operation.\n\nIf specific filename and binary columns aren\u0027t specified, the command will guess based on the datatype (binary/image) for the binary column and a match for \"name\" as the filename column.", "Links": "https://dbatools.io/Export-DbaBinaryFile", "Synopsis": "Extracts binary data from SQL Server tables and writes it to physical files.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input.", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to scan for tables containing binary data. Accepts wildcards for pattern matching.\r\nUse this to limit the export scope when you only need files from specific databases instead of scanning the entire instance.", "", false, "false", "", "" ], [ "Table", "Specifies the table(s) containing binary data to export. Supports three-part naming (database.schema.table) and wildcards.\r\nUse this when you know exactly which tables contain your stored files, such as document management or attachment tables.\r\nWrap table names with special characters in square brackets, like [Documents.Archive] for tables with periods in the name.", "", false, "false", "", "" ], [ "Schema", "Limits the search to tables within specific schemas. Useful in databases with multiple schemas for organizing different application areas.\r\nCommon schemas include dbo, app, archive, or custom business schemas where file storage tables are organized.", "", false, "false", "", "" ], [ "FileNameColumn", "Identifies which column contains the original filename or file identifier for the stored binary data.\r\nThe function auto-detects columns with \u0027name\u0027 in the column name, but specify this when your filename column has a different naming pattern like \u0027DocumentName\u0027 or \u0027FileID\u0027.", "", false, "false", "", "" ], [ "BinaryColumn", "Identifies which column contains the actual binary file data to export.\r\nThe function auto-detects binary, varbinary, and image columns, but specify this when you have multiple binary columns or non-standard column names like \u0027DocumentData\u0027 or \u0027FileContent\u0027.", "", false, "false", "", "" ], [ "Path", "Sets the target directory where exported files will be saved using their original filenames from the database.\r\nThe directory will be created if it doesn\u0027t exist. Use this when exporting multiple files and want to preserve their original names.", "", false, "false", "", "" ], [ "Query", "Provides a custom SQL query to retrieve specific files based on complex criteria or joins.\r\nUse this when you need to filter files by metadata, join with other tables, or when the auto-detection doesn\u0027t work with your table structure.\r\nYour query must return exactly two columns: filename and binary data in that order.", "", false, "false", "", "" ], [ "FilePath", "Specifies the exact path and filename for a single exported file, overriding the stored filename.\r\nUse this when exporting one specific file or when you need to rename the output file to a standardized naming convention.", "OutFile,FileName", false, "false", "", "" ], [ "InputObject", "Accepts table objects from the pipeline, typically from Get-DbaDbTable or Get-DbaBinaryFileTable.\r\nUse this for advanced scenarios where you need to pre-filter or analyze tables before exporting their binary content.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "Shows what would happen if the command were to run. No actions are actually performed", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before executing any changing operations within the command", "cf", false, "false", "", "" ] ] }, { "Tags": "Credential", "CommandName": "Export-DbaCredential", "Name": "Export-DbaCredential", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Export-DbaCredential [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [[-Path] \u003cString\u003e] [[-FilePath] \u003cString\u003e] [[-Identity] \u003cString[]\u003e] [-ExcludePassword] [-Append] [-Passthru] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.IO.FileInfo\nReturns a file object representing the exported T-SQL script file(s) containing the CREATE CREDENTIAL statements. One file is returned for each SQL Server instance from which credentials were \r\nexported.\nProperties:\r\n- FullName: The complete path to the exported script file\r\n- Name: The name of the exported script file\r\n- Length: The size of the exported file in bytes\r\n- LastWriteTime: The date and time the file was created or last modified\r\n- Directory: The directory containing the exported file", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eExport-DbaCredential -SqlInstance sql2017 -Path C:\\temp\\cred.sql\nExports credentials, including passwords, from sql2017 to the file C:\\temp\\cred.sql", "Description": "Exports SQL Server credentials to T-SQL files containing CREATE CREDENTIAL statements that can recreate the credentials on another instance. By default, this includes decrypted passwords, making it perfect for migration scenarios where you need to move credentials between servers.\n\nThe function generates executable T-SQL scripts that DBAs can run to recreate credentials during migrations, disaster recovery, or when setting up new environments. When passwords are included, the function requires sysadmin privileges and remote Windows registry access to decrypt the stored secrets.\n\nUse the ExcludePassword parameter to export credential definitions without sensitive data for documentation or security-conscious scenarios.", "Links": "https://dbatools.io/Export-DbaCredential", "Synopsis": "Exports SQL Server credentials to executable T-SQL CREATE CREDENTIAL scripts", "Availability": "Windows only", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Credential", "Login to the target OS using alternative credentials. Accepts credential objects (Get-Credential)\nOnly used when passwords are being exported, as it requires access to the Windows OS via PowerShell remoting to decrypt the passwords.", "", false, "false", "", "" ], [ "Path", "Specifies the directory where the exported T-SQL script file will be saved. Defaults to the configured DbatoolsExport path.\r\nUse this when you want to control where credential scripts are stored for organization or compliance requirements.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027Path.DbatoolsExport\u0027)", "" ], [ "FilePath", "Specifies the complete file path and name for the exported T-SQL script. Overrides the Path parameter when specified.\r\nUse this when you need precise control over the output file name and location, especially for automated processes.", "OutFile,FileName", false, "false", "", "" ], [ "Identity", "Specifies which credential names to export by filtering on the Identity property. Accepts an array of credential names.\r\nUse this to export specific credentials instead of all credentials, particularly useful when migrating only certain application or service accounts.", "", false, "false", "", "" ], [ "ExcludePassword", "Exports credential definitions without the actual password values, replacing them with placeholder text.\r\nUse this for documentation purposes or when you need credential structure without sensitive data for security reviews.", "", false, "false", "False", "" ], [ "Append", "Adds the exported credential scripts to an existing file instead of overwriting it.\r\nUse this when consolidating credentials from multiple instances into a single deployment script.", "", false, "false", "False", "" ], [ "Passthru", "Returns the generated T-SQL script to the PowerShell pipeline instead of saving to file.\r\nUse this to capture the script in a variable, pipe to other commands, or display directly in the console.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Export", "CSV", "Data", "Compression" ], "CommandName": "Export-DbaCsv", "Name": "Export-DbaCsv", "Author": "the dbatools team + Claude", "Syntax": "Export-DbaCsv [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString\u003e] [[-Query] \u003cString\u003e] [[-Table] \u003cString\u003e] [[-InputObject] \u003cObject[]\u003e] [-Path] \u003cString\u003e [[-Delimiter] \u003cString\u003e] [-NoHeader] [[-Quote] \u003cChar\u003e] [[-QuotingBehavior] \u003cString\u003e] [[-Encoding] \u003cString\u003e] [[-NullValue] \u003cString\u003e] [[-DateTimeFormat] \u003cString\u003e] [-UseUtc] [[-CompressionType] \u003cString\u003e] [[-CompressionLevel] \u003cString\u003e] [-Append] [-NoClobber] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns a single object containing export summary information only when rows are successfully exported. If no rows are exported, no output is returned.\nProperties:\r\n- Path: The full file system path where the CSV file was written (string)\r\n- RowsExported: The total number of rows written to the CSV file (int)\r\n- FileSizeBytes: The size of the output file in bytes (long)\r\n- FileSizeMB: The size of the output file in megabytes, rounded to 2 decimal places (double)\r\n- CompressionType: The compression format applied to the file - None, GZip, Deflate, Brotli, or ZLib (string)\r\n- Elapsed: A TimeSpan object representing the total time taken to export all data (TimeSpan)\r\n- RowsPerSecond: The average export throughput calculated as rows written per second (double)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eExport-DbaCsv -SqlInstance sql001 -Database Northwind -Query \"SELECT * FROM Customers\" -Path C:\\temp\\customers.csv\nExports all customers from the Northwind database to a CSV file.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eExport-DbaCsv -SqlInstance sql001 -Database Northwind -Table \"dbo.Orders\" -Path C:\\temp\\orders.csv.gz -CompressionType GZip\nExports the Orders table to a GZip-compressed CSV file.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbTable -SqlInstance sql001 -Database tempdb -Table \"#MyTempTable\" | Export-DbaCsv -Path C:\\temp\\data.csv\nPipes table data from Get-DbaDbTable to export as CSV.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eExport-DbaCsv -SqlInstance sql001 -Database Sales -Query \"SELECT * FROM BigTable\" -Path C:\\archive\\data.csv.gz -CompressionType GZip -CompressionLevel SmallestSize\nExports query results with maximum GZip compression for archival purposes.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eExport-DbaCsv -SqlInstance sql001 -Database HR -Table Employees -Path C:\\temp\\employees.csv -Delimiter \"`t\" -QuotingBehavior Always\nExports to a tab-delimited file with all fields quoted.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e$results = Invoke-DbaQuery -SqlInstance sql001 -Database master -Query \"SELECT * FROM sys.databases\"\nPS C:\\\u003e $results | Export-DbaCsv -Path C:\\temp\\databases.csv -DateTimeFormat \"yyyy-MM-dd\"\nExports query results with custom date formatting.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eExport-DbaCsv -SqlInstance sql001 -Database Sales -Query \"SELECT * FROM Orders WHERE Region = \u0027EMEA\u0027\" -Path C:\\temp\\emea.csv -Encoding Unicode\nExports with Unicode encoding for international character support.", "Description": "Export-DbaCsv provides high-performance CSV export capabilities with support for multiple compression formats\nincluding GZip, Deflate, Brotli, and ZLib. The function can export data from SQL queries, tables, or piped\nobjects to CSV files with configurable formatting options.\n\nSupports various output formats including custom delimiters, quoting behaviors, date formatting, and encoding options.\nCompression can significantly reduce file sizes for large exports, making it ideal for archiving, data transfer,\nor storage-constrained environments.\n\nPerfect for ETL processes, data exports, reporting, and creating portable data files from SQL Server.", "Links": "https://dbatools.io/Export-DbaCsv", "Synopsis": "Exports SQL Server query results or table data to CSV files with optional compression.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies the database to query. Required when using -Query or -Table parameters.", "", false, "false", "", "" ], [ "Query", "The T-SQL query to execute. Results will be exported to CSV.", "", false, "false", "", "" ], [ "Table", "The name of the table to export. Can include schema (e.g., \"dbo.Customers\").", "", false, "false", "", "" ], [ "InputObject", "Accepts piped objects to export. Can be used with results from other dbatools commands or any PowerShell objects.", "", false, "true (ByValue)", "", "" ], [ "Path", "The output file path for the CSV. If the path ends with .gz, .br, .deflate, or .zlib,\r\nthe appropriate compression will be applied automatically unless -CompressionType is specified.", "", true, "false", "", "" ], [ "Delimiter", "Sets the field separator for the CSV output. Defaults to comma.\r\nCommon values include comma (,), tab (`t), pipe (|), or semicolon (;).\r\nMulti-character delimiters are supported (e.g., \"::\", \"||\").", "", false, "false", ",", "" ], [ "NoHeader", "Suppresses the header row in the output. Use this when appending to existing files\r\nor when the consuming application doesn\u0027t expect headers.", "", false, "false", "False", "" ], [ "Quote", "Specifies the character used to quote fields. Defaults to double-quote (\").", "", false, "false", "\"", "" ], [ "QuotingBehavior", "Controls when field values are quoted.\r\n- AsNeeded: Quote only when necessary (contains delimiter, quote, or newline). This is the default.\r\n- Always: Always quote all fields.\r\n- Never: Never quote fields (may produce invalid CSV with some data).\r\n- NonNumeric: Quote only non-numeric fields.", "", false, "false", "AsNeeded", "AsNeeded,Always,Never,NonNumeric" ], [ "Encoding", "The text encoding for the output file. Defaults to UTF8.\r\nValid values: ASCII, BigEndianUnicode, Unicode, UTF7, UTF8, UTF32.", "", false, "false", "UTF8", "ASCII,BigEndianUnicode,Unicode,UTF7,UTF8,UTF32" ], [ "NullValue", "The string to use for NULL values in the output. Defaults to empty string.", "", false, "false", "", "" ], [ "DateTimeFormat", "The format string for DateTime values. Defaults to ISO 8601 format (yyyy-MM-dd HH:mm:ss.fff).", "", false, "false", "yyyy-MM-dd HH:mm:ss.fff", "" ], [ "UseUtc", "Converts DateTime values to UTC before formatting.", "", false, "false", "False", "" ], [ "CompressionType", "The type of compression to apply to the output file.\r\n- None: No compression (default)\r\n- GZip: GZip compression (.gz)\r\n- Deflate: Deflate compression\r\n- Brotli: Brotli compression (.br) - .NET 8+ only\r\n- ZLib: ZLib compression - .NET 8+ only", "", false, "false", "None", "None,GZip,Deflate,Brotli,ZLib" ], [ "CompressionLevel", "The compression level to use. Defaults to Optimal.\r\n- Fastest: Compress as fast as possible, even if the resulting file is not optimally compressed.\r\n- Optimal: Balance between compression speed and file size.\r\n- SmallestSize: Compress as much as possible, even if it takes longer.\r\n- NoCompression: No compression.", "", false, "false", "Optimal", "Fastest,Optimal,SmallestSize,NoCompression" ], [ "Append", "Appends to an existing file instead of overwriting. Headers are automatically suppressed when appending.", "", false, "false", "False", "" ], [ "NoClobber", "Prevents overwriting an existing file. Returns an error if the file already exists.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "", "wi", false, "false", "", "" ], [ "Confirm", "", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Dacpac", "Deployment" ], "CommandName": "Export-DbaDacPackage", "Name": "Export-DbaDacPackage", "Author": "Richie lee (@richiebzzzt)", "Syntax": "Export-DbaDacPackage -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-AllUserDatabases] [-Path \u003cString\u003e] [-FilePath \u003cString\u003e] [-DacOption \u003cObject\u003e] [-Type \u003cString\u003e] [-Table \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]\nExport-DbaDacPackage -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-AllUserDatabases] [-Path \u003cString\u003e] [-FilePath \u003cString\u003e] [-ExtendedParameters \u003cString\u003e] [-ExtendedProperties \u003cString\u003e] [-Type \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database exported as a DACPAC or BACPAC package.\nDefault display properties (via Select-DefaultView):\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: The name of the database that was exported\r\n- Path: The full file path where the package file was saved\r\n- Elapsed: The elapsed time for the export operation (formatted timespan)\r\n- Result: The output from the extraction/export operation, typically containing status messages from DacServices or SqlPackage.exe\nAdditional properties available:\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eExport-DbaDacPackage -SqlInstance sql2016 -Database SharePoint_Config -FilePath C:\\SharePoint_Config.dacpac\nExports the dacpac for SharePoint_Config on sql2016 to C:\\SharePoint_Config.dacpac\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$options = New-DbaDacOption -Type Dacpac -Action Export\nPS C:\\\u003e $options.ExtractAllTableData = $true\r\nPS C:\\\u003e $options.CommandTimeout = 0\r\nPS C:\\\u003e Export-DbaDacPackage -SqlInstance sql2016 -Database DB1 -DacOption $options\nUses DacOption object to set the CommandTimeout to 0 then extracts the dacpac for DB1 on sql2016 to C:\\Users\\username\\Documents\\DbatoolsExport\\sql2016-DB1-20201227140759-dacpackage.dacpac including \r\nall table data. As noted the generated filename will contain the server name, database name, and the current timestamp in the \"%Y%m%d%H%M%S\" format.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eExport-DbaDacPackage -SqlInstance sql2016 -AllUserDatabases -ExcludeDatabase \"DBMaintenance\",\"DBMonitoring\" -Path \"C:\\temp\"\nExports dacpac packages for all USER databases, excluding \"DBMaintenance\" \u0026 \"DBMonitoring\", on sql2016 and saves them to C:\\temp. The generated filename(s) will contain the server name, database \r\nname, and the current timestamp in the \"%Y%m%d%H%M%S\" format.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$moreparams = \"/OverwriteFiles:$true /Quiet:$true\"\nPS C:\\\u003e Export-DbaDacPackage -SqlInstance sql2016 -Database SharePoint_Config -Path C:\\temp -ExtendedParameters $moreparams\nUsing extended parameters to over-write the files and performs the extraction in quiet mode to C:\\temp\\sql2016-SharePoint_Config-20201227140759-dacpackage.dacpac. Uses SqlPackage.exe command line \r\ninstead of DacFx API behind the scenes. As noted the generated filename will contain the server name, database name, and the current timestamp in the \"%Y%m%d%H%M%S\" format.", "Description": "Creates database deployment packages for version control, migrations, and schema distribution. Generates DACPAC files containing database schema definitions or BACPAC files that include both schema and data.\n\nPerfect for creating deployable packages from development databases, capturing schema snapshots for source control, or preparing migration artifacts for different environments. The function handles multiple databases in batch operations and provides flexible table filtering when you only need specific objects.\n\nUses Microsoft DacFx API from dbatools.library. Note that extraction can fail with three-part references to external databases or complex cross-database dependencies.\n\nFor help with the extract action parameters and properties, refer to https://learn.microsoft.com/en-us/sql/tools/sqlpackage/sqlpackage-extract", "Links": "https://dbatools.io/Export-DbaDacPackage", "Synopsis": "Exports DACPAC or BACPAC packages from SQL Server databases using the DacFx framework", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. Must be SQL Server 2008 R2 or higher (DAC Framework minimum version 10.50).", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nOnly SQL authentication is supported. When not specified, uses Trusted Authentication.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to export as DACPAC or BACPAC packages. Accepts multiple database names and supports wildcards.\r\nUse this to target specific databases instead of processing all user databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies databases to skip during export operations. Works with both Database and AllUserDatabases parameters.\r\nUse this to exclude system databases, maintenance databases, or any databases you don\u0027t want to package.", "", false, "false", "", "" ], [ "AllUserDatabases", "Exports packages for all user databases on the instance, automatically excluding system databases.\r\nUse this for bulk operations when you want to create deployment packages for every application database.", "", false, "false", "False", "" ], [ "Path", "Specifies the directory where DACPAC or BACPAC files will be saved. Defaults to the configured DbatoolsExport path.\r\nUse this when you want to organize exports in a specific location or when working with multiple databases that need consistent file placement.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027Path.DbatoolsExport\u0027)", "" ], [ "FilePath", "Specifies the complete file path including filename for the export package. Overrides both Path and automatic file naming.\r\nUse this when you need a specific filename or when exporting a single database to a predetermined location.", "OutFile,FileName", false, "false", "", "" ], [ "DacOption", "Configures advanced export settings using a DacExtractOptions or DacExportOptions object created by New-DbaDacOption.\r\nUse this to control extraction behavior like command timeouts, table data inclusion, or specific schema elements to include or exclude.", "ExtractOptions,ExportOptions,DacExtractOptions,DacExportOptions,Options,Option", false, "false", "", "" ], [ "ExtendedParameters", "Passes additional command-line parameters directly to SqlPackage.exe for advanced scenarios (e.g., \u0027/OverwriteFiles:true /Quiet:true\u0027).\r\nUse this when you need SqlPackage options not available through DacOption or when integrating with existing SqlPackage workflows.\r\nNote: This parameter requires SqlPackage.exe to be installed via Install-DbaSqlPackage or locally.", "", false, "false", "", "" ], [ "ExtendedProperties", "Passes additional property settings directly to SqlPackage.exe for fine-tuned control over extraction behavior.\r\nUse this when you need to set specific SqlPackage properties that aren\u0027t exposed through the standard DacOption parameter.\r\nNote: This parameter requires SqlPackage.exe to be installed via Install-DbaSqlPackage.", "", false, "false", "", "" ], [ "Type", "Specifies the package type to create: Dacpac (schema-only) or Bacpac (schema and data). Defaults to Dacpac.\r\nUse Dacpac for version control and schema deployments, or Bacpac when you need to include table data for migrations or testing.", "", false, "false", "Dacpac", "Dacpac,Bacpac" ], [ "Table", "Specifies which tables to include in the export package. Provide as schema.table format (e.g., \u0027dbo.Users\u0027, \u0027Sales.Orders\u0027).\r\nUse this when you only need specific tables rather than the entire database, such as for partial deployments or data subsets.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Export", "Role" ], "CommandName": "Export-DbaDbRole", "Name": "Export-DbaDbRole", "Author": "Patrick Flynn (@sqllensman)", "Syntax": "Export-DbaDbRole [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-InputObject] \u003cObject[]\u003e] [[-ScriptingOptionsObject] \u003cScriptingOptions\u003e] [[-Database] \u003cObject[]\u003e] [[-Role] \u003cObject[]\u003e] [[-ExcludeRole] \u003cObject[]\u003e] [-ExcludeFixedRole] [-IncludeRoleMember] [[-Path] \u003cString\u003e] [[-FilePath] \u003cString\u003e] [-Passthru] [[-BatchSeparator] \u003cString\u003e] [-NoClobber] [-Append] [-NoPrefix] [[-Encoding] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.String (when -Passthru is specified or no -Path/-FilePath is provided)\nReturns the generated T-SQL script as a string containing all role definitions, permission statements, and optionally role membership commands.\nSystem.IO.FileInfo (when -Path or -FilePath is specified)\nReturns file information objects for each created script file. Multiple databases result in multiple FileInfo objects.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eExport-DbaDbRole -SqlInstance sql2005 -Path C:\\temp\nExports all the Database Roles for SQL Server \"sql2005\" and writes them to the file \"C:\\temp\\sql2005-logins.sql\"\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eExport-DbaDbRole -SqlInstance sqlserver2014a -ExcludeRole realcajun -SqlCredential $scred -Path C:\\temp\\roles.sql -Append\nAuthenticates to sqlserver2014a using SQL Authentication. Exports all roles except for realcajun to C:\\temp\\roles.sql, and appends to the file if it exists. If not, the file will be created.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eExport-DbaDbRole -SqlInstance sqlserver2014a -Role realcajun,netnerds -Path C:\\temp\\roles.sql\nExports ONLY roles netnerds and realcajun FROM sqlserver2014a to the file C:\\temp\\roles.sql\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eExport-DbaDbRole -SqlInstance sqlserver2014a -Role realcajun,netnerds -Database HR, Accounting\nExports ONLY roles netnerds and realcajun FROM sqlserver2014a with the permissions on databases HR and Accounting\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sqlserver2014a -Database HR, Accounting | Export-DbaDbRole\nExports ONLY roles FROM sqlserver2014a with permissions on databases HR and Accounting\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eSet-DbatoolsConfig -FullName formatting.batchseparator -Value $null\nPS C:\\\u003e Export-DbaDbRole -SqlInstance sqlserver2008 -Role realcajun,netnerds -Path C:\\temp\\roles.sql\nSets the BatchSeparator configuration to null, removing the default \"GO\" value.\r\nExports ONLY roles netnerds and realcajun FROM sqlserver2008 server, to the C:\\temp\\roles.sql file, without the \"GO\" batch separator.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eExport-DbaDbRole -SqlInstance sqlserver2008 -Role realcajun,netnerds -Path C:\\temp\\roles.sql -BatchSeparator $null\nExports ONLY roles netnerds and realcajun FROM sqlserver2008 server, to the C:\\temp\\roles.sql file, without the \"GO\" batch separator.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sqlserver2008 | Export-DbaDbRole -Role realcajun\nExports role realcajun for all databases on sqlserver2008\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003eGet-DbaDbRole -SqlInstance sqlserver2008 -ExcludeFixedRole | Export-DbaDbRole\nExports all roles from all databases on sqlserver2008, excludes all roles marked as as FixedRole", "Description": "Creates executable T-SQL scripts that fully define database roles including CREATE ROLE statements, granular object permissions, and schema ownership assignments. The output captures every permission granted to custom roles across all database securables like tables, schemas, assemblies, and certificates so you can recreate identical security configurations in other environments. This is particularly useful for migrating role-based security between development, test, and production databases, or documenting security configurations for compliance audits.\n\nThis command is based off of John Eisbrener\u0027s post \"Fully Script out a MSSQL Database Role\"\nReference: https://dbaeyes.wordpress.com/2013/04/19/fully-script-out-a-mssql-database-role/", "Links": "https://dbatools.io/Export-DbaDbRole", "Synopsis": "Generates T-SQL scripts for database role definitions with their complete permission sets and schema ownership", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. SQL Server 2005 and above supported.\r\nAny databases in CompatibilityLevel 80 or lower will be skipped", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "InputObject", "Accepts database role objects from Get-DbaDbRole, database objects from Get-DbaDatabase, or server instances.\r\nUse this when you need to export roles from a filtered set of databases or specific role objects.", "", false, "true (ByValue)", "", "" ], [ "ScriptingOptionsObject", "Controls T-SQL script generation options using an SMO ScriptingOptions object from New-DbaScriptingOption.\r\nCustomize output format, object naming, and scripting behavior to match your deployment requirements.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to export role definitions from. Accepts wildcards for pattern matching.\r\nUse this when you need role scripts for specific databases rather than processing all databases on the instance.", "", false, "false", "", "" ], [ "Role", "Specifies which database roles to export. Accepts wildcards and multiple role names.\r\nUse this when you need scripts for specific custom roles rather than all roles in the database.", "", false, "false", "", "" ], [ "ExcludeRole", "Excludes specific database roles from the export operation. Accepts wildcards and multiple role names.\r\nUseful when you want most roles except certain application-specific or sensitive roles.", "", false, "false", "", "" ], [ "ExcludeFixedRole", "Excludes built-in SQL Server fixed database roles like db_datareader, db_datawriter, and db_owner.\r\nUse this when you only want to export custom application roles and not the standard SQL Server roles.", "", false, "false", "False", "" ], [ "IncludeRoleMember", "Includes ALTER ROLE statements to add existing members back to the roles.\r\nUse this when you need to recreate both the role definitions and their current membership assignments.", "", false, "false", "False", "" ], [ "Path", "Specifies the output directory for generated SQL script files. Defaults to the configured DbatoolsExport path.\r\nEach database gets its own script file named with the instance and database name for organization.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027Path.DbatoolsExport\u0027)", "" ], [ "FilePath", "Specifies the exact file path for the output script. Auto-generates filename based on instance and database if not provided.\r\nOnly use this when processing a single database, as multiple databases would overwrite the same file.", "OutFile,FileName", false, "false", "", "" ], [ "Passthru", "Outputs the T-SQL script to the console instead of writing to files.\r\nUse this to review the generated scripts before saving them or to pipe output to other commands.", "", false, "false", "False", "" ], [ "BatchSeparator", "Sets the batch separator between T-SQL statements in the output script. Defaults to \"GO\" from configuration.\r\nChange this when deploying to tools that require different batch separators or set to null to remove separators entirely.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027Formatting.BatchSeparator\u0027)", "" ], [ "NoClobber", "Prevents overwriting existing files at the target location. The operation will fail if files already exist.\r\nUse this as a safety measure when you want to avoid accidentally replacing existing role scripts.", "", false, "false", "False", "" ], [ "Append", "Adds the generated T-SQL scripts to the end of existing files rather than overwriting them.\r\nUse this to combine role scripts from multiple operations into a single deployment file.", "", false, "false", "False", "" ], [ "NoPrefix", "Removes the header comment block that includes creation timestamp, user, and source information.\r\nUse this when you need clean T-SQL scripts without metadata comments for automated deployments.", "", false, "false", "False", "" ], [ "Encoding", "Sets the character encoding for output files. Defaults to UTF8 for broad compatibility.\r\nChange to Unicode when working with international character sets in role names or comments.", "", false, "false", "UTF8", "ASCII,BigEndianUnicode,Byte,String,Unicode,UTF7,UTF8,Unknown" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Migration", "Backup", "Export" ], "CommandName": "Export-DbaDbTableData", "Name": "Export-DbaDbTableData", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Export-DbaDbTableData [-InputObject] \u003cTable[]\u003e [[-Path] \u003cString\u003e] [[-FilePath] \u003cString\u003e] [[-Encoding] \u003cString\u003e] [[-BatchSeparator] \u003cString\u003e] [-NoPrefix] [-Passthru] [-NoClobber] [-Append] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.IO.FileInfo\nWhen used without -Passthru, returns file information objects for the created SQL script files.\nProperties:\r\n- Name: The filename of the generated SQL script\r\n- FullName: The complete file path to the generated script\r\n- Directory: The directory containing the script file\r\n- Length: The size of the file in bytes\r\n- LastWriteTime: When the file was last modified\r\n- CreationTime: When the file was created\nSystem.String (when -Passthru is specified)\nReturns the generated INSERT statements as string output. Multiple strings are returned for table data scripts, one per INSERT statement or batch. Use -BatchSeparator parameter to control statement \r\nseparation with GO or other batch terminators.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbTable -SqlInstance sql2017 -Database AdventureWorks2014 -Table EmployeePayHistory | Export-DbaDbTableData\nExports data from EmployeePayHistory in AdventureWorks2014 in sql2017\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbTable -SqlInstance sql2017 -Database AdventureWorks2014 -Table EmployeePayHistory | Export-DbaDbTableData -FilePath C:\\temp\\export.sql -Append\nExports data from EmployeePayHistory in AdventureWorks2014 in sql2017 using a trusted connection - Will append the output to the file C:\\temp\\export.sql if it already exists\r\nScript does not include Batch Separator and will not compile\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbTable -SqlInstance sql2016 -Database MyDatabase -Table \u0027dbo.Table1\u0027, \u0027dbo.Table2\u0027 -SqlCredential sqladmin | Export-DbaDbTableData -FilePath C:\\temp\\export.sql -Append\nExports only data from \u0027dbo.Table1\u0027 and \u0027dbo.Table2\u0027 in MyDatabase to C:\\temp\\export.sql and uses the SQL login \"sqladmin\" to login to sql2016", "Description": "Creates executable INSERT statements from existing table data, making it easy to move data between SQL Server instances or environments. This is particularly useful for migrating reference tables, lookup data, or configuration tables where you need the actual data values rather than just the table structure. The generated scripts include proper USE database context and can be saved to files or piped to other commands for further processing.", "Links": "https://dbatools.io/Export-DbaDbTableData", "Synopsis": "Generates INSERT statements from table data for migration and deployment scripts", "Availability": "Windows, Linux, macOS", "Params": [ [ "InputObject", "Accepts table objects from Get-DbaDbTable through the pipeline.\r\nUse this to process specific tables you\u0027ve already identified rather than specifying table names again.", "", true, "true (ByValue)", "", "" ], [ "Path", "Sets the directory where output files will be created when not using FilePath.\r\nDefaults to the dbatools export directory configured in module settings.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027Path.DbatoolsExport\u0027)", "" ], [ "FilePath", "Specifies the complete path and filename for the output SQL script.\r\nUse this when you need the INSERT statements saved to a specific file location for deployment or version control.", "OutFile,FileName", false, "false", "", "" ], [ "Encoding", "Controls the character encoding of the exported SQL file. Defaults to UTF8.\r\nUse UTF8 for compatibility with most modern SQL tools, or ASCII for older systems that don\u0027t support Unicode.\nValid values are:\r\n - ASCII: Uses the encoding for the ASCII (7-bit) character set.\r\n - BigEndianUnicode: Encodes in UTF-16 format using the big-endian byte order.\r\n - Byte: Encodes a set of characters into a sequence of bytes.\r\n - String: Uses the encoding type for a string.\r\n - Unicode: Encodes in UTF-16 format using the little-endian byte order.\r\n - UTF7: Encodes in UTF-7 format.\r\n - UTF8: Encodes in UTF-8 format.\r\n - Unknown: The encoding type is unknown or invalid. The data can be treated as binary.", "", false, "false", "UTF8", "ASCII,BigEndianUnicode,Byte,String,Unicode,UTF7,UTF8,Unknown" ], [ "BatchSeparator", "Adds batch separators (like GO) between INSERT statements in the output script.\r\nUse this when creating deployment scripts that will be executed in SQL Server Management Studio or sqlcmd.", "", false, "false", "", "" ], [ "NoPrefix", "Excludes the USE database statement and other prefixes from the generated script.\r\nUse this when combining output with other scripts or when the database context is already established.", "", false, "false", "False", "" ], [ "Passthru", "Displays the generated INSERT statements in the PowerShell console in addition to file output.\r\nUseful for reviewing the script content before execution or when piping to other commands.", "", false, "false", "False", "" ], [ "NoClobber", "Prevents overwriting existing files at the specified FilePath.\r\nUse this as a safety measure to avoid accidentally replacing important deployment scripts.", "", false, "false", "False", "" ], [ "Append", "Adds the INSERT statements to the end of an existing file instead of creating a new one.\r\nUseful when building comprehensive deployment scripts from multiple table exports or combining with other SQL operations.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "Shows what would happen if the command were to run. No actions are actually performed", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before executing any changing operations within the command", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Community", "GlennBerry" ], "CommandName": "Export-DbaDiagnosticQuery", "Name": "Export-DbaDiagnosticQuery", "Author": "Andre Kamman (@AndreKamman), clouddba.io", "Syntax": "Export-DbaDiagnosticQuery [-InputObject] \u003cObject[]\u003e [[-ConvertTo] \u003cString\u003e] [[-Path] \u003cFileInfo\u003e] [[-Suffix] \u003cString\u003e] [-NoPlanExport] [-NoQueryExport] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.IO.FileInfo\nReturns one or more file objects representing the exported files. The specific files returned depend on the parameters used and the content of the diagnostic query results.\nFor each diagnostic query result processed, the function may return:\r\n- CSV file: When ConvertTo is \"Csv\" (one file per diagnostic query or one per database if DatabaseSpecific)\r\n- Excel file: When ConvertTo is \"Excel\" (one workbook per instance or per database if DatabaseSpecific)\r\n- .sqlplan file: Query execution plan files extracted from result columns (unless NoPlanExport is specified)\r\n- .sql file: Query text files extracted from result columns (unless NoQueryExport is specified)\nEach System.IO.FileInfo object contains standard file properties including:\r\n- Name: The filename (e.g., \"SERVERNAME-DQ-20231215120530ms.xlsx\")\r\n- FullName: The complete path to the file\r\n- Directory: The directory where the file is located\r\n- Length: File size in bytes\r\n- CreationTime: When the file was created\r\n- LastWriteTime: When the file was last modified", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaDiagnosticQuery -SqlInstance sql2016 | Export-DbaDiagnosticQuery -Path c:\\temp\nConverts output from Invoke-DbaDiagnosticQuery to multiple CSV files\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$output = Invoke-DbaDiagnosticQuery -SqlInstance sql2016\nPS C:\\\u003e Export-DbaDiagnosticQuery -InputObject $output -ConvertTo Excel\nConverts output from Invoke-DbaDiagnosticQuery to Excel worksheet(s) in the Documents folder", "Description": "Processes the PowerShell objects returned by Glenn Berry\u0027s diagnostic queries and saves them as CSV files or Excel worksheets for analysis, reporting, and sharing with vendors.\nAutomatically extracts execution plans as separate .sqlplan files and query text as .sql files, which can be opened directly in SQL Server Management Studio.\nThis is useful when you need file-based output for compliance documentation, performance analysis, or when working with teams that prefer traditional file formats over PowerShell objects.\nCSV output creates individual files per query while Excel output consolidates results into worksheets within a single workbook.", "Links": "https://dbatools.io/Export-DbaDiagnosticQuery", "Synopsis": "Converts diagnostic query results from Invoke-DbaDiagnosticQuery into CSV or Excel files", "Availability": "Windows, Linux, macOS", "Params": [ [ "InputObject", "Specifies the diagnostic query results from Invoke-DbaDiagnosticQuery to convert to files.\r\nAccepts pipeline input directly from Invoke-DbaDiagnosticQuery or stored results in a variable.\r\nEach object contains query results, execution plans, and metadata needed for file export.", "", true, "true (ByValue)", "", "" ], [ "ConvertTo", "Specifies the output format for diagnostic query results. Valid choices are Excel and CSV with CSV as the default.\r\nUse Excel when you need consolidated results in worksheets for easier analysis and sharing with non-technical stakeholders.\r\nChoose CSV when you need individual files per query for automated processing or importing into other tools.", "", false, "false", "Csv", "Excel,Csv" ], [ "Path", "Specifies the directory path where exported files will be created. Must be a directory, not a filename.\r\nDefaults to the configured dbatools export path if not specified.\r\nThe function creates separate files for each diagnostic query result within this directory.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027Path.DbatoolsExport\u0027)", "" ], [ "Suffix", "Specifies a suffix to append to all generated filenames for uniqueness. Defaults to a timestamp in yyyyMMddHHmmssms format.\r\nUse this when running exports multiple times to prevent filename conflicts or when you need custom file identification.\r\nHelps organize multiple export runs when tracking performance trends over time.", "", false, "false", "\"$(Get-Date -format \u0027yyyyMMddHHmmssms\u0027)\"", "" ], [ "NoPlanExport", "Suppresses the export of execution plans as separate .sqlplan files. These files can be opened directly in SQL Server Management Studio for plan analysis.\r\nUse this switch when you only need the query results data and not the execution plan details.\r\nReduces file clutter when performing bulk exports where execution plans are not required for analysis.", "", false, "false", "False", "" ], [ "NoQueryExport", "Suppresses the export of query text as separate .sql files. These files contain the actual SQL statements from the diagnostic queries.\r\nUse this switch when you only need the result data and not the source query text.\r\nHelpful when exporting large result sets where the query text is not needed for your analysis workflow.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Diagnostic", "Performance", "ExecutionPlan" ], "CommandName": "Export-DbaExecutionPlan", "Name": "Export-DbaExecutionPlan", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Export-DbaExecutionPlan [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nExport-DbaExecutionPlan -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-Path \u003cString\u003e] [-SinceCreation \u003cDateTime\u003e] [-SinceLastExecution \u003cDateTime\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nExport-DbaExecutionPlan [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-Path \u003cString\u003e] -InputObject \u003cObject[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per execution plan exported. Each object contains information about the exported plan and the file where it was saved.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- DatabaseName: The name of the database containing the execution plan\r\n- SqlHandle: Hexadecimal identifier for the SQL statement (used internally by SQL Server)\r\n- CreationTime: DateTime when the plan was first compiled/cached\r\n- LastExecutionTime: DateTime when the plan was last executed\r\n- OutputFile: Full path to the .sqlplan file saved to disk\nAdditional properties available (not displayed by default):\r\n- PlanHandle: Hexadecimal identifier for the compiled plan\r\n- QueryPosition: Position of the statement within the batch (determined by row number)\r\n- SingleStatementPlan: XML string representation of the single-statement execution plan\r\n- BatchQueryPlan: XML string representation of the batch query execution plan\r\n- SingleStatementPlanRaw: XML object parsed from SingleStatementPlan\r\n- BatchQueryPlanRaw: XML object parsed from BatchQueryPlan\nUse Select-Object * to access all properties if needed for scripting or further processing.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eExport-DbaExecutionPlan -SqlInstance sqlserver2014a -Path C:\\Temp\nExports all execution plans for sqlserver2014a. Files saved in to C:\\Temp\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eExport-DbaExecutionPlan -SqlInstance sqlserver2014a -Database db1, db2 -SinceLastExecution \u00272016-07-01 10:47:00\u0027 -Path C:\\Temp\nExports all execution plans for databases db1 and db2 on sqlserver2014a since July 1, 2016 at 10:47 AM. Files saved in to C:\\Temp\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaExecutionPlan -SqlInstance sqlserver2014a | Export-DbaExecutionPlan -Path C:\\Temp\nGets all execution plans for sqlserver2014a. Using Pipeline exports them all to C:\\Temp\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaExecutionPlan -SqlInstance sqlserver2014a | Export-DbaExecutionPlan -Path C:\\Temp -WhatIf\nGets all execution plans for sqlserver2014a. Then shows what would happen if the results where piped to Export-DbaExecutionPlan", "Description": "Queries the SQL Server plan cache using dynamic management views and exports execution plans as XML files with .sqlplan extensions. These files can be opened directly in SQL Server Management Studio for detailed analysis and troubleshooting. The function retrieves both single statement plans and batch query plans from sys.dm_exec_query_stats, allowing you to analyze query performance patterns and identify optimization opportunities. You can filter results by database, creation time, or last execution time to focus on specific time periods or problematic queries. This eliminates the need to manually capture plans during query execution or dig through plan cache DMVs.\n\nThanks to\nhttps://www.simple-talk.com/sql/t-sql-programming/dmvs-for-query-plan-metadata/\nand\nhttp://www.scarydba.com/2017/02/13/export-plans-cache-sqlplan-file/\nfor the idea and query.", "Links": "https://dbatools.io/Export-DbaExecutionPlan", "Synopsis": "Extracts execution plans from plan cache and saves them as .sqlplan files for analysis", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to export execution plans from. Accepts wildcards for pattern matching.\r\nUse this when you need to focus on specific databases instead of analyzing plans from all databases on the instance.\r\nHelps reduce output volume and processing time when troubleshooting database-specific performance issues.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies which databases to exclude from execution plan export. Accepts wildcards for pattern matching.\r\nUse this to skip system databases or databases that are known to be performing well when doing instance-wide plan analysis.\r\nCommon exclusions include tempdb, model, or development databases that don\u0027t need performance review.", "", false, "false", "", "" ], [ "Path", "Specifies the directory path where .sqlplan files will be saved. Defaults to the dbatools export configuration path.\r\nFiles are named using a pattern that includes instance name, database, query position, and SQL handle for easy identification.\r\nEnsure the path exists and has sufficient space, as large plan caches can generate hundreds of files.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027Path.DbatoolsExport\u0027)", "" ], [ "SinceCreation", "Filters execution plans to only include those created after the specified date and time.\r\nUse this when investigating performance issues that started after a specific deployment, configuration change, or known incident.\r\nHelps focus analysis on recently compiled plans rather than older cached plans that may no longer be relevant.", "", false, "false", "", "" ], [ "SinceLastExecution", "Filters execution plans to only include those last executed after the specified date and time.\r\nUse this when you want to analyze only actively used plans rather than stale plans sitting in cache.\r\nParticularly useful for identifying currently problematic queries during active performance issues or recent workload changes.", "", false, "false", "", "" ], [ "InputObject", "Accepts execution plan objects from the pipeline, typically from Get-DbaExecutionPlan.\r\nUse this when you want to filter or process plans with Get-DbaExecutionPlan first, then export specific results.\r\nAllows for more complex filtering scenarios before exporting plans to files.", "", true, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "Shows what would happen if the command were to run. No actions are actually performed.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before executing any changing operations within the command.", "cf", false, "false", "", "" ] ] }, { "Tags": "Export", "CommandName": "Export-DbaInstance", "Name": "Export-DbaInstance", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Export-DbaInstance [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [[-Path] \u003cString\u003e] [-NoRecovery] [[-AzureCredential] \u003cString\u003e] [-IncludeDbMasterKey] [[-EncryptionPassword] \u003cSecureString\u003e] [[-DecryptionPassword] \u003cSecureString\u003e] [[-Exclude] \u003cString[]\u003e] [[-BatchSeparator] \u003cString\u003e] [[-ScriptingOption] \u003cScriptingOptions\u003e] [-NoPrefix] [-ExcludePassword] [-Force] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.IO.FileInfo\nReturns one or more FileInfo objects representing the exported SQL script files and configuration files created during the instance export. Each file represents a different component type being \r\nexported (logins, jobs, credentials, etc.).\nThe command returns file objects for successfully created export files, such as:\r\n- sp_configure.sql: SQL Server configuration settings\r\n- customererrors.sql: User-defined error messages\r\n- serverroles.sql: Server role definitions\r\n- credentials.sql: SQL credentials\r\n- logins.sql: SQL Server logins\r\n- dbmail.sql: Database Mail configuration\r\n- regserver.xml: Central Management Server registration settings\r\n- backupdevices.sql: Backup device definitions\r\n- linkedservers.sql: Linked server configurations\r\n- servertriggers.sql: Server-level triggers\r\n- databases.sql: Database restore scripts\r\n- audits.sql: Server audits\r\n- auditspecs.sql: Server audit specifications\r\n- endpoints.sql: Server endpoints\r\n- policymanagement.sql: Policy-Based Management policies and conditions\r\n- resourcegov.sql: Resource Governor configuration\r\n- extendedevents.sql: Extended Events sessions\r\n- sqlagent.sql: SQL Agent jobs, schedules, operators, alerts, and proxies\r\n- replication.sql: Replication settings\r\n- userobjectsinsysdbs.sql: User-created objects in system databases\r\n- AvailabilityGroups.sql: Availability Groups configuration\r\n- OleDbProvider.sql: OLEDB provider configuration\r\n- *.cer: Database certificate backups when -IncludeDbMasterKey is specified\r\n- *.pvk: Database certificate private key backups when -IncludeDbMasterKey and -EncryptionPassword are specified\r\n- *.key: Database master key backups when -IncludeDbMasterKey and -EncryptionPassword are specified\nFiles are returned only if they were successfully created and are not excluded via the -Exclude parameter.\r\nThe -ErrorAction Ignore used in Get-ChildItem means that if a file is not created, no error object is returned for that file.\nAll FileInfo properties are accessible, including:\r\n- FullName: Complete path to the exported file\r\n- Name: File name\r\n- Length: File size in bytes\r\n- CreationTime: When the file was created\r\n- LastWriteTime: When the file was last written", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eExport-DbaInstance -SqlInstance sqlserver\\instance\nAll databases, logins, job objects and sp_configure options will be exported from sqlserver\\instance to an automatically generated folder name in Documents. For example, \r\n%userprofile%\\Documents\\DbatoolsExport\\sqldev1$sqlcluster-20201108140000\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eExport-DbaInstance -SqlInstance sqlcluster -Exclude Databases, Logins -Path C:\\dr\\sqlcluster\nExports everything but logins and database restore scripts to a folder such as C:\\dr\\sqlcluster\\sqldev1$sqlcluster-20201108140000\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eExport-DbaInstance -SqlInstance sqlcluster -Path C:\\servers\\ -NoPrefix\nExports everything to a folder such as C:\\servers\\sqldev1$sqlcluster-20201108140000 but scripts will not include prefix information.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eExport-DbaInstance -SqlInstance sqlcluster -Path C:\\servers\\ -Force\nExports everything to a folder such as C:\\servers\\sqldev1$sqlcluster and will overwrite/refresh existing files in that folder. Note: when the -Force param is used the generated folder name will not \r\ninclude a timestamp. This supports the use case of running Export-DbaInstance on a schedule and writing to the same dir each time.", "Description": "Export-DbaInstance consolidates most of the export scripts in dbatools into one command that captures everything needed to recreate or migrate a SQL Server instance.\n\nThis command saves hours of manual work when migrating instances to new servers, creating disaster recovery scripts, or documenting configurations for compliance. It generates individual T-SQL script files for each component type, organized in a timestamped folder structure that\u0027s perfect for version control or automated deployment pipelines.\n\nUnless an -Exclude is specified, it exports:\n\nAll database \u0027restore from backup\u0027 scripts. Note: if a database does not have a backup the \u0027restore from backup\u0027 script won\u0027t be generated.\nAll logins.\nAll database mail objects.\nAll credentials.\nAll objects within the Job Server (SQL Agent).\nAll linked servers.\nAll groups and servers within Central Management Server.\nAll SQL Server configuration objects (everything in sp_configure).\nAll user objects in system databases.\nAll system triggers.\nAll system backup devices.\nAll Audits.\nAll Endpoints.\nAll Extended Events.\nAll Policy Management objects.\nAll Resource Governor objects.\nAll Server Audit Specifications.\nAll Custom Errors (User Defined Messages).\nAll Server Roles.\nAll Availability Groups.\nAll OLEDB Providers.\n\nWhen -IncludeDbMasterKey is specified: all database certificates (exported as .cer files; private keys exported as .pvk files when -EncryptionPassword is provided) and all database master keys encrypted with the -EncryptionPassword.\n\nThe exported files are written to a folder using the naming convention \"machinename$instance-yyyyMMddHHmmss\", making it easy to identify the source instance and export timestamp.\n\nThis command is particularly valuable for:\n- Instance migrations when moving to new hardware or cloud platforms\n- Creating standardized development and test environments that match production\n- Disaster recovery planning by maintaining current configuration snapshots\n- Compliance documentation that automatically captures security settings and configurations\n- Change management workflows where you need baseline configurations before major updates\n\nTwo folder management options are supported:\n1. Default behavior creates new timestamped folders for historical archiving\n2. Using -Force overwrites files in the same location, ideal for scheduled exports that feed into version control systems\n\nFor more granular control, please use one of the -Exclude parameters and use the other functions available within the dbatools module.", "Links": "https://dbatools.io/Export-DbaInstance", "Synopsis": "Exports complete SQL Server instance configuration as T-SQL scripts for migration or disaster recovery", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instances", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Credential", "Alternative Windows credentials for exporting Linked Servers and Credentials. Accepts credential objects (Get-Credential)", "", false, "false", "", "" ], [ "Path", "Specifies the root directory where export files will be created in a timestamped subfolder.\r\nDefaults to the dbatools export path configuration setting, typically Documents\\DbatoolsExport.", "FilePath", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027Path.DbatoolsExport\u0027)", "" ], [ "NoRecovery", "Generates database restore scripts with NORECOVERY option, leaving databases in restoring state.\r\nEssential for log shipping scenarios or when you need to apply additional transaction log backups after the initial restore.", "", false, "false", "False", "" ], [ "AzureCredential", "Specifies the Azure storage credential name for accessing backups stored in Azure Blob Storage.\r\nRequired when generating restore scripts for databases backed up to Azure storage containers.", "", false, "false", "", "" ], [ "IncludeDbMasterKey", "When specified, exports database certificates (.cer files) and database master keys (.key files) to the export directory.\r\nCertificate private keys (.pvk files) are also exported when -EncryptionPassword is provided.\r\nDatabase master keys require -EncryptionPassword to be specified; if omitted, only certificates are exported.\r\nUse -Exclude DbCertificates to suppress certificate export while still exporting master keys.", "", false, "false", "False", "" ], [ "EncryptionPassword", "Secure password used to encrypt exported certificate private key files (.pvk) and database master key backups (.key).\r\nWhen specified with -IncludeDbMasterKey, enables export of private keys alongside certificates and also backs up database master keys.\r\nRequired for database master key export; optional for certificate export (without it only .cer files are generated).", "", false, "false", "", "" ], [ "DecryptionPassword", "Password required to decrypt the certificate\u0027s existing private key before it can be re-encrypted for backup.\r\nUse this when certificates were originally created with a password or imported from a password-protected source.\r\nOnly applies when -IncludeDbMasterKey is specified and DbCertificates is not in -Exclude.", "", false, "false", "", "" ], [ "Exclude", "Skips specific object types from the export to reduce scope or avoid problematic areas.\r\nUseful when you only need certain components or when specific features cause export issues in your environment.\r\nValid values: Databases, Logins, AgentServer, Credentials, LinkedServers, SpConfigure, CentralManagementServer, DatabaseMail, SysDbUserObjects, SystemTriggers, BackupDevices, Audits, Endpoints, \r\nExtendedEvents, PolicyManagement, ResourceGovernor, ServerAuditSpecifications, CustomErrors, ServerRoles, AvailabilityGroups, ReplicationSettings, OleDbProvider, DbCertificates.", "", false, "false", "", "AgentServer,Audits,AvailabilityGroups,BackupDevices,CentralManagementServer,Credentials,CustomErrors,DatabaseMail,Databases,DbCertificates,Endpoints,ExtendedEvents,LinkedServers,Logins,PolicyManagement,ReplicationSettings,ResourceGovernor,ServerAuditSpecifications,ServerRoles,SpConfigure,SysDbUserObjects,SystemTriggers,OleDbProvider" ], [ "BatchSeparator", "Defines the T-SQL batch separator used in generated scripts, defaults to \"GO\".\r\nChange this if your deployment tools or target environment requires a different batch separator like semicolon or custom delimiter.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027formatting.batchseparator\u0027)", "" ], [ "ScriptingOption", "Provides a Microsoft.SqlServer.Management.Smo.ScriptingOptions object to customize script generation behavior.\r\nUse this to control advanced scripting options like check constraints, triggers, indexes, or permissions that aren\u0027t controlled by other parameters.", "", false, "false", "", "" ], [ "NoPrefix", "Removes header comments from generated scripts that normally include creation timestamp and dbatools version.\r\nUse this for cleaner scripts when feeding into version control systems or automated deployment pipelines that don\u0027t need metadata headers.", "", false, "false", "False", "" ], [ "ExcludePassword", "Omits passwords from exported scripts for logins, credentials, and linked servers, replacing them with placeholder text.\r\nEssential for security compliance when export scripts will be stored in version control or shared with other team members.", "", false, "false", "False", "" ], [ "Force", "Overwrites existing export files and uses a static folder name without timestamp.\r\nIdeal for scheduled exports that always write to the same location, such as automated backup documentation or CI/CD integration.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": "LinkedServer", "CommandName": "Export-DbaLinkedServer", "Name": "Export-DbaLinkedServer", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Export-DbaLinkedServer [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-LinkedServer] \u003cString[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [[-Path] \u003cString\u003e] [[-FilePath] \u003cString\u003e] [-ExcludePassword] [-Append] [-Passthru] [[-InputObject] \u003cLinkedServer[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.String (when -Passthru is specified or when no -Path/-FilePath is provided)\nReturns the generated T-SQL script as a string or array of strings. The script contains the necessary T-SQL commands to recreate the linked server configuration on another SQL Server instance.\nSystem.IO.FileInfo (when -Path or -FilePath is specified)\nReturns file information for the exported T-SQL script file. Properties include:\r\n- FullName: Complete file path including filename\r\n- Name: The filename (e.g., \"sql2017_linkedservers.sql\")\r\n- Directory: The directory where the file is located\r\n- Length: File size in bytes\r\n- LastWriteTime: Timestamp of when the file was created or last modified", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eExport-DbaLinkedServer -SqlInstance sql2017 -Path C:\\temp\\ls.sql\nExports the linked servers, including passwords, from sql2017 to the file C:\\temp\\ls.sql\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eExport-DbaLinkedServer -SqlInstance sql2017 -Path C:\\temp\\ls.sql -ExcludePassword\nExports the linked servers, without passwords, from sql2017 to the file C:\\temp\\ls.sql\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eExport-DbaLinkedServer -SqlInstance sql2017 -Passthru\nReturns the T-SQL script for linked servers to the console instead of writing to a file", "Description": "Creates executable T-SQL scripts from existing linked server definitions, including remote login mappings and passwords. Perfect for migrating linked servers between environments, creating disaster recovery scripts, or documenting your linked server landscape. When passwords are included, the function accesses the local registry to decrypt stored credentials, so the generated scripts contain actual working passwords rather than placeholder values.", "Links": "https://dbatools.io/Export-DbaLinkedServer", "Synopsis": "Generates T-SQL scripts to recreate linked server configurations with their login credentials.", "Availability": "Windows only", "Params": [ [ "SqlInstance", "Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2005 or higher.", "", true, "true (ByValue)", "", "" ], [ "LinkedServer", "Specifies one or more linked server names to export, supporting wildcards for pattern matching. If not specified, all linked servers on the instance will be exported.\r\nUse this when you need to export specific linked servers rather than the entire linked server configuration from an instance.", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Credential", "Login to the target OS using alternative credentials. Accepts credential objects (Get-Credential)\nOnly used when passwords are being exported, as it requires access to the Windows OS via PowerShell remoting to decrypt the passwords.", "", false, "false", "", "" ], [ "Path", "Specifies the directory where the linked server export file will be created. Defaults to the configured DbatoolsExport path.\r\nUse this when you need the script saved to a specific folder location for organization or deployment purposes.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027Path.DbatoolsExport\u0027)", "" ], [ "FilePath", "Specifies the complete file path and name for the exported T-SQL script, including the .sql extension.\r\nUse this when you need precise control over the output filename and location, overriding the automatic naming from Path parameter.", "OutFile,FileName", false, "false", "", "" ], [ "ExcludePassword", "Excludes actual passwords from the exported script, replacing them with placeholder values for security purposes.\r\nUse this when sharing scripts across environments or with team members where you need the linked server structure but want to protect sensitive credentials.", "", false, "false", "False", "" ], [ "Append", "Adds the exported linked server scripts to an existing file instead of overwriting it.\r\nUse this when combining multiple linked server exports into a single deployment script or building comprehensive migration scripts over multiple runs.", "", false, "false", "False", "" ], [ "Passthru", "Returns the generated T-SQL script to the PowerShell pipeline instead of saving to file.\r\nUse this to capture the script in a variable, pipe to other commands, or display directly in the console.", "", false, "false", "False", "" ], [ "InputObject", "Accepts linked server objects piped from Get-DbaLinkedServer, allowing you to filter and process specific linked servers before export.\r\nUse this when you want to chain commands together, such as first getting linked servers with specific criteria then exporting only those results.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Export", "Login" ], "CommandName": "Export-DbaLogin", "Name": "Export-DbaLogin", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Export-DbaLogin [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-InputObject] \u003cObject[]\u003e] [[-Login] \u003cObject[]\u003e] [[-ExcludeLogin] \u003cObject[]\u003e] [[-Database] \u003cObject[]\u003e] [-ExcludeJobs] [-ExcludeDatabase] [-ExcludePassword] [[-DefaultDatabase] \u003cString\u003e] [[-Path] \u003cString\u003e] [[-FilePath] \u003cString\u003e] [[-Encoding] \u003cString\u003e] [-NoClobber] [-Append] [[-BatchSeparator] \u003cString\u003e] [[-DestinationVersion] \u003cString\u003e] [-NoPrefix] [-Passthru] [-ObjectLevel] [-IncludeRolePermissions] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.String (when -Passthru is specified or neither -Path nor -FilePath is specified)\nReturns the generated T-SQL script as a string. When -Passthru is specified, the script is sent to the pipeline. If -Path or -FilePath are not specified, the script is returned directly without being \r\nsaved to a file.\nSystem.IO.FileInfo (when -Path or -FilePath is specified)\nReturns file information objects for the created export files. Each file contains the generated T-SQL script for login recreation including:\r\n- CREATE LOGIN statements with password hashes (or placeholder text if -ExcludePassword is used)\r\n- DEFAULT_DATABASE setting (or the -DefaultDatabase override if specified)\r\n- Login enabled/disabled status\r\n- DENY CONNECT SQL restrictions if applicable\r\n- Server role memberships\r\n- SQL Agent job ownership assignments (unless -ExcludeJobs is specified)\r\n- Server-level permissions and securables (for SQL Server 2005+)\r\n- Credential associations\r\n- Database user mappings and database roles (unless -ExcludeDatabase is specified)\r\n- Object-level permissions (if -ObjectLevel is specified)\nThe script is formatted with the specified -BatchSeparator (default \u0027GO\u0027) between statements and includes a dbatools header comment unless -NoPrefix is specified.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eExport-DbaLogin -SqlInstance sql2005 -Path C:\\temp\\sql2005-logins.sql\nExports the logins for SQL Server \"sql2005\" and writes them to the file \"C:\\temp\\sql2005-logins.sql\"\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eExport-DbaLogin -SqlInstance sqlserver2014a -ExcludeLogin realcajun -SqlCredential $scred -Path C:\\temp\\logins.sql -Append\nAuthenticates to sqlserver2014a using SQL Authentication. Exports all logins except for realcajun to C:\\temp\\logins.sql, and appends to the file if it exists. If not, the file will be created.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eExport-DbaLogin -SqlInstance sqlserver2014a -Login realcajun, netnerds -Path C:\\temp\\logins.sql\nExports ONLY logins netnerds and realcajun FROM sqlserver2014a to the file C:\\temp\\logins.sql\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eExport-DbaLogin -SqlInstance sqlserver2014a -Login realcajun, netnerds -Database HR, Accounting\nExports ONLY logins netnerds and realcajun FROM sqlserver2014a with the permissions on databases HR and Accounting\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sqlserver2014a -Database HR, Accounting | Export-DbaLogin\nExports ONLY logins FROM sqlserver2014a with permissions on databases HR and Accounting\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eSet-DbatoolsConfig -FullName formatting.batchseparator -Value $null\nPS C:\\\u003e Export-DbaLogin -SqlInstance sqlserver2008 -Login realcajun, netnerds -Path C:\\temp\\login.sql\nExports ONLY logins netnerds and realcajun FROM sqlserver2008 server, to the C:\\temp\\login.sql file without the \u0027GO\u0027 batch separator.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eExport-DbaLogin -SqlInstance sqlserver2008 -Login realcajun -Path C:\\temp\\users.sql -DestinationVersion SQLServer2016\nExports login realcajun from sqlserver2008 to the file C:\\temp\\users.sql with syntax to run on SQL Server 2016\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sqlserver2008 -Login realcajun | Export-DbaLogin\nExports login realcajun from sqlserver2008\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003eGet-DbaLogin -SqlInstance sqlserver2008, sqlserver2012 | Where-Object { $_.IsDisabled -eq $false } | Export-DbaLogin\nExports all enabled logins from sqlserver2008 and sqlserver2008", "Description": "Creates executable T-SQL scripts that recreate SQL Server and Windows logins along with their complete security configuration. The export includes login properties (SID, hashed passwords, default database), server-level permissions and role memberships, database user mappings and roles, plus SQL Agent job ownership assignments. This addresses the common challenge where restoring databases doesn\u0027t restore the associated logins, leaving applications unable to connect. DBAs use this for server migrations, disaster recovery scenarios, and maintaining consistent security across environments.", "Links": "https://dbatools.io/Export-DbaLogin", "Synopsis": "Generates T-SQL scripts to recreate SQL Server logins with their complete security context for migration and disaster recovery.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. SQL Server 2000 and above supported.", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "InputObject", "Accepts piped objects from Get-DbaLogin, Get-DbaDatabase, or Connect-DbaInstance commands.\r\nUse this when you want to export logins from specific objects rather than specifying instances directly.", "", false, "true (ByValue)", "", "" ], [ "Login", "Specifies which SQL Server logins to export by name. Accepts wildcards and arrays.\r\nWhen specified, only these logins are processed instead of all server logins. Use this to target specific accounts for migration or backup.", "", false, "false", "", "" ], [ "ExcludeLogin", "Specifies login names to skip during export. Accepts wildcards and arrays.\r\nUse this to exclude system accounts, service accounts, or other logins that shouldn\u0027t be migrated to the target environment.", "", false, "false", "", "" ], [ "Database", "Limits export to logins that have user mappings in the specified databases. Accepts database names or database objects.\r\nWhen specified, only logins with permissions or user accounts in these databases are exported, reducing script size for targeted migrations.", "", false, "false", "", "" ], [ "ExcludeJobs", "Excludes SQL Agent job ownership assignments from the export script.\r\nUse this when migrating logins to servers where the associated jobs don\u0027t exist or will be owned by different accounts.", "", false, "false", "False", "" ], [ "ExcludeDatabase", "Excludes database user mappings and permissions from the export script.\r\nUse this when you only need server-level login definitions without their database-specific permissions and role memberships.", "ExcludeDatabases", false, "false", "False", "" ], [ "ExcludePassword", "Excludes hashed password values from SQL login export, replacing them with placeholder text.\r\nUse this for security compliance when sharing scripts or when passwords will be reset after migration.", "", false, "false", "False", "" ], [ "DefaultDatabase", "Overrides the default database for all exported logins with the specified database name.\r\nUse this when migrating to servers where the original default databases don\u0027t exist, preventing login creation failures.", "", false, "false", "", "" ], [ "Path", "Specifies the directory where export files will be saved. Defaults to the Path.DbatoolsExport configuration setting.\r\nFiles are automatically named based on instance and timestamp unless FilePath is specified.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027Path.DbatoolsExport\u0027)", "" ], [ "FilePath", "Specifies the complete file path for the export script. Cannot be used when exporting from multiple instances.\r\nUse this when you need precise control over the output file location and name.", "OutFile,FileName", false, "false", "", "" ], [ "Encoding", "Sets the character encoding for the output file. Defaults to UTF8.\r\nChoose the appropriate encoding based on your deployment environment requirements and any special characters in login names.", "", false, "false", "UTF8", "ASCII,BigEndianUnicode,Byte,String,Unicode,UTF7,UTF8,Unknown" ], [ "NoClobber", "Prevents overwriting existing files at the specified Path location.\r\nUse this as a safety measure when you don\u0027t want to accidentally replace existing login export scripts.", "NoOverwrite", false, "false", "False", "" ], [ "Append", "Adds the generated script to an existing file instead of overwriting it.\r\nUse this to combine login exports from multiple instances into a single deployment script.", "", false, "false", "False", "" ], [ "BatchSeparator", "Sets the T-SQL batch separator used between statements. Defaults to \u0027GO\u0027 from the Formatting.BatchSeparator configuration.\r\nSpecify an empty string to remove batch separators when the target system doesn\u0027t support them.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027Formatting.BatchSeparator\u0027)", "" ], [ "DestinationVersion", "Generates T-SQL syntax compatible with the specified SQL Server version. Defaults to the source instance version.\r\nUse this when migrating to older SQL Server versions that require different syntax for role assignments or other features.", "", false, "false", "", "SQLServer2000,SQLServer2005,SQLServer2008/2008R2,SQLServer2012,SQLServer2014,SQLServer2016,SQLServer2017,SQLServer2019,SQLServer2022" ], [ "NoPrefix", "Excludes the standard dbatools header comment from the generated script.\r\nUse this when you need clean T-SQL output without metadata comments for automated deployment systems.", "", false, "false", "False", "" ], [ "Passthru", "Returns the generated T-SQL script to the PowerShell pipeline instead of saving to file.\r\nUse this to capture the script in a variable, pipe to other commands, or display directly in the console.", "", false, "false", "False", "" ], [ "ObjectLevel", "Includes detailed object-level permissions for each database user associated with the exported logins.\r\nUse this for complete permission migration when you need granular security settings preserved in the target environment.", "", false, "false", "False", "" ], [ "IncludeRolePermissions", "Includes permissions granted to database roles that the login\u0027s database users are members of.\r\nBy default, Export-DbaLogin scripts role membership (ALTER ROLE ... ADD MEMBER) but not the permissions granted to those roles.\r\nUse this switch to also export GRANT/DENY statements for each non-fixed role, ensuring the roles have the correct permissions on the target server.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Performance", "DataCollector" ], "CommandName": "Export-DbaPfDataCollectorSetTemplate", "Name": "Export-DbaPfDataCollectorSetTemplate", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Export-DbaPfDataCollectorSetTemplate [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-CollectorSet] \u003cString[]\u003e] [[-Path] \u003cString\u003e] [[-FilePath] \u003cString\u003e] [[-InputObject] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.IO.FileInfo\nReturns one FileInfo object for each exported XML template file. The file contains the complete configuration of the data collector set including counter selections, sampling intervals, and output \r\nsettings.\nProperties:\r\n- Name: The filename of the exported template (e.g., \u0027System Correlation.xml\u0027)\r\n- FullName: The complete path to the exported XML file\r\n- Directory: The parent folder where the file was created\r\n- Length: File size in bytes\r\n- CreationTime: When the file was created\r\n- LastWriteTime: When the file was last modified\r\n- Extension: File extension (.xml)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eExport-DbaPfDataCollectorSetTemplate -ComputerName sql2017 -Path C:\\temp\\pf\nExports all data collector sets from to the C:\\temp\\pf folder.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorSet ComputerName sql2017 -CollectorSet \u0027System Correlation\u0027 | Export-DbaPfDataCollectorSetTemplate -Path C:\\temp\nExports the \u0027System Correlation\u0027 data collector set from sql2017 to C:\\temp.", "Description": "Exports Data Collector Set configurations from Windows Performance Monitor as XML template files that can be imported on other SQL Server hosts. This allows you to standardize performance monitoring across your SQL Server environment by saving custom counter collections, sampling intervals, and output settings as portable templates. Particularly useful for creating consistent performance baselines and troubleshooting configurations that can be quickly deployed when performance issues arise.", "Links": "https://dbatools.io/Export-DbaPfDataCollectorSetTemplate", "Synopsis": "Exports Windows Performance Monitor Data Collector Set configurations as reusable XML templates.", "Availability": "Windows only", "Params": [ [ "ComputerName", "Specifies the target computer(s) to export data collector sets from. Defaults to localhost.\r\nUse this to export performance monitoring templates from remote SQL Server hosts for standardization across your environment.", "", false, "false", "$env:COMPUTERNAME", "" ], [ "Credential", "Allows you to login to $ComputerName using alternative credentials. To use:\n$cred = Get-Credential, then pass $cred object to the -Credential parameter.", "", false, "false", "", "" ], [ "CollectorSet", "Specifies the name(s) of specific data collector sets to export. If not specified, all collector sets will be exported.\r\nUse this when you only need to export particular performance monitoring configurations rather than all available sets.", "DataCollectorSet", false, "false", "", "" ], [ "Path", "Specifies the directory where XML template files will be created. Each collector set exports as a separate XML file.\r\nDefaults to the configured dbatools export path, typically used when exporting multiple collector sets.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027Path.DbatoolsExport\u0027)", "" ], [ "FilePath", "Specifies the complete file path including filename for the exported XML template. Use instead of Path when exporting a single collector set.\r\nAutomatically appends .xml extension if not provided, ideal for creating named templates for specific monitoring scenarios.", "OutFile,FileName", false, "false", "", "" ], [ "InputObject", "Accepts data collector set objects from Get-DbaPfDataCollectorSet via pipeline input. Enables pipeline workflows for filtering and processing collector sets.\r\nUse this when you need to chain commands together, such as filtering collector sets before exporting them.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "RegisteredServer", "CMS" ], "CommandName": "Export-DbaRegServer", "Name": "Export-DbaRegServer", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Export-DbaRegServer [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-InputObject] \u003cObject[]\u003e] [[-Path] \u003cString\u003e] [[-FilePath] \u003cFileInfo\u003e] [[-CredentialPersistenceType] \u003cString\u003e] [[-Group] \u003cObject[]\u003e] [[-ExcludeGroup] \u003cObject[]\u003e] [-Overwrite] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.IO.FileInfo\nReturns one file object for each exported registered server or server group. The file object contains information about the exported XML file that was created.\nProperties:\r\n- Name: The filename of the exported registered server file\r\n- FullName: The complete file path to the exported file\r\n- Directory: The directory containing the exported file\r\n- Extension: The file extension (.xml or .regsrvr)\r\n- Length: The size of the exported file in bytes\r\n- CreationTime: When the file was created\r\n- LastWriteTime: When the file was last modified\r\n- Attributes: File attributes (Archive, etc.)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eExport-DbaRegServer -SqlInstance sql2008\nExports all Registered Server and Registered Server Groups on sql2008 to an automatically generated file name in the current directory\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaRegServer -SqlInstance sql2008, sql2012 | Export-DbaRegServer\nExports all registered servers on sql2008 and sql2012. Warning - each one will have its own individual file. Consider piping groups.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaRegServerGroup -SqlInstance sql2008, sql2012 | Export-DbaRegServer\nExports all registered servers on sql2008 and sql2012, organized by group.", "Description": "Exports registered servers and registered server groups to file", "Links": "https://dbatools.io/Export-DbaRegServer", "Synopsis": "Exports registered servers and registered server groups to file", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "InputObject", "Accepts registered server or server group objects from Get-DbaRegServer, Get-DbaRegServerGroup, or custom objects via pipeline.\r\nUse this to export specific servers or groups that have been filtered or modified before export.\r\nFor custom objects, requires a ServerName column with optional Name, Description, and Group columns.", "", false, "true (ByValue)", "", "" ], [ "Path", "Specifies the directory where the exported registered server files will be saved.\r\nUses the dbatools default export directory if not specified, typically your user profile\u0027s Documents folder.\r\nAutomatically generates timestamped filenames when exporting multiple servers or groups.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027Path.DbatoolsExport\u0027)", "" ], [ "FilePath", "Specifies the complete file path for the exported registered server file, including filename and extension.\r\nMust end with .xml or .regsrvr extension to be compatible with SQL Server Management Studio imports.\r\nWhen exporting multiple groups, the group name is automatically appended to avoid file conflicts.", "OutFile,FileName", false, "false", "", "" ], [ "CredentialPersistenceType", "Controls how login credentials are stored in the exported registered server file.\r\nUse \u0027PersistLoginName\u0027 to save usernames only, or \u0027PersistLoginNameAndPassword\u0027 to include passwords for automated connections.\r\nDefaults to \u0027None\u0027 for security, requiring manual credential entry when connecting.", "", false, "false", "None", "None,PersistLoginName,PersistLoginNameAndPassword" ], [ "Group", "Filters export to include only registered servers from the specified server group names.\r\nUse this when you want to export servers from specific organizational groups like \u0027Production\u0027, \u0027Development\u0027, or \u0027QA\u0027.\r\nAccepts wildcards and multiple group names to export several groups in a single operation.", "", false, "false", "", "" ], [ "ExcludeGroup", "Excludes registered servers from the specified server group names during export.\r\nUseful when exporting most groups but need to skip sensitive environments like \u0027Production\u0027 or \u0027Customer-Facing\u0027.\r\nCan be combined with the Group parameter to fine-tune which servers are included in the export.", "", false, "false", "", "" ], [ "Overwrite", "Allows the function to replace an existing file at the specified FilePath location.\r\nRequired when the target export file already exists, preventing accidental data loss.\r\nWithout this switch, the function will stop with an error if the destination file is found.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Replication", "Repl" ], "CommandName": "Export-DbaReplServerSetting", "Name": "Export-DbaReplServerSetting", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Export-DbaReplServerSetting [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Path] \u003cString\u003e] [[-FilePath] \u003cString\u003e] [[-ScriptOption] \u003cObject[]\u003e] [[-InputObject] \u003cObject[]\u003e] [[-Encoding] \u003cString\u003e] [-Passthru] [-NoClobber] [-Append] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "Export-DbaRepServerSetting", "Outputs": "System.String (when -Passthru is specified)\nReturns the generated T-SQL replication script as a string. The script includes:\r\n- An \u0027exec sp_dropdistributor\u0027 statement with @no_checks = 1 and @ignore_distributor = 1\r\n- T-SQL commands to recreate the distributor configuration\r\n- T-SQL commands to recreate all publications and their settings\r\n- T-SQL commands to recreate all subscriptions\r\n- All related replication objects and configurations based on the specified -ScriptOption flags\nNone (when -Passthru is not specified)\nNo output is returned to the pipeline when saving to a file. The T-SQL script is written to the specified file path containing the complete replication configuration needed to recreate the \r\nreplication setup on another server.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eExport-DbaReplServerSetting -SqlInstance sql2017 -Path C:\\temp\\replication.sql\nExports the replication settings on sql2017 to the file C:\\temp\\replication.sql\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaReplServer -SqlInstance sql2017 | Export-DbaReplServerSetting -Path C:\\temp\\replication.sql\nExports the replication settings on sql2017 to the file C:\\temp\\replication.sql", "Description": "Creates T-SQL scripts that can recreate your SQL Server replication setup, including distributor configuration, publications, subscriptions, and all related settings. The generated scripts include both creation commands and a distributor cleanup statement, making this perfect for disaster recovery planning, environment migrations, or replication topology documentation.\n\nThe function scripts out the complete replication configuration using SQL Server\u0027s replication management objects, so you can rebuild identical replication setups on different servers or restore replication after system failures.\n\nAll replication commands need SQL Server Management Studio installed and are therefore currently not supported.\nHave a look at this issue to get more information: https://github.com/dataplat/dbatools/issues/7428", "Links": "https://dbatools.io/Export-DbaReplServerSetting", "Synopsis": "Generates T-SQL scripts to recreate SQL Server replication distributor and publication configurations", "Availability": "Windows only", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Path", "Specifies the directory where the replication script file will be created. Defaults to the dbatools export path configuration.\r\nUse this when you want to organize replication scripts in a specific directory structure for disaster recovery or documentation purposes.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027Path.DbatoolsExport\u0027)", "" ], [ "FilePath", "Specifies the complete file path including filename for the exported replication script. Overrides both Path parameter and default naming.\r\nUse this when you need precise control over the output file location and name, especially for automated backup processes.", "OutFile,FileName", false, "false", "", "" ], [ "ScriptOption", "Specifies custom Microsoft.SqlServer.Replication.ScriptOptions flags to control which replication components are scripted.\r\nAdvanced parameter for fine-tuning script output when the default options don\u0027t meet specific requirements.", "", false, "false", "", "" ], [ "InputObject", "Accepts replication server objects from Get-DbaReplServer pipeline input for batch processing.\r\nUse this when scripting replication settings from multiple servers or when combining with other replication commands in a pipeline.", "", false, "true (ByValue)", "", "" ], [ "Encoding", "Specifies the character encoding for the output script file. Defaults to UTF8 which handles international characters properly.\r\nUse ASCII for maximum compatibility with older systems, or Unicode when working with databases containing non-English characters.", "", false, "false", "UTF8", "ASCII,BigEndianUnicode,Byte,String,Unicode,UTF7,UTF8,Unknown" ], [ "Passthru", "Returns the generated T-SQL replication script to the console instead of writing to a file.\r\nUse this for immediate review of the script content or when piping output to other commands for further processing.", "", false, "false", "False", "" ], [ "NoClobber", "Prevents overwriting an existing file with the same name. The operation will fail if the target file already exists.\r\nUse this as a safety measure to avoid accidentally replacing existing replication scripts during routine exports.", "", false, "false", "False", "" ], [ "Append", "Adds the replication script to the end of an existing file instead of overwriting it.\r\nUse this when consolidating multiple replication configurations into a single script file for bulk operations.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Migration", "Backup", "Export" ], "CommandName": "Export-DbaScript", "Name": "Export-DbaScript", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Export-DbaScript [-InputObject] \u003cObject[]\u003e [[-ScriptingOptionsObject] \u003cScriptingOptions\u003e] [[-Path] \u003cString\u003e] [[-FilePath] \u003cString\u003e] [[-Encoding] \u003cString\u003e] [[-BatchSeparator] \u003cString\u003e] [-NoPrefix] [-Passthru] [-NoClobber] [-Append] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.String (when -Passthru is specified)\nReturns the generated T-SQL script as a string. When multiple objects are piped in, returns multiple strings separated by newlines.\r\nEach script includes a comment prefix (unless -NoPrefix is used) with generation timestamp, username, and dbatools version.\r\nScript sections are separated by the configured batch terminator (typically \"GO\").\nSystem.IO.FileInfo (default when -Passthru is not specified)\nReturns one file object per input object representing the generated SQL script file(s) written to disk.\r\nWhen multiple objects are piped in, multiple file objects are returned.\nProperties:\r\n- Name: The filename of the exported script (e.g., \"sql2016-Export-DbaScript-20231215_143022.sql\")\r\n- FullName: The complete path to the exported script file\r\n- Directory: The directory object containing the file\r\n- CreationTime: When the file was created\r\n- LastWriteTime: When the file was last modified\r\n- Length: Size of the file in bytes\r\n- Extension: Always \".sql\"", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAgentJob -SqlInstance sql2016 | Export-DbaScript\nExports all jobs on the SQL Server sql2016 instance using a trusted connection - automatically determines filename based on the Path.DbatoolsExport configuration setting, current time and server name.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgentJob -SqlInstance sql2016 | Export-DbaScript -FilePath C:\\temp\\export.sql -Append\nExports all jobs on the SQL Server sql2016 instance using a trusted connection - Will append the output to the file C:\\temp\\export.sql if it already exists\r\nInclusion of Batch Separator in script depends on the configuration s not include Batch Separator and will not compile\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbTable -SqlInstance sql2016 -Database MyDatabase -Table \u0027dbo.Table1\u0027, \u0027dbo.Table2\u0027 -SqlCredential sqladmin | Export-DbaScript -FilePath C:\\temp\\export.sql\nExports only script for \u0027dbo.Table1\u0027 and \u0027dbo.Table2\u0027 in MyDatabase to C:temp\\export.sql and uses the SQL login \"sqladmin\" to login to sql2016\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaAgentJob -SqlInstance sql2016 -Job syspolicy_purge_history, \u0027Hourly Log Backups\u0027 -SqlCredential sqladmin | Export-DbaScript -FilePath C:\\temp\\export.sql -NoPrefix\nExports only syspolicy_purge_history and \u0027Hourly Log Backups\u0027 to C:temp\\export.sql and uses the SQL login \"sqladmin\" to login to sql2016\r\nSuppress the output of a Prefix\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$options = New-DbaScriptingOption\nPS C:\\\u003e $options.ScriptSchema = $true\r\nPS C:\\\u003e $options.IncludeDatabaseContext = $true\r\nPS C:\\\u003e $options.IncludeHeaders = $false\r\nPS C:\\\u003e $Options.NoCommandTerminator = $false\r\nPS C:\\\u003e $Options.ScriptBatchTerminator = $true\r\nPS C:\\\u003e $Options.AnsiFile = $true\r\nPS C:\\\u003e Get-DbaAgentJob -SqlInstance sql2016 -Job syspolicy_purge_history, \u0027Hourly Log Backups\u0027 -SqlCredential sqladmin | Export-DbaScript -FilePath C:\\temp\\export.sql -ScriptingOptionsObject $options\nExports only syspolicy_purge_history and \u0027Hourly Log Backups\u0027 to C:temp\\export.sql and uses the SQL login \"sqladmin\" to login to sql2016\r\nUses Scripting options to ensure Batch Terminator is set\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaAgentJob -SqlInstance sql2014 | Export-DbaScript -Passthru | ForEach-Object { $_.Replace(\u0027sql2014\u0027,\u0027sql2016\u0027) } | Set-Content -Path C:\\temp\\export.sql\nExports jobs and replaces all instances of the servername \"sql2014\" with \"sql2016\" then writes to C:\\temp\\export.sql\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003e$options = New-DbaScriptingOption\nPS C:\\\u003e $options.ScriptSchema = $true\r\nPS C:\\\u003e $options.IncludeDatabaseContext = $true\r\nPS C:\\\u003e $options.IncludeHeaders = $false\r\nPS C:\\\u003e $Options.NoCommandTerminator = $false\r\nPS C:\\\u003e $Options.ScriptBatchTerminator = $true\r\nPS C:\\\u003e $Options.AnsiFile = $true\r\nPS C:\\\u003e $Databases = Get-DbaDatabase -SqlInstance sql2016 -ExcludeDatabase master, model, msdb, tempdb\r\nPS C:\\\u003e foreach ($db in $Databases) {\r\n\u003e\u003e Export-DbaScript -InputObject $db -FilePath C:\\temp\\export.sql -Append -Encoding UTF8 -ScriptingOptionsObject $options -NoPrefix\r\n\u003e\u003e }\nExports Script for each database on sql2016 excluding system databases\r\nUses Scripting options to ensure Batch Terminator is set\r\nWill append the output to the file C:\\temp\\export.sql if it already exists", "Description": "Takes any SQL Server Management Object from dbatools commands and converts it into executable T-SQL CREATE scripts using SMO scripting. This lets you script out database objects like tables, jobs, logins, stored procedures, and more for migration between environments or backup purposes. The function handles proper formatting with batch separators and supports custom scripting options to control what gets included in the output. Perfect for creating deployment scripts or documenting your SQL Server configurations without manual scripting.", "Links": "https://dbatools.io/Export-DbaScript", "Synopsis": "Generates T-SQL CREATE scripts from SQL Server Management Objects for migration and deployment", "Availability": "Windows, Linux, macOS", "Params": [ [ "InputObject", "Accepts any SQL Server Management Object (SMO) from dbatools commands like Get-DbaLogin, Get-DbaAgentJob, or Get-DbaDatabase.\r\nUse this when you need to generate CREATE scripts for specific database objects, jobs, logins, or other SQL Server components.\r\nThe object type determines what kind of T-SQL script will be generated.", "", true, "true (ByValue)", "", "" ], [ "ScriptingOptionsObject", "Accepts a customized SMO ScriptingOptions object created with New-DbaScriptingOption to control script generation.\r\nUse this when you need specific formatting like including schema context, headers, or data along with object definitions.\r\nSettings in this object override other Export-DbaScript parameters like BatchSeparator.", "ScriptingOptionObject", false, "false", "", "" ], [ "Path", "Sets the directory where script files will be saved when FilePath is not specified.\r\nDefaults to the configured dbatools export directory from your Path.DbatoolsExport setting.\r\nUse this when you want scripts saved to a standard location with auto-generated filenames.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027Path.DbatoolsExport\u0027)", "" ], [ "FilePath", "Sets the complete file path and name for the output script file.\r\nUse this when you need the script saved to a specific location with a custom filename.\r\nOverrides the Path parameter when specified.", "OutFile,FileName", false, "false", "", "" ], [ "Encoding", "Controls the character encoding used when writing script files to disk.\r\nDefault is UTF8 which handles international characters and is widely supported.\r\nUse UTF8 for most scenarios, or ASCII if you need compatibility with older tools that don\u0027t support Unicode.", "", false, "false", "UTF8", "ASCII,BigEndianUnicode,Byte,String,Unicode,UTF7,UTF8,Unknown" ], [ "BatchSeparator", "Sets the batch terminator added between SQL statements in the output script.\r\nDefaults to \"GO\" from your dbatools configuration, which is standard for SQL Server Management Studio.\r\nUse a different separator if deploying to tools that require different batch terminators.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027Formatting.BatchSeparator\u0027)", "" ], [ "NoPrefix", "Suppresses the header comment block that normally identifies when and by whom the script was generated.\r\nUse this when you need clean scripts without metadata comments for automated deployments.\r\nThe prefix normally includes timestamp, username, and dbatools version information.", "", false, "false", "False", "" ], [ "Passthru", "Returns the generated T-SQL script as string output instead of writing to a file.\r\nUse this when you need to capture the script in a variable for further processing or modification.\r\nCommonly used in pipelines to transform scripts before saving.", "", false, "false", "False", "" ], [ "NoClobber", "Prevents overwriting existing files, causing the command to fail if the target file already exists.\r\nUse this as a safety measure when you want to ensure you don\u0027t accidentally replace existing scripts.\r\nCombine with -Append if you want to add to existing files instead.", "", false, "false", "False", "" ], [ "Append", "Adds the generated script to the end of an existing file instead of overwriting it.\r\nUse this when building consolidated deployment scripts by combining multiple objects into one file.\r\nParticularly useful for scripting multiple databases or object types into a single migration script.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "Shows what would happen if the command were to run. No actions are actually performed", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before executing any changing operations within the command", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Export", "Role" ], "CommandName": "Export-DbaServerRole", "Name": "Export-DbaServerRole", "Author": "Patrick Flynn (@sqllensman)", "Syntax": "Export-DbaServerRole [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-InputObject] \u003cObject[]\u003e] [[-ScriptingOptionsObject] \u003cScriptingOptions\u003e] [[-ServerRole] \u003cString[]\u003e] [[-ExcludeServerRole] \u003cString[]\u003e] [-ExcludeFixedRole] [-IncludeRoleMember] [[-Path] \u003cString\u003e] [[-FilePath] \u003cString\u003e] [-Passthru] [[-BatchSeparator] \u003cString\u003e] [-NoClobber] [-Append] [-NoPrefix] [[-Encoding] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.String\nWhen -Passthru is specified, or when neither -Path nor -FilePath is provided, returns the generated T-SQL script as a string.\nProperties of the output include:\r\n- Role creation statements with IF NOT EXISTS clauses\r\n- GRANT, DENY, and REVOKE permission statements for each role\u0027s permissions\r\n- Optional ALTER SERVER ROLE statements to add current role members (when -IncludeRoleMember is specified)\r\n- Optional header comment block with generation metadata (unless -NoPrefix is specified)\r\n- Batch separator statements between T-SQL commands (configurable via -BatchSeparator)\nSystem.IO.FileInfo\nWhen -Path or -FilePath is specified (and -Passthru is not used), returns FileInfo objects for each script file created, one per instance processed.\nProperties:\r\n- FullName: Complete file path where the script was saved\r\n- Name: File name of the exported script\r\n- Directory: Directory containing the script file\r\n- Length: Size of the file in bytes\r\n- CreationTime: Timestamp when the file was created\r\n- LastWriteTime: Timestamp of the last modification", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eExport-DbaServerRole -SqlInstance sql2005\nExports the Server Roles for SQL Server \"sql2005\" and writes them to the path defined in the ConfigValue \u0027Path.DbatoolsExport\u0027 using a a default name pattern of ServerName-YYYYMMDDhhmmss-serverrole. \r\nUses BatchSeparator defined by Config \u0027Formatting.BatchSeparator\u0027\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eExport-DbaServerRole -SqlInstance sql2005 -Path C:\\temp\nExports the Server Roles for SQL Server \"sql2005\" and writes them to the path \"C:\\temp\" using a a default name pattern of ServerName-YYYYMMDDhhmmss-serverrole. Uses BatchSeparator defined by Config \r\n\u0027Formatting.BatchSeparator\u0027\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eExport-DbaServerRole -SqlInstance sqlserver2014a -FilePath C:\\temp\\ServerRoles.sql\nExports the Server Roles for SQL Server sqlserver2014a to the file C:\\temp\\ServerRoles.sql. Overwrites file if exists\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eExport-DbaServerRole -SqlInstance sqlserver2014a -ServerRole SchemaReader -Passthru\nExports ONLY ServerRole SchemaReader FROM sqlserver2014a and writes script to console\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eExport-DbaServerRole -SqlInstance sqlserver2008 -ExcludeFixedRole -ExcludeServerRole Public -IncludeRoleMember -FilePath C:\\temp\\ServerRoles.sql -Append -BatchSeparator \u0027\u0027\nExports server roles from sqlserver2008, excludes all roles marked as as FixedRole and Public role. Includes RoleMembers and writes to file C:\\temp\\ServerRoles.sql, appending to file if it exits. \r\nDoes not include a BatchSeparator\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaServerRole -SqlInstance sqlserver2012, sqlserver2014 | Export-DbaServerRole\nExports server roles from sqlserver2012, sqlserver2014 and writes them to the path defined in the ConfigValue \u0027Path.DbatoolsExport\u0027 using a a default name pattern of \r\nServerName-YYYYMMDDhhmmss-serverrole\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eGet-DbaServerRole -SqlInstance sqlserver2016 -ExcludeFixedRole -ExcludeServerRole Public | Export-DbaServerRole -IncludeRoleMember\nExports server roles from sqlserver2016, excludes all roles marked as as FixedRole and Public role. Includes RoleMembers", "Description": "Creates complete T-SQL scripts that can recreate server-level roles along with their permissions and memberships on another instance. This eliminates the need to manually recreate security configurations during server migrations or disaster recovery scenarios. The function queries sys.server_permissions to capture all role permissions (GRANT, DENY, REVOKE) and generates the appropriate T-SQL statements for role creation and member assignments.\n\nPrimarily targets SQL Server 2012 and higher where user-defined server roles were introduced, but works on earlier versions to script role memberships for built-in roles.\nThis command extends John Eisbrener\u0027s post \"Fully Script out a MSSQL Database Role\"\nReference: https://dbaeyes.wordpress.com/2013/04/19/fully-script-out-a-mssql-database-role/", "Links": "https://dbatools.io/Export-DbaServerRole", "Synopsis": "Generates T-SQL scripts for server-level roles including permissions and memberships", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. SQL Server 2000 and above supported.", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "InputObject", "Accepts server role objects from Get-DbaServerRole for pipeline processing. Use this when you need to filter roles first with Get-DbaServerRole before exporting.", "", false, "true (ByValue)", "", "" ], [ "ScriptingOptionsObject", "Provides custom SMO scripting options to control the generated T-SQL output format. Use New-DbaScriptingOption to create custom options when you need specific formatting requirements like excluding \r\nobject owners or database context.", "", false, "false", "", "" ], [ "ServerRole", "Specifies which server-level roles to export by name. Useful when you only need to script specific custom roles instead of all roles on the instance.", "", false, "false", "", "" ], [ "ExcludeServerRole", "Excludes specific server-level roles from the export by name. Use this to skip problematic roles or roles you don\u0027t want to migrate to the target instance.", "", false, "false", "", "" ], [ "ExcludeFixedRole", "Excludes built-in server roles like sysadmin, serveradmin, and dbcreator from the export. Use this when migrating between instances where you only want to transfer custom user-defined roles. On SQL \r\nServer 2008/2008R2, this will exclude all roles since user-defined server roles weren\u0027t supported.", "", false, "false", "False", "" ], [ "IncludeRoleMember", "Includes ALTER SERVER ROLE statements to add current role members to the exported script. Essential when you need to recreate both the roles and their membership assignments on the target instance.", "", false, "false", "False", "" ], [ "Path", "Specifies the directory where script files will be saved. Defaults to the Path.DbatoolsExport configuration setting. Use this when you want to organize exports in a specific folder structure for your \r\ndeployment process.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027Path.DbatoolsExport\u0027)", "" ], [ "FilePath", "Specifies the complete file path for the exported script. When blank, creates timestamped files using the instance name. Use this when you need consistent file naming for deployment pipelines or when \r\nexporting from a single instance.", "OutFile,FileName", false, "false", "", "" ], [ "Passthru", "Displays the generated T-SQL script in the console instead of saving to file. Perfect for quick review of the script or when you need to copy-paste the output directly into SSMS.", "", false, "false", "False", "" ], [ "BatchSeparator", "Sets the batch separator used between T-SQL statements in the output. Defaults to the configured value, typically \u0027GO\u0027. Change this when deploying to tools that use different batch separators or set \r\nto empty string to remove separators entirely.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027Formatting.BatchSeparator\u0027)", "" ], [ "NoClobber", "Prevents overwriting existing files at the target location. Use this as a safety measure when running automated exports to avoid accidentally replacing important deployment scripts.", "", false, "false", "False", "" ], [ "Append", "Adds the exported script to an existing file instead of overwriting it. Useful when building comprehensive deployment scripts that combine multiple exports into a single file.", "", false, "false", "False", "" ], [ "NoPrefix", "Excludes the header comment block that contains generation metadata like timestamp and user information. Use this when you need clean T-SQL output without documentation headers for automated \r\ndeployments.", "", false, "false", "False", "" ], [ "Encoding", "Sets the character encoding for the output file. Defaults to UTF8 which handles international characters correctly. Change to ASCII only if you\u0027re certain the role names contain no special characters \r\nand need compatibility with older systems.", "", false, "false", "UTF8", "ASCII,BigEndianUnicode,Byte,String,Unicode,UTF7,UTF8,Unknown" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "SpConfig", "Configure", "Configuration" ], "CommandName": "Export-DbaSpConfigure", "Name": "Export-DbaSpConfigure", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Export-DbaSpConfigure [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Path] \u003cString\u003e] [[-FilePath] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.IO.FileInfo\nReturns one file object for each SQL Server instance processed. The file contains the complete SQL script with EXEC sp_configure statements that can be executed on another SQL Server instance to \r\nreplicate the exact configuration settings.\nProperties:\r\n- Name: The name of the exported SQL script file (format: Servername-MMDDYYYYhhmmss-sp_configure.sql)\r\n- FullName: The complete file path to the exported SQL script\r\n- Directory: The parent directory object where the file is stored\r\n- Length: The size of the SQL script file in bytes\r\n- CreationTime: DateTime when the file was created\r\n- LastWriteTime: DateTime when the file was last modified\r\n- Extension: The file extension (.sql)\r\n- Attributes: File attributes (Archive, etc.)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eExport-DbaSpConfigure -SqlInstance sourceserver\nExports the SPConfigure settings on sourceserver. As no Path was defined outputs to My Documents folder with default name format of Servername-MMDDYYYYhhmmss-sp_configure.sql\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eExport-DbaSpConfigure -SqlInstance sourceserver -Path C:\\temp\nExports the SPConfigure settings on sourceserver to the directory C:\\temp using the default name format\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Export-DbaSpConfigure -SqlInstance sourceserver -SqlCredential $cred -Path C:\\temp\\sp_configure.sql\nExports the SPConfigure settings on sourceserver to the file C:\\temp\\sp_configure.sql. Uses SQL Authentication to connect. Will require SysAdmin rights if needs to set \u0027show advanced options\u0027\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e\u0027Server1\u0027, \u0027Server2\u0027 | Export-DbaSpConfigure -Path C:\\temp\\configure.sql\nExports the SPConfigure settings for Server1 and Server2 using pipeline. As more than 1 Server adds prefix of Servername and date to the file name and saves to file like \r\nC:\\temp\\Servername-MMDDYYYYhhmmss-configure.sql", "Description": "Creates a complete SQL script file with EXEC sp_configure statements for all server configuration options, including advanced settings. This script can be executed on another SQL Server instance to replicate the exact same configuration settings, making it invaluable for environment standardization, disaster recovery preparation, or compliance documentation. The function temporarily enables \u0027show advanced options\u0027 if needed to capture all available settings, then restores the original setting.", "Links": "https://dbatools.io/Export-DbaSpConfigure", "Synopsis": "Generates SQL script containing all sp_configure settings for SQL Server instance configuration replication and documentation.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input.\r\nYou must have sysadmin access if needs to set \u0027show advanced options\u0027 to 1 and server version must be SQL Server version 2005 or higher.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Path", "Specifies the directory where the sp_configure script files will be exported. Defaults to the configured DbatoolsExport path.\r\nUse this when you need to organize configuration scripts in a specific location for documentation or deployment procedures.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027Path.DbatoolsExport\u0027)", "" ], [ "FilePath", "Specifies the complete file path including filename for the exported sp_configure script. Overrides the Path parameter when specified.\r\nUse this when you need precise control over the output filename, especially for automated deployment scripts or standardized naming conventions.", "OutFile,FileName", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Export", "Object", "SystemDatabase" ], "CommandName": "Export-DbaSysDbUserObject", "Name": "Export-DbaSysDbUserObject", "Author": "Jess Pomfret (@jpomfret)", "Syntax": "Export-DbaSysDbUserObject [-SqlInstance] \u003cDbaInstanceParameter\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-IncludeDependencies] [[-BatchSeparator] \u003cString\u003e] [[-Path] \u003cString\u003e] [[-FilePath] \u003cString\u003e] [-NoPrefix] [[-ScriptingOptionsObject] \u003cScriptingOptions\u003e] [-NoClobber] [-PassThru] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.String (when -PassThru is specified)\nReturns the generated T-SQL CREATE scripts as strings. One string per user-defined object discovered in the system databases.\r\nEach script includes a comment prefix (unless -NoPrefix is used) with generation timestamp, username, and dbatools version.\r\nScript sections are separated by the configured batch terminator (typically \"GO\").\nSystem.IO.FileInfo (when -Path or -FilePath is specified)\nReturns one file object per system database that contains user-defined objects, representing the generated SQL script file(s) written to disk.\nProperties:\r\n- Name: The filename of the exported script (e.g., \"server1-Export-DbaSysDbUserObject-master-20231215_143022.sql\")\r\n- FullName: The complete path to the exported script file\r\n- Directory: The directory object containing the file\r\n- CreationTime: When the file was created\r\n- LastWriteTime: When the file was last modified\r\n- Length: Size of the file in bytes\r\n- Extension: Always \".sql\"", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eExport-DbaSysDbUserObject -SqlInstance server1\nExports any user objects that are in the system database to the default location.", "Description": "Scans the master, model, and msdb system databases to identify tables, views, stored procedures, functions, triggers, and other objects that were created by users rather than SQL Server itself. This function helps DBAs document custom objects that may have been inadvertently created in system databases, which is critical for server migrations, compliance audits, and maintaining clean system database environments. The exported SQL scripts can be used to recreate these objects on other instances or to review what custom code exists in your system databases.", "Links": "https://dbatools.io/Export-DbaSysDbUserObject", "Synopsis": "Discovers and exports user-created objects from SQL Server system databases (master, model, msdb) to SQL script files.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.\r\nThis can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials.\r\nWindows and SQL Authentication supported. Accepts credential objects (Get-Credential)", "", false, "false", "", "" ], [ "IncludeDependencies", "Includes dependent objects in the scripted output when exporting user objects.\r\nUse this when your custom objects have dependencies that need to be recreated together on the target instance.", "", false, "false", "False", "" ], [ "BatchSeparator", "Sets the batch separator used between SQL statements in the exported script files. Defaults to \"GO\".\r\nChange this when you need compatibility with specific SQL tools that use different batch separators.", "", false, "false", "GO", "" ], [ "Path", "Specifies the directory where the exported SQL script file will be created. Uses the dbatools default export path if not specified.\r\nProvide this when you need the script saved to a specific location for documentation or deployment purposes.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027Path.DbatoolsExport\u0027)", "" ], [ "FilePath", "Specifies the complete file path including filename for the exported SQL script.\r\nUse this instead of Path when you need precise control over the output file name and location.", "", false, "false", "", "" ], [ "NoPrefix", "Excludes header information from the exported scripts, removing creator details and timestamp comments.\r\nUse this when you need clean scripts without metadata for version control or when the header information is not needed.", "", false, "false", "False", "" ], [ "ScriptingOptionsObject", "Provides a custom ScriptingOptions object to control how objects are scripted, including permissions, indexes, and constraints.\r\nUse this when you need specific scripting behavior beyond the default options, such as excluding certain object properties.", "", false, "false", "", "" ], [ "NoClobber", "Prevents overwriting existing files at the target location and throws an error if the file already exists.\r\nUse this as a safety measure when you want to avoid accidentally replacing existing script files.", "", false, "false", "False", "" ], [ "PassThru", "Outputs the generated SQL scripts directly to the PowerShell console instead of saving to a file.\r\nUse this when you want to review the scripts immediately or pipe them to other cmdlets for further processing.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": "Module", "CommandName": "Export-DbatoolsConfig", "Name": "Export-DbatoolsConfig", "Author": "Friedrich Weinmann (@FredWeinmann)", "Syntax": "Export-DbatoolsConfig -FullName \u003cString\u003e [-OutPath] \u003cString\u003e [-SkipUnchanged] [-EnableException] [\u003cCommonParameters\u003e]\nExport-DbatoolsConfig -Module \u003cString\u003e [[-Name] \u003cString\u003e] [-OutPath] \u003cString\u003e [-SkipUnchanged] [-EnableException] [\u003cCommonParameters\u003e]\nExport-DbatoolsConfig -Config \u003cConfig[]\u003e [-OutPath] \u003cString\u003e [-SkipUnchanged] [-EnableException] [\u003cCommonParameters\u003e]\nExport-DbatoolsConfig -ModuleName \u003cString\u003e [-ModuleVersion \u003cInt32\u003e] [-Scope {UserDefault | UserMandatory | SystemDefault | SystemMandatory | FileUserLocal | FileUserShared | FileSystem}] [-SkipUnchanged] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "None\nThis function does not output any objects to the pipeline. It writes configuration data to JSON files specified by the OutPath parameter or to predefined system locations when using the ModuleName \r\nparameter. File write operations are performed silently without pipeline output.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbatoolsConfig | Export-DbatoolsConfig -OutPath \u0027~/export.json\u0027\nExports all current settings to json.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eExport-DbatoolsConfig -Module message -OutPath \u0027~/export.json\u0027 -SkipUnchanged\nExports all settings of the module \u0027message\u0027 that are no longer the original default values to json.", "Description": "Exports dbatools configuration settings to a JSON file, allowing you to backup your current settings or migrate them to other machines. This function captures customized settings like connection timeouts, default database paths, and other module preferences that have been changed from their default values. You can export all settings or filter by specific modules, and optionally exclude settings that haven\u0027t been modified from defaults.", "Links": "https://dbatools.io/Export-DbatoolsConfig", "Synopsis": "Exports dbatools module configuration settings to a JSON file for backup or migration.", "Availability": "Windows, Linux, macOS", "Params": [ [ "FullName", "Specifies the complete configuration setting name to export, including the module prefix (e.g., \u0027dbatools.path.dbatoolsdata\u0027).\r\nUse this when you need to export a specific configuration setting and know its exact full name.", "", true, "false", "", "" ], [ "Module", "Filters configuration settings to export only those belonging to a specific dbatools module (e.g., \u0027sql\u0027, \u0027path\u0027, \u0027message\u0027).\r\nUse this when you want to export all settings related to a particular functional area of dbatools rather than individual settings.", "", true, "false", "", "" ], [ "Name", "Specifies a pattern to match configuration setting names within the selected module, supporting wildcards.\r\nUse this with the Module parameter to narrow down which settings to export when you don\u0027t need all settings from a module.", "", false, "false", "*", "" ], [ "Config", "Accepts configuration objects directly from Get-DbatoolsConfig for export to JSON.\r\nUse this when you want to filter or manipulate configuration objects before export, typically in pipeline operations.", "", true, "true (ByValue)", "", "" ], [ "ModuleName", "Exports module-specific configuration settings to predefined system locations rather than a custom path.\r\nOnly exports settings marked as \u0027ModuleExport\u0027 that have been modified from defaults, useful for creating standardized module configuration packages.", "", true, "false", "", "" ], [ "ModuleVersion", "Specifies the version number to include in the exported configuration filename when using ModuleName parameter.\r\nDefaults to 1 and helps track different versions of module configuration exports for change management.", "", false, "false", "1", "" ], [ "Scope", "Determines where to save module configuration files when using ModuleName parameter - user profile, shared location, or system-wide.\r\nOnly file-based scopes are supported (registry scopes are blocked). Defaults to FileUserShared for cross-user accessibility.", "", false, "false", "FileUserShared", "" ], [ "OutPath", "Specifies the complete file path where the JSON configuration export will be saved, including the filename.\r\nThe parent directory must exist or the export will fail, and any existing file at this location will be overwritten.", "", true, "false", "", "" ], [ "SkipUnchanged", "Excludes configuration settings that still have their original default values from the export.\r\nUse this to create smaller backup files containing only your customized settings, making configuration migration more focused.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "User", "Export" ], "CommandName": "Export-DbaUser", "Name": "Export-DbaUser", "Author": "Claudio Silva (@ClaudioESSilva)", "Syntax": "Export-DbaUser [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-ExcludeDatabase] \u003cString[]\u003e] [[-User] \u003cString[]\u003e] [[-DestinationVersion] \u003cString\u003e] [[-Path] \u003cString\u003e] [[-FilePath] \u003cString\u003e] [[-Encoding] \u003cString\u003e] [-NoClobber] [-Append] [-Passthru] [-Template] [-EnableException] [[-ScriptingOptionsObject] \u003cScriptingOptions\u003e] [-ExcludeGoBatchSeparator] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.String (when -Passthru is specified)\nReturns the generated T-SQL script containing CREATE USER statements, role memberships, database permissions, and object-level permissions as raw text.\nSystem.IO.FileInfo (default)\nReturns file system object(s) for the created T-SQL script file(s). When generating one file per user (using -Path without -FilePath), returns one FileInfo object per user file. When consolidating to \r\na single file (using -FilePath), returns one FileInfo object for that file.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eExport-DbaUser -SqlInstance sql2005 -FilePath C:\\temp\\sql2005-users.sql\nExports SQL for the users in server \"sql2005\" and writes them to the file \"C:\\temp\\sql2005-users.sql\"\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eExport-DbaUser -SqlInstance sqlserver2014a $scred -FilePath C:\\temp\\users.sql -Append\nAuthenticates to sqlserver2014a using SQL Authentication. Exports all users to C:\\temp\\users.sql, and appends to the file if it exists. If not, the file will be created.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eExport-DbaUser -SqlInstance sqlserver2014a -User User1, User2 -FilePath C:\\temp\\users.sql\nExports ONLY users User1 and User2 from sqlserver2014a to the file C:\\temp\\users.sql\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eExport-DbaUser -SqlInstance sqlserver2014a -User User1, User2 -Path C:\\temp\nExports ONLY users User1 and User2 from sqlserver2014a to the folder C:\\temp. One file per user will be generated\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eExport-DbaUser -SqlInstance sqlserver2008 -User User1 -FilePath C:\\temp\\users.sql -DestinationVersion SQLServer2016\nExports user User1 from sqlserver2008 to the file C:\\temp\\users.sql with syntax to run on SQL Server 2016\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eExport-DbaUser -SqlInstance sqlserver2008 -Database db1,db2 -FilePath C:\\temp\\users.sql\nExports ONLY users from db1 and db2 database on sqlserver2008 server, to the C:\\temp\\users.sql file.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003e$options = New-DbaScriptingOption\nPS C:\\\u003e $options.ScriptDrops = $false\r\nPS C:\\\u003e $options.WithDependencies = $true\r\nPS C:\\\u003e Export-DbaUser -SqlInstance sqlserver2008 -Database db1,db2 -FilePath C:\\temp\\users.sql -ScriptingOptionsObject $options\nExports ONLY users from db1 and db2 database on sqlserver2008 server, to the C:\\temp\\users.sql file.\r\nIt will not script drops but will script dependencies.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eExport-DbaUser -SqlInstance sqlserver2008 -Database db1,db2 -FilePath C:\\temp\\users.sql -ExcludeGoBatchSeparator\nExports ONLY users from db1 and db2 database on sqlserver2008 server, to the C:\\temp\\users.sql file without the \u0027GO\u0027 batch separator.\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003eExport-DbaUser -SqlInstance sqlserver2008 -Database db1 -User user1 -Template -PassThru\nExports user1 from database db1, replacing loginname and username with {templateLogin} and {templateUser} correspondingly.", "Description": "Creates comprehensive T-SQL scripts that fully recreate database users along with their security assignments and permissions. The generated scripts include user creation statements, role memberships, database-level permissions (like CONNECT, SELECT, INSERT), and granular object-level permissions for tables, views, stored procedures, functions, and other database objects.\n\nThis function is essential for migrating users between environments, documenting security configurations for compliance audits, creating deployment scripts for application users, or preparing disaster recovery procedures. Each exported script is self-contained and includes all necessary role creation statements to avoid dependency issues during execution.\n\nThe function examines the complete security context for each user, including custom database roles, explicit permissions granted at the database level, and specific object permissions across all supported SQL Server object types (tables, views, procedures, functions, assemblies, certificates, schemas, and Service Broker objects).", "Links": "https://dbatools.io/Export-DbaUser", "Synopsis": "Generates T-SQL scripts to recreate database users with their complete security context including roles and permissions", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. SQL Server 2000 and above supported.", "", false, "true (ByValue)", "", "" ], [ "InputObject", "Accepts database objects piped from Get-DbaDatabase for processing specific database collections.\r\nUse this in pipeline operations when you have pre-filtered database objects to process.", "", false, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to export users from. Accepts wildcards for pattern matching.\r\nUse this when you need to export users from specific databases instead of all databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies databases to exclude from user export operations. Accepts wildcards for pattern matching.\r\nUseful when exporting from most databases but need to skip system databases or specific application databases.", "", false, "false", "", "" ], [ "User", "Exports only the specified database users by name. Accepts multiple user names.\r\nUse this when you need to export specific application users or service accounts rather than all database users.", "", false, "false", "", "" ], [ "DestinationVersion", "Specifies the target SQL Server version for the generated T-SQL script syntax compatibility.\r\nUse this when migrating users to a different SQL Server version than the source database compatibility level.", "", false, "false", "", "SQLServer2000,SQLServer2005,SQLServer2008/2008R2,SQLServer2012,SQLServer2014,SQLServer2016,SQLServer2017,SQLServer2019,SQLServer2022" ], [ "Path", "Sets the directory path where user script files will be created. Creates individual files per user when FilePath is not specified.\r\nUse this when organizing exported scripts by directory structure for different environments or applications.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027Path.DbatoolsExport\u0027)", "" ], [ "FilePath", "Sets the complete file path for a single consolidated script containing all exported users.\r\nUse this when you need all user definitions in one file for batch deployment or version control.", "OutFile,FileName", false, "false", "", "" ], [ "Encoding", "Sets the character encoding for the output T-SQL script file. Defaults to UTF8.\r\nChange this when you need to match specific encoding requirements for your deployment tools or source control systems.", "", false, "false", "UTF8", "ASCII,BigEndianUnicode,Byte,String,Unicode,UTF7,UTF8,Unknown" ], [ "NoClobber", "Prevents overwriting existing files during export operations.\r\nUse this safety feature when running exports to avoid accidentally replacing existing user scripts.", "NoOverwrite", false, "false", "False", "" ], [ "Append", "Adds the exported user scripts to the end of an existing file instead of creating a new file.\r\nUse this when consolidating user exports from multiple instances or databases into a single deployment script.", "", false, "false", "False", "" ], [ "Passthru", "Returns the T-SQL script to the console instead of writing to a file.\r\nUse this for copying scripts to clipboard, reviewing output before saving, or integrating with other PowerShell operations.", "", false, "false", "False", "" ], [ "Template", "Replaces actual usernames and login names with placeholders {templateUser} and {templateLogin} in the generated script.\r\nUse this when creating reusable deployment scripts that can be parameterized for different environments or applications.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "ScriptingOptionsObject", "Provides a custom ScriptingOptions object to control detailed T-SQL generation behavior and formatting.\r\nUse this for advanced scenarios requiring specific scripting options beyond the standard Export-DbaUser parameters.", "", false, "false", "", "" ], [ "ExcludeGoBatchSeparator", "Removes the \u0027GO\u0027 batch separator statements from the generated T-SQL script.\r\nUse this when the target deployment tool or application doesn\u0027t support batch separators or requires continuous T-SQL.", "", false, "false", "False", "" ] ] }, { "Tags": [ "ExtendedEvent", "XE", "XEvent" ], "CommandName": "Export-DbaXESession", "Name": "Export-DbaXESession", "Author": "Patrick Flynn (@sqllensman)", "Syntax": "Export-DbaXESession [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-InputObject] \u003cSession[]\u003e] [[-Session] \u003cString[]\u003e] [[-Path] \u003cString\u003e] [[-FilePath] \u003cString\u003e] [[-Encoding] \u003cString\u003e] [-Passthru] [[-BatchSeparator] \u003cString\u003e] [-NoPrefix] [-NoClobber] [-Append] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.String (when -Passthru is specified or no output path is specified)\nReturns the generated T-SQL CREATE EVENT SESSION script as a string. The script contains the complete definition of the Extended Events session including all events, actions, targets, and \r\nconfiguration settings.\nSystem.IO.FileInfo (when -Path or -FilePath is specified)\nReturns file information objects for each generated script file. One file is created per SQL Server instance processed. When exporting multiple sessions from the same instance using -Append, only the \r\nfirst session returns file information for that instance.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eExport-DbaXESession -SqlInstance sourceserver -Passthru\nExports a script to create all Extended Events Sessions on sourceserver to the console\r\nWill include prefix information containing creator and datetime. and uses the default value for BatchSeparator value from configuration Formatting.BatchSeparator\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eExport-DbaXESession -SqlInstance sourceserver\nExports a script to create all Extended Events Sessions on sourceserver. As no Path was defined - automatically determines filename based on the Path.DbatoolsExport configuration setting, current \r\ntime and server name like Servername-YYYYMMDDhhmmss-sp_configure.sql\r\nWill include prefix information containing creator and datetime. and uses the default value for BatchSeparator value from configuration Formatting.BatchSeparator\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eExport-DbaXESession -SqlInstance sourceserver -FilePath C:\\temp\nExports a script to create all Extended Events Sessions on sourceserver to the directory C:\\temp using the default name format of Servername-YYYYMMDDhhmmss-sp_configure.sql\r\nWill include prefix information containing creator and datetime. and uses the default value for BatchSeparator value from configuration Formatting.BatchSeparator\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Export-DbaXESession -SqlInstance sourceserver -SqlCredential $cred -FilePath C:\\temp\\EEvents.sql -BatchSeparator \"\" -NoPrefix -NoClobber\nExports a script to create all Extended Events Sessions on sourceserver to the file C:\\temp\\EEvents.sql.\r\nWill exclude prefix information containing creator and datetime and does not include a BatchSeparator\r\nWill not overwrite file if it already exists\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e\u0027Server1\u0027, \u0027Server2\u0027 | Export-DbaXESession -FilePath \u0027C:\\Temp\\EE.sql\u0027 -Append\nExports a script to create all Extended Events Sessions for Server1 and Server2 using pipeline.\r\nWrites to a single file using the Append switch\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaXESession -SqlInstance Server1, Server2 -Session system_health | Export-DbaXESession -Path \u0027C:\\Temp\u0027\nExports a script to create the System_Health Extended Events Sessions for Server1 and Server2 using pipeline.\r\nWrite to the directory C:\\temp using the default name format of Servername-YYYYMMDDhhmmss-sp_configure.sql\r\nWill include prefix information containing creator and datetime. and uses the default value for BatchSeparator value from configuration Formatting.BatchSeparator", "Description": "Generates T-SQL scripts that can recreate your Extended Events sessions, making it easy to migrate monitoring configurations between environments or create backups of your XE session definitions. This is particularly useful when moving sessions from development to production, creating deployment scripts, or documenting your current monitoring setup for compliance purposes. The function connects to your SQL Server instances, retrieves the session definitions, and outputs the complete CREATE EVENT SESSION statements with all events, actions, targets, and configuration settings intact.", "Links": "https://dbatools.io/Export-DbaXESession", "Synopsis": "Generates T-SQL creation scripts for Extended Events sessions to files or console", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input.\r\nServer version must be SQL Server version 2008 or higher.", "", false, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "InputObject", "Accepts Extended Event session objects from Get-DbaXESession for pipeline processing. Use this when you already have session objects loaded and want to export specific sessions without re-querying \r\nthe server.", "", false, "true (ByValue)", "", "" ], [ "Session", "Specifies specific Extended Event session names to export instead of all sessions. Accepts multiple session names and supports wildcards for pattern matching. Use this when you only need to export \r\nspecific monitoring configurations rather than all sessions on the server.", "", false, "false", "", "" ], [ "Path", "Specifies the output directory for the generated T-SQL scripts. Creates automatically named files using the format ServerName-YYYYMMDDHHMMSS-xe.sql. Use this when you want files organized in a \r\nspecific directory with consistent naming for multiple servers or scheduled exports.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027Path.DbatoolsExport\u0027)", "" ], [ "FilePath", "Sets the exact file path and name for the output script. Use this when you need precise control over the output file location and naming. When exporting from multiple servers to a single file, you \r\nmust also use -Append to prevent data loss from overwriting.", "OutFile,FileName", false, "false", "", "" ], [ "Encoding", "Controls the character encoding for the output file. Defaults to UTF8 which handles international characters properly. Use ASCII only if you need compatibility with older systems that don\u0027t support \r\nUnicode. Use Unicode (UTF-16) if required by specific deployment tools or when working with non-Latin scripts.", "", false, "false", "UTF8", "ASCII,BigEndianUnicode,Byte,String,Unicode,UTF7,UTF8,Unknown" ], [ "Passthru", "Displays the generated T-SQL script in the console instead of writing to a file. Use this for immediate review of the session definitions, copying to clipboard, or redirecting to other tools in your \r\nPowerShell pipeline.", "", false, "false", "False", "" ], [ "BatchSeparator", "Sets the T-SQL batch separator in the output script, typically \"GO\". Use an empty string to remove batch separators when the target environment doesn\u0027t support them, or customize for specific \r\ndeployment tools that require different separators.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027Formatting.BatchSeparator\u0027)", "" ], [ "NoPrefix", "Removes the header comments that identify when and who created the script. Use this when you need clean T-SQL scripts without metadata comments, or when scripts will be version controlled and you \r\nwant to avoid unnecessary differences between exports.", "", false, "false", "False", "" ], [ "NoClobber", "Prevents overwriting an existing file when using -FilePath. The function will stop with an error if the target file already exists. Use this as a safety check when you want to ensure you don\u0027t \r\naccidentally replace important script files.", "", false, "false", "False", "" ], [ "Append", "Adds new content to an existing file instead of overwriting when using -FilePath. Required when exporting sessions from multiple servers to a single consolidated script file. Use this to build \r\ncomprehensive deployment scripts that include sessions from multiple SQL Server instances.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "ExtendedEvent", "XE", "XEvent" ], "CommandName": "Export-DbaXESessionTemplate", "Name": "Export-DbaXESessionTemplate", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Export-DbaXESessionTemplate [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Session] \u003cObject[]\u003e] [[-Path] \u003cString\u003e] [[-FilePath] \u003cString\u003e] [[-InputObject] \u003cSession[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.IO.FileInfo\nReturns one FileInfo object per Extended Events session exported. Each object represents the XML template file that was created.\nProperties:\r\n- Name: The filename of the exported XE session template (e.g., \"system_health.xml\")\r\n- FullName: The complete path to the exported template file\r\n- DirectoryName: The directory path where the template file was saved\r\n- Extension: The file extension (\".xml\")\r\n- Length: The size of the template file in bytes\r\n- CreationTime: When the template file was created\r\n- LastWriteTime: When the template file was last modified\r\n- LastAccessTime: When the template file was last accessed\r\n- Mode: File attributes and permissions (e.g., \"-a----\")", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eExport-DbaXESessionTemplate -SqlInstance sql2017 -Path C:\\temp\\xe\nExports an XESession XML Template for all Extended Event Sessions on sql2017 to the C:\\temp\\xe folder.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaXESession -SqlInstance sql2017 -Session system_health | Export-DbaXESessionTemplate -Path C:\\temp\\xe\nGets the system_health Extended Events Session from sql2017 and then exports as an XESession XML Template to C:\\temp\\xe", "Description": "Converts existing Extended Events sessions into XML template files that can be imported and reused in SQL Server Management Studio.\nThis lets you standardize XE session configurations across multiple environments without manually recreating session definitions.\nTemplates are saved to the SSMS XEvent templates folder by default, making them immediately available in the SSMS template browser.\nAccepts sessions directly from SQL Server instances or from Get-DbaXESession pipeline output.", "Links": "https://dbatools.io/Export-DbaXESessionTemplate", "Synopsis": "Exports Extended Events sessions as reusable XML templates for SSMS", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher.", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Session", "Specifies which Extended Events sessions to export by name. Accepts wildcards for pattern matching.\r\nUse this to export specific sessions instead of all sessions on the instance. Common sessions include system_health, AlwaysOn_health, or custom monitoring sessions.", "", false, "false", "", "" ], [ "Path", "Sets the directory where XML template files will be saved. Defaults to the SSMS XEvent Templates folder in your Documents.\r\nTemplates saved to the default location appear automatically in SSMS under Templates \u003e XEventTemplates for easy reuse.", "", false, "false", "\"$home\\Documents\\SQL Server Management Studio\\Templates\\XEventTemplates\"", "" ], [ "FilePath", "Sets the complete file path including filename for the exported template. Use when you need a specific filename or location.\r\nWhen specified, only one session can be exported at a time. If not provided, files are named after the session and saved to the Path directory.", "OutFile,FileName", false, "false", "", "" ], [ "InputObject", "Accepts Extended Events session objects from Get-DbaXESession pipeline input.\r\nUse this when you need to filter sessions first or when working with sessions from multiple instances in a single export operation.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Agent", "Job", "Lookup" ], "CommandName": "Find-DbaAgentJob", "Name": "Find-DbaAgentJob", "Author": "Stephen Bennett, sqlnotesfromtheunderground.wordpress.com", "Syntax": "Find-DbaAgentJob [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-JobName] \u003cString[]\u003e] [[-ExcludeJobName] \u003cString[]\u003e] [[-StepName] \u003cString[]\u003e] [[-Pattern] \u003cString[]\u003e] [[-LastUsed] \u003cInt32\u003e] [-IsDisabled] [-IsFailed] [-IsNotScheduled] [-IsNoEmailNotification] [[-Category] \u003cString[]\u003e] [[-Owner] \u003cString\u003e] [[-Since] \u003cDateTime\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Job\nReturns one Job object for each job that matches the specified search criteria. Multiple jobs can be returned per instance depending on filter parameters.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Name: Job name\r\n- Category: Job category classification\r\n- OwnerLoginName: Login name of the job owner\r\n- CurrentRunStatus: Current execution status (Idle, Running, etc.)\r\n- CurrentRunRetryAttempt: Number of retry attempts for current execution\r\n- Enabled: Boolean indicating if the job is enabled (aliased from IsEnabled)\r\n- LastRunDate: DateTime of the most recent job execution\r\n- LastRunOutcome: Outcome of the last execution (Succeeded, Failed, Cancelled, etc.)\r\n- DateCreated: DateTime when the job was created\r\n- HasSchedule: Boolean indicating if the job has a schedule assigned\r\n- OperatorToEmail: Email operator name for notifications\r\n- CreateDate: DateTime when the job was created (aliased from DateCreated)\nAdditional properties available (from SMO Job object):\r\n- JobId: Unique identifier for the job (GUID)\r\n- IsEnabled: Boolean indicating if the job is enabled and can be scheduled\r\n- JobType: Type of job (Local or MultiServer)\r\n- Category: Job category name\r\n- CategoryID: Numeric category identifier\r\n- Owner: Job owner name\r\n- OwnerLoginName: Login name of the job owner\r\n- Description: Job description text\r\n- StartStepID: ID of the first step to execute\r\n- EventLogLevel: Event log level for job events (OnSuccess, OnFailure, Always, Never)\r\n- EmailLevel: Email notification level (OnSuccess, OnFailure, OnCompletion, Never)\r\n- NetsendLevel: NetSend notification level (OnSuccess, OnFailure, OnCompletion, Never)\r\n- PageLevel: Pager notification level (OnSuccess, OnFailure, OnCompletion, Never)\r\n- OperatorToNetSend: Operator name for NetSend notifications\r\n- OperatorToPage: Operator name for pager notifications\r\n- LastRunDuration: Duration of last run in seconds\r\n- NextRunDate: DateTime when the job is scheduled to run next\r\n- DateModified: DateTime when the job was last modified\r\n- HasSchedule: Boolean indicating if the job has a schedule\r\n- IsRunnable: Boolean indicating if the job can be executed\r\n- Parent: Reference to parent JobServer SMO object\nAll properties from the base SMO Job object are accessible even though only default properties are displayed without using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eFind-DbaAgentJob -SqlInstance Dev01 -JobName *backup*\nReturns all agent job(s) that have backup in the name\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eFind-DbaAgentJob -SqlInstance Dev01, Dev02 -JobName Mybackup\nReturns all agent job(s) that are named exactly Mybackup\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eFind-DbaAgentJob -SqlInstance Dev01 -Pattern \"^(Backup|Restore)-\\d{4}$\"\nReturns jobs whose names match the supplied regular expression.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eFind-DbaAgentJob -SqlInstance Dev01 -LastUsed 10\nReturns all agent job(s) that have not ran in 10 days\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eFind-DbaAgentJob -SqlInstance Dev01 -IsDisabled -IsNoEmailNotification -IsNotScheduled\nReturns all agent job(s) that are either disabled, have no email notification or don\u0027t have a schedule. returned with detail\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e$servers | Find-DbaAgentJob -IsFailed | Start-DbaAgentJob\nFinds all failed job then starts them. Consider using a -WhatIf at the end of Start-DbaAgentJob to see what it\u0027ll do first\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eFind-DbaAgentJob -SqlInstance Dev01 -LastUsed 10 -ExcludeJobName \"Yearly - RollUp Workload\", \"SMS - Notification\"\nReturns all agent jobs that have not ran in the last 10 days ignoring jobs \"Yearly - RollUp Workload\" and \"SMS - Notification\"\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eFind-DbaAgentJob -SqlInstance Dev01 -Category \"REPL-Distribution\", \"REPL-Snapshot\" | Format-Table -AutoSize -Wrap\nReturns all job/s on Dev01 that are in either category \"REPL-Distribution\" or \"REPL-Snapshot\"\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003eFind-DbaAgentJob -SqlInstance Dev01, Dev02 -IsFailed -Since \u00272016-07-01 10:47:00\u0027\nReturns all agent job(s) on Dev01 and Dev02 that have failed since July of 2016 (and still have history in msdb)\n-------------------------- EXAMPLE 10 --------------------------\nPS C:\\\u003eGet-DbaRegServer -SqlInstance CMSServer -Group Production | Find-DbaAgentJob -Disabled -IsNotScheduled | Format-Table -AutoSize -Wrap\nQueries CMS server to return all SQL instances in the Production folder and then list out all agent jobs that have either been disabled or have no schedule.\n-------------------------- EXAMPLE 11 --------------------------\nPS C:\\\u003e$Instances = \u0027SQL2017N5\u0027,\u0027SQL2019N5\u0027,\u0027SQL2019N20\u0027,\u0027SQL2019N21\u0027,\u0027SQL2019N22\u0027\nFind-DbaAgentJob -SqlInstance $Instances -JobName *backup* -IsNotScheduled\nReturns all agent job(s) wiht backup in the name, that don\u0027t have a schedule on \u0027SQL2017N5\u0027,\u0027SQL2019N5\u0027,\u0027SQL2019N20\u0027,\u0027SQL2019N21\u0027,\u0027SQL2019N22\u0027", "Description": "Searches SQL Agent jobs across one or more SQL Server instances using various filter criteria including job name, step name, execution status, schedule status, and notification settings. Helps DBAs identify problematic jobs that have failed, haven\u0027t run recently, are disabled, lack schedules, or missing email notifications. Useful for maintenance audits, troubleshooting job issues, and identifying cleanup candidates in environments with many automated processes.", "Links": "https://dbatools.io/Find-DbaAgentJob", "Synopsis": "Searches and filters SQL Agent jobs across SQL Server instances using multiple criteria.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or higher.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "JobName", "Specifies agent job names to search for using exact matches or wildcard patterns.\r\nSupports wildcards like *backup*, MyJob*, or *ETL* to find jobs with specific naming conventions.\r\nUseful when you need to focus on particular job types or troubleshoot specific processes.", "Name", false, "false", "", "" ], [ "ExcludeJobName", "Excludes specific job names from the search results using exact name matches.\r\nUse this to filter out known good jobs when searching for problematic ones, like excluding maintenance jobs when looking for failed application jobs.", "", false, "false", "", "" ], [ "StepName", "Searches for jobs containing steps with specific names or patterns.\r\nSupports wildcards to find jobs with steps like *backup*, *index*, or *cleanup*.\r\nHelpful when troubleshooting issues in multi-step jobs or finding jobs that perform specific operations.", "", false, "false", "", "" ], [ "Pattern", "Filters job names using one or more regular expressions. Multiple patterns use OR semantics.\r\nCombine this with JobName or StepName to further narrow those results.", "", false, "false", "", "" ], [ "LastUsed", "Finds jobs that haven\u0027t executed successfully in the specified number of days.\r\nUse this to identify stale or potentially broken jobs that may need attention.\r\nCommon values are 7, 30, or 90 days depending on job frequency and business requirements.", "", false, "false", "0", "" ], [ "IsDisabled", "Finds all jobs with disabled status (not scheduled to run automatically).\r\nUse this during maintenance windows to identify jobs that were disabled for troubleshooting or may have been forgotten after maintenance.", "Disabled", false, "false", "False", "" ], [ "IsFailed", "Finds jobs where the last execution resulted in a failure status.\r\nEssential for daily health checks and identifying jobs that need immediate attention.\r\nCombine with Since parameter to focus on recent failures or look at historical patterns.", "Failed", false, "false", "False", "" ], [ "IsNotScheduled", "Finds jobs that exist but have no schedule defined (manual execution only).\r\nUseful for identifying orphaned jobs, temporary jobs that should be cleaned up, or jobs awaiting proper scheduling configuration.", "NoSchedule", false, "false", "False", "" ], [ "IsNoEmailNotification", "Finds jobs that lack email notification setup for failures or completion.\r\nImportant for ensuring critical jobs will alert DBAs when they fail.\r\nUse this during compliance audits or when establishing monitoring standards.", "NoEmailNotification", false, "false", "False", "" ], [ "Category", "Filters jobs by their assigned categories such as \u0027Database Maintenance\u0027, \u0027REPL-Distribution\u0027, or custom categories.\r\nUseful for focusing on specific types of jobs like replication jobs, maintenance tasks, or application-specific processes.\r\nCategories help organize and manage jobs in environments with many different job types.", "", false, "false", "", "" ], [ "Owner", "Filters jobs by their owner login name, or excludes jobs by prefixing with a dash (-).\r\nUse \u0027DOMAIN\\\\User\u0027 to find jobs owned by specific accounts, or \u0027-sa\u0027 to exclude sa-owned jobs.\r\nHelpful for security audits, identifying jobs that may need ownership changes, or finding jobs created by specific users.", "", false, "false", "", "" ], [ "Since", "Limits results to jobs that last ran on or after the specified date and time.\r\nUse with IsFailed to find jobs that failed since a specific incident, or combine with other filters to focus on recent activity.\r\nAccepts standard datetime formats like \u00272023-01-01\u0027 or \u00272023-01-01 14:30:00\u0027.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Backup", "Lookup" ], "CommandName": "Find-DbaBackup", "Name": "Find-DbaBackup", "Author": "Chris Sommer (@cjsommer), www.cjsommer.com", "Syntax": "Find-DbaBackup [-Path] \u003cString\u003e [-BackupFileExtension] \u003cString\u003e [-RetentionPeriod] \u003cString\u003e [-CheckArchiveBit] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.IO.FileInfo\nReturns one file object for each backup file found in the specified directory and subdirectories that meets the age and archive bit criteria.\nProperties:\r\n- FullName: The complete path to the backup file\r\n- Name: The file name including extension\r\n- Extension: The file extension (e.g., .bak, .trn, .dif, .log)\r\n- DirectoryName: The directory containing the file\r\n- Length: The file size in bytes\r\n- LastWriteTime: The timestamp when the file was last modified, used to determine if it meets the retention period\r\n- Attributes: File attributes including the Archive bit status (checked when -CheckArchiveBit is specified)\r\n- CreationTime: The timestamp when the file was created\r\n- LastAccessTime: The timestamp when the file was last accessed\nThese file objects are suitable for piping to Remove-Item or other file management cmdlets for automated cleanup workflows.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eFind-DbaBackup -Path \u0027C:\\MSSQL\\SQL Backup\\\u0027 -BackupFileExtension trn -RetentionPeriod 48h\nSearches for all trn files in C:\\MSSQL\\SQL Backup\\ and all subdirectories that are more than 48 hours old will be included.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eFind-DbaBackup -Path \u0027C:\\MSSQL\\Backup\\\u0027 -BackupFileExtension bak -RetentionPeriod 7d -CheckArchiveBit\nSearches for all bak files in C:\\MSSQL\\Backup\\ and all subdirectories that are more than 7 days old will be included, but only if the files have been backed up to another location as verified by \r\nchecking the Archive bit.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eFind-DbaBackup -Path \u0027\\\\SQL2014\\Backup\\\u0027 -BackupFileExtension bak -RetentionPeriod 24h | Remove-Item -Verbose\nSearches for all bak files in \\\\SQL2014\\Backup\\ and all subdirectories that are more than 24 hours old and deletes only those files with verbose message.", "Description": "Recursively scans specified directories to locate SQL Server backup files (.bak, .trn, .dif, etc.) older than your defined retention period. Returns file objects that can be piped to removal commands or processed for cleanup workflows.\n\nThis function replaces manual directory searches when managing backup retention policies. You can filter results to only include files that have been archived (using the Archive bit check) to ensure backups are safely stored elsewhere before cleanup.\n\nCommonly used in automated maintenance scripts to identify backup files ready for deletion based on your organization\u0027s retention requirements.", "Links": "https://dbatools.io/Find-DbaBackup", "Synopsis": "Searches filesystem directories for SQL Server backup files based on age and extension criteria.", "Availability": "Windows, Linux, macOS", "Params": [ [ "Path", "Specifies the root directory path to recursively search for backup files. Searches all subdirectories within this path.\r\nUse this to target specific backup locations like dedicated backup drives or network shares where your SQL Server backups are stored.", "BackupFolder", true, "false", "", "" ], [ "BackupFileExtension", "Specifies the file extension to search for without the period (e.g., \u0027bak\u0027, \u0027trn\u0027, \u0027dif\u0027, \u0027log\u0027).\r\nUse \u0027bak\u0027 for full backups, \u0027trn\u0027 or \u0027log\u0027 for transaction log backups, or \u0027dif\u0027 for differential backups depending on which backup type you need to manage.", "", true, "false", "", "" ], [ "RetentionPeriod", "Specifies how old backup files must be before they\u0027re included in results, using format like \u00277d\u0027 or \u002748h\u0027.\r\nFiles older than this period will be returned, making this essential for backup cleanup operations based on your retention policy.\r\nValid units: h (hours), d (days), w (weeks), m (months). Examples: \u002748h\u0027, \u00277d\u0027, \u00274w\u0027, \u00271m\u0027.", "", true, "false", "", "" ], [ "CheckArchiveBit", "Only includes backup files that have been archived to another location (Archive bit is not set).\r\nUse this safety feature to ensure backups have been copied to tape, cloud storage, or other backup systems before cleanup to prevent accidental data loss.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Module", "Lookup" ], "CommandName": "Find-DbaCommand", "Name": "Find-DbaCommand", "Author": "Simone Bizzotto (@niphlod)", "Syntax": "Find-DbaCommand [[-Pattern] \u003cString\u003e] [[-Tag] \u003cString[]\u003e] [[-Author] \u003cString\u003e] [[-MinimumVersion] \u003cString\u003e] [[-MaximumVersion] \u003cString\u003e] [-Rebuild] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per dbatools command matching the specified filters.\nDefault display properties (via Select-DefaultView):\r\n- CommandName: The name of the dbatools command\r\n- Synopsis: A brief one-line description of what the command does\nAdditional properties available (use Select-Object * to see all):\r\n- Name: The full name of the command function\r\n- Availability: Platform availability (Windows, Linux, macOS or Windows only)\r\n- Alias: Comma-separated list of command aliases\r\n- Description: Detailed description of the command\u0027s functionality\r\n- Examples: Full examples section from the command\u0027s help text\r\n- Links: Related documentation links\r\n- Syntax: Complete syntax information for the command\r\n- Tags: Array of tags categorizing the command by feature area (Backup, AG, Job, Security, etc.)\r\n- Author: Name(s) of the command author(s)\r\n- MinimumVersion: Minimum dbatools version required to use this command\r\n- MaximumVersion: Maximum dbatools version supported by this command\r\n- Params: Array of parameter information (name, description, aliases, required status, pipeline support, default values, accepted values)\nAll properties from the full command help index are accessible. Use Select-Object * to display all available properties for further analysis.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eFind-DbaCommand \"snapshot\"\nFor lazy typers: finds all commands searching the entire help for \"snapshot\"\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eFind-DbaCommand -Pattern \"snapshot\"\nFor rigorous typers: finds all commands searching the entire help for \"snapshot\"\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eFind-DbaCommand -Tag Job\nFinds all commands tagged with \"Job\"\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eFind-DbaCommand -Tag Job,Owner\nFinds all commands tagged with BOTH \"Job\" and \"Owner\"\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eFind-DbaCommand -Author Chrissy\nFinds every command whose author contains our beloved \"Chrissy\"\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eFind-DbaCommand -Author Chrissy -Tag AG\nFinds every command whose author contains our beloved \"Chrissy\" and it tagged as \"AG\"\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eFind-DbaCommand -Pattern snapshot -Rebuild\nFinds all commands searching the entire help for \"snapshot\", rebuilding the index (good for developers)", "Description": "Finds dbatools commands searching through the inline help text, building a consolidated json index and querying it because Get-Help is too slow", "Links": "https://dbatools.io/Find-DbaCommand", "Synopsis": "Finds dbatools commands searching through the inline help text", "Availability": "Windows, Linux, macOS", "Params": [ [ "Pattern", "Searches all help text properties (synopsis, description, examples, parameters) for the specified text pattern using wildcard matching.\r\nUse this for broad searches when you know a concept or term but aren\u0027t sure which specific commands handle it.", "", false, "false", "", "" ], [ "Tag", "Filters results to show only commands that contain all specified tags. Tags categorize commands by SQL Server feature area like \"Backup\", \"AG\", \"Job\", or \"Security\".\r\nUse this when you need to find commands related to specific SQL Server functionality. Multiple tags require commands to have ALL specified tags.", "", false, "false", "", "" ], [ "Author", "Filters results to show commands created by authors whose name contains the specified text. Uses wildcard matching so partial names work.\r\nUseful when you want to find commands written by a specific contributor or when following up on recommendations from particular experts.", "", false, "false", "", "" ], [ "MinimumVersion", "Filters results to show only commands that require the specified minimum version of dbatools or higher.\r\nUse this to ensure compatibility when working with older dbatools installations or when checking what features require recent updates.", "", false, "false", "", "" ], [ "MaximumVersion", "Filters results to show only commands that work with the specified maximum version of dbatools or lower.\r\nHelpful when working with legacy environments where you need to avoid commands that require newer dbatools versions.", "", false, "false", "", "" ], [ "Rebuild", "Forces a complete rebuild of the dbatools command index from the current module state. This rescans all help text and updates the cached index file.\r\nUse this when developing new commands, after updating dbatools, or when search results seem outdated or incomplete.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "Displays what would happen if the command is run", "wi", false, "false", "", "" ], [ "Confirm", "Confirms overwrite of index", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Database", "Lookup" ], "CommandName": "Find-DbaDatabase", "Name": "Find-DbaDatabase", "Author": "Stephen Bennett, sqlnotesfromtheunderground.wordpress.com", "Syntax": "Find-DbaDatabase [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Property] \u003cString\u003e] [-Pattern] \u003cString\u003e [-Exact] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database matching the search criteria.\nProperties:\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Name: The database name\r\n- Id: The database ID\r\n- Size: The database size in megabytes (dbasize object for formatting)\r\n- Owner: The database owner login\r\n- CreateDate: DateTime when the database was created\r\n- ServiceBrokerGuid: The Service Broker GUID for the database (useful for identifying mismatched GUIDs after restore operations)\r\n- Tables: Count of user-defined tables in the database\r\n- StoredProcedures: Count of user-defined stored procedures in the database\r\n- Views: Count of user-defined views in the database\r\n- ExtendedProperties: Array of PSCustomObjects containing extended properties (each with Name and Value properties), or 0 if no extended properties exist", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eFind-DbaDatabase -SqlInstance \"DEV01\", \"DEV02\", \"UAT01\", \"UAT02\", \"PROD01\", \"PROD02\" -Pattern Report\nReturns all database from the SqlInstances that have a database with Report in the name\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eFind-DbaDatabase -SqlInstance \"DEV01\", \"DEV02\", \"UAT01\", \"UAT02\", \"PROD01\", \"PROD02\" -Pattern TestDB -Exact | Select-Object *\nReturns all database from the SqlInstances that have a database named TestDB with a detailed output.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eFind-DbaDatabase -SqlInstance \"DEV01\", \"DEV02\", \"UAT01\", \"UAT02\", \"PROD01\", \"PROD02\" -Property ServiceBrokerGuid -Pattern \u0027-faeb-495a-9898-f25a782835f5\u0027 | Select-Object *\nReturns all database from the SqlInstances that have the same Service Broker GUID with a detailed output", "Description": "Performs database discovery and inventory across multiple SQL Server instances by searching for databases that match specific criteria. You can search by database name (using regex patterns), database owner, or Service Broker GUID to locate databases across environments.\n\nThis is particularly useful for tracking databases across development, test, and production environments, finding databases by ownership for security audits, or identifying databases with matching Service Broker GUIDs. The function returns detailed information including database size, object counts (tables, views, stored procedures), and creation details.\n\nService Broker GUIDs can become mismatched on restored databases when using ALTER DATABASE...NEW_BROKER or when Service Broker is disabled, which resets the GUID to all zeros. This function helps identify such scenarios during database migrations and troubleshooting.", "Links": "https://dbatools.io/Find-DbaDatabase", "Synopsis": "Searches multiple SQL Server instances for databases matching name, owner, or Service Broker GUID patterns", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Property", "Specifies which database property to search against: Name, Owner, or ServiceBrokerGuid. Defaults to Name for database name searches.\r\nUse Owner when tracking down databases by their owner for security audits, or ServiceBrokerGuid when identifying databases with matching Service Broker configurations across environments.", "", false, "false", "Name", "Name,ServiceBrokerGuid,Owner" ], [ "Pattern", "The search value to match against the specified property. Supports regular expressions for flexible pattern matching.\r\nUse simple strings like \u0027Sales\u0027 or \u0027Test\u0027, or regex patterns like \u0027^prod.*db$\u0027 to match databases starting with \u0027prod\u0027 and ending with \u0027db\u0027.", "", true, "false", "", "" ], [ "Exact", "Forces an exact string match instead of pattern matching. Use this when you need to find databases with names that exactly match your search term.\r\nParticularly useful when searching for database names that contain regex special characters or when you want precise matches without wildcards.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Index", "Lookup" ], "CommandName": "Find-DbaDbDisabledIndex", "Name": "Find-DbaDbDisabledIndex", "Author": "Jason Squires, sqlnotnull.com", "Syntax": "Find-DbaDbDisabledIndex [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-NoClobber] [-Append] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.Data.DataRow\nReturns one data row per disabled index found in the scanned databases.\nProperties:\r\n- DatabaseName: The name of the database containing the disabled index\r\n- DatabaseId: The numeric ID of the database in SQL Server\r\n- SchemaName: The schema name where the table containing the index resides\r\n- TableName: The name of the table that contains the disabled index\r\n- ObjectId: The numeric ID of the table object in SQL Server\r\n- IndexName: The name of the disabled index\r\n- IndexId: The numeric ID of the index within the table (0 = clustered index, 1+ = nonclustered indexes)\r\n- TypeDesc: The type of index (e.g., CLUSTERED, NONCLUSTERED, HEAP, SPATIAL, etc.)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eFind-DbaDbDisabledIndex -SqlInstance sql2005\nGenerates the SQL statements to drop the selected disabled indexes on server \"sql2005\".\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eFind-DbaDbDisabledIndex -SqlInstance sqlserver2016 -SqlCredential $cred\nGenerates the SQL statements to drop the selected disabled indexes on server \"sqlserver2016\", using SQL Authentication to connect to the database.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eFind-DbaDbDisabledIndex -SqlInstance sqlserver2016 -Database db1, db2\nGenerates the SQL Statement to drop selected indexes in databases db1 \u0026 db2 on server \"sqlserver2016\".\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eFind-DbaDbDisabledIndex -SqlInstance sqlserver2016\nGenerates the SQL statements to drop selected indexes on all user databases.", "Description": "Scans SQL Server databases to locate indexes that have been disabled, returning detailed information including database, schema, table, and index names. Disabled indexes consume storage space but aren\u0027t maintained during data modifications, making them candidates for cleanup or re-enabling. This is useful for database maintenance, performance troubleshooting, and identifying indexes that were disabled during bulk operations but never re-enabled.", "Links": "https://dbatools.io/Find-DbaDbDisabledIndex", "Synopsis": "Identifies disabled indexes across SQL Server databases", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to scan for disabled indexes. Accepts multiple database names and supports wildcards.\r\nWhen not specified, all accessible user databases on the instance will be scanned.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific databases from the disabled index scan. Useful when you want to scan most databases but skip certain ones like staging or temp databases.\r\nAccepts multiple database names to exclude from the operation.", "", false, "false", "", "" ], [ "NoClobber", "Prevents overwriting existing output files when used with file export functionality.\r\nNote: This parameter is currently not implemented in the function logic.", "", false, "false", "False", "" ], [ "Append", "Appends results to existing output files instead of overwriting them when used with file export functionality.\r\nNote: This parameter is currently not implemented in the function logic.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Index", "Lookup" ], "CommandName": "Find-DbaDbDuplicateIndex", "Name": "Find-DbaDbDuplicateIndex", "Author": "Claudio Silva (@ClaudioESSilva)", "Syntax": "Find-DbaDbDuplicateIndex [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [-IncludeOverlapping] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per duplicate or overlapping index found. When exact duplicates are found, one object is returned for each matching index (e.g., if three indexes have identical structure, three \r\nobjects are returned).\nProperties:\r\n- DatabaseName: Name of the database containing the index\r\n- TableName: Name of the table containing the index (schema.table format)\r\n- IndexName: Name of the index\r\n- KeyColumns: Comma-separated list of key columns with sort direction (ASC/DESC)\r\n- IncludedColumns: Comma-separated list of included columns with sort direction (empty if none)\r\n- IndexType: Type of index (CLUSTERED or NONCLUSTERED)\r\n- IndexSizeMB: Size of the index in megabytes (Decimal)\r\n- RowCount: Number of rows in the table (Integer)\r\n- IsDisabled: Boolean indicating if the index is disabled\r\n- IsUnique: Boolean indicating if the index is unique\r\n- IsFiltered: Boolean indicating if the index has a filter condition (SQL Server 2008+)\r\n- CompressionDescription: Data compression type applied to the index - NONE, ROW, or PAGE (SQL Server 2008+)\nThe function returns different property sets based on the target SQL Server version:\r\n- SQL Server 2005: Excludes IsFiltered and CompressionDescription properties\r\n- SQL Server 2008+: Includes all properties including IsFiltered and CompressionDescription", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eFind-DbaDbDuplicateIndex -SqlInstance sql2005\nReturns duplicate indexes found on sql2005\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eFind-DbaDbDuplicateIndex -SqlInstance sql2017 -SqlCredential sqladmin\nFinds exact duplicate indexes on all user databases present on sql2017, using SQL authentication.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eFind-DbaDbDuplicateIndex -SqlInstance sql2017 -Database db1, db2\nFinds exact duplicate indexes on the db1 and db2 databases.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eFind-DbaDbDuplicateIndex -SqlInstance sql2017 -IncludeOverlapping\nFinds both duplicate and overlapping indexes on all user databases.", "Description": "Scans database tables to identify indexes that have identical or overlapping column structures, which consume unnecessary storage space and slow down insert, update, and delete operations. Duplicate indexes have exactly the same key columns, included columns, and filter conditions, while overlapping indexes share some key columns but differ in others.\n\nUse this during index maintenance to eliminate redundant indexes before they impact performance. The function analyzes sys.indexes and related catalog views to compare column structures, accounting for column order and sort direction. On SQL Server 2008 and higher, filtered indexes are properly differentiated using the IsFiltered property.\n\nSupports both clustered and nonclustered indexes on user tables, excluding system objects. Returns comprehensive index details including size in MB, row counts, compression settings (2008+), and disabled/filtered status to help prioritize which duplicates to remove.\n\nOutput includes:\nTableName, IndexName, KeyColumns, IncludedColumns, IndexSizeMB, IndexType, CompressionDescription (2008+), RowCount, IsDisabled, IsFiltered (2008+)", "Links": "https://dbatools.io/Find-DbaDbDuplicateIndex", "Synopsis": "Identifies duplicate and overlapping indexes that waste storage space and degrade insert performance", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to analyze for duplicate indexes. Accepts wildcards for pattern matching.\r\nUse this when you need to focus on specific databases instead of scanning all databases on the instance, which can be time-consuming on servers with many databases.", "", false, "false", "", "" ], [ "IncludeOverlapping", "Finds indexes that share some key columns but have different column structures, not just exact duplicates.\r\nUse this to identify indexes where one might be redundant because it\u0027s covered by another with additional columns.\r\nFor example, an index on (CustomerID) would be flagged as overlapping with an index on (CustomerID, OrderDate).", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "AutoGrow", "Database", "Lookup" ], "CommandName": "Find-DbaDbGrowthEvent", "Name": "Find-DbaDbGrowthEvent", "Author": "Aaron Nelson", "Syntax": "Find-DbaDbGrowthEvent [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-EventType] \u003cString\u003e] [[-FileType] \u003cString\u003e] [-UseLocalTime] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database auto-growth or auto-shrink event found in the SQL Server Default Trace. The specific events returned depend on the -EventType and -FileType parameters.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name where the SQL Server instance is running\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- EventClass: The trace event class (92 = Data File Auto Grow, 93 = Log File Auto Grow, 94 = Data File Auto Shrink, 95 = Log File Auto Shrink)\r\n- DatabaseName: The name of the database that experienced the growth/shrink event\r\n- Filename: The path and name of the database file that was resized\r\n- Duration: The duration of the event in milliseconds\r\n- StartTime: The date and time when the event started (UTC by default, local time if -UseLocalTime is specified)\r\n- EndTime: The date and time when the event ended (UTC by default, local time if -UseLocalTime is specified)\r\n- ChangeInSize: The size change during the event in megabytes (MB)\r\n- ApplicationName: The application that triggered the growth event\r\n- HostName: The host name of the client that triggered the event\nAdditional properties available (accessible with Select-Object *):\r\n- DatabaseId: The numeric database identifier from sys.databases\r\n- SessionLoginName: The SQL login name of the session that triggered the event\r\n- SPID: The SQL Server session ID (SPID) of the process that caused the event\r\n- OrderRank: Internal ranking value used for trace file rotation ordering", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eFind-DbaDbGrowthEvent -SqlInstance localhost\nReturns any database AutoGrow events in the Default Trace with UTC time for the instance for every database on the localhost instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eFind-DbaDbGrowthEvent -SqlInstance localhost -UseLocalTime\nReturns any database AutoGrow events in the Default Trace with the local time of the instance for every database on the localhost instance.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eFind-DbaDbGrowthEvent -SqlInstance ServerA\\SQL2016, ServerA\\SQL2014\nReturns any database AutoGrow events in the Default Traces for every database on ServerA\\sql2016 \u0026 ServerA\\SQL2014.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eFind-DbaDbGrowthEvent -SqlInstance ServerA\\SQL2016 | Format-Table -AutoSize -Wrap\nReturns any database AutoGrow events in the Default Trace for every database on the ServerA\\SQL2016 instance in a table format.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eFind-DbaDbGrowthEvent -SqlInstance ServerA\\SQL2016 -EventType Shrink\nReturns any database Auto Shrink events in the Default Trace for every database on the ServerA\\SQL2016 instance.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eFind-DbaDbGrowthEvent -SqlInstance ServerA\\SQL2016 -EventType Growth -FileType Data\nReturns any database Auto Growth events on data files in the Default Trace for every database on the ServerA\\SQL2016 instance.", "Description": "Queries the SQL Server Default Trace to identify when database files have automatically grown or shrunk, providing detailed timing and size change information essential for performance troubleshooting and capacity planning. This function helps DBAs investigate unexpected performance slowdowns caused by auto-growth events, analyze storage growth patterns to optimize initial file sizing, and track which applications or processes are triggering unplanned database expansions. Returns comprehensive details including the exact time of each event, size change in MB, duration, and the application/user that caused the growth, so you don\u0027t have to manually parse trace files or write custom T-SQL queries.\n\nThe following events are included:\n92 - Data File Auto Grow\n93 - Log File Auto Grow\n94 - Data File Auto Shrink\n95 - Log File Auto Shrink", "Links": "https://dbatools.io/Find-DbaDbGrowthEvent", "Synopsis": "Retrieves database auto-growth and auto-shrink events from the SQL Server Default Trace", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to search for growth events. Accepts wildcards for pattern matching.\r\nUse this to focus on specific databases when investigating growth patterns or troubleshooting performance issues.\r\nIf not specified, searches all databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specified databases from the growth event search. Accepts wildcards for pattern matching.\r\nUseful when you want to skip system databases like tempdb or exclude databases with known frequent growth events.\r\nCommonly used with tempdb, master, model, and msdb to focus on user databases only.", "", false, "false", "", "" ], [ "EventType", "Filters results to show only specific types of database size change events.\r\nUse \u0027Growth\u0027 to identify when files expanded automatically, which can indicate undersized initial allocations or unexpected data volume increases.\r\nUse \u0027Shrink\u0027 to find auto-shrink events that may be causing performance problems due to file fragmentation.\nAllowed values: Growth, Shrink", "", false, "false", "", "Growth,Shrink" ], [ "FileType", "Filters results to show only data file or log file growth events.\r\nUse \u0027Data\u0027 when investigating storage capacity issues or unexpected table growth patterns.\r\nUse \u0027Log\u0027 when troubleshooting transaction log growth, often caused by long-running transactions or delayed log backups.\nAllowed values: Data, Log", "", false, "false", "", "Data,Log" ], [ "UseLocalTime", "Returns timestamps in the SQL Server instance\u0027s local time zone instead of converting to UTC.\r\nUse this when correlating growth events with local application schedules, maintenance windows, or business hours.\r\nBy default, times are converted to UTC for consistency across multiple time zones.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Index", "Lookup" ], "CommandName": "Find-DbaDbUnusedIndex", "Name": "Find-DbaDbUnusedIndex", "Author": "Aaron Nelson (@SQLvariant), SQLvariant.com", "Syntax": "Find-DbaDbUnusedIndex [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-IgnoreUptime] [[-Seeks] \u003cInt32\u003e] [[-Scans] \u003cInt32\u003e] [[-Lookups] \u003cInt32\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per unused index found. Each object contains comprehensive index usage statistics and metadata.\nProperties:\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: The name of the database containing the index\r\n- DatabaseId: Numeric ID of the database\r\n- Schema: The schema name containing the table\r\n- Table: The name of the table containing the index\r\n- ObjectId: Numeric ID of the table object\r\n- IndexName: The name of the index\r\n- IndexId: Numeric ID of the index within the table\r\n- TypeDesc: Type description of the index (CLUSTERED, NONCLUSTERED, etc.)\r\n- UserSeeks: Number of seek operations by user queries since last SQL Server restart\r\n- UserScans: Number of scan operations by user queries since last SQL Server restart\r\n- UserLookups: Number of lookup operations by user queries since last SQL Server restart\r\n- UserUpdates: Number of update operations on the index by user queries since last SQL Server restart\r\n- LastUserSeek: Timestamp of the last seek operation by user queries\r\n- LastUserScan: Timestamp of the last scan operation by user queries\r\n- LastUserLookup: Timestamp of the last lookup operation by user queries\r\n- LastUserUpdate: Timestamp of the last update operation by user queries\r\n- SystemSeeks: Number of seek operations by system queries since last SQL Server restart\r\n- SystemScans: Number of scan operations by system queries since last SQL Server restart\r\n- SystemLookup: Number of lookup operations by system queries since last SQL Server restart\r\n- SystemUpdates: Number of update operations on the index by system queries since last SQL Server restart\r\n- LastSystemSeek: Timestamp of the last seek operation by system queries\r\n- LastSystemScan: Timestamp of the last scan operation by system queries\r\n- LastSystemLookup: Timestamp of the last lookup operation by system queries\r\n- LastSystemUpdate: Timestamp of the last update operation by system queries\r\n- IndexSizeMB: Size of the index in megabytes\r\n- RowCount: Number of rows in the index\r\n- CompressionDescription: Data compression type (SQL Server 2008+ only). Values include None, Row, Page, ColumnStore, or ColumnStoreArchive\nIndexes are identified as \"unused\" when their usage statistics fall below the specified thresholds (default: UserSeeks \u003c 1, UserScans \u003c 1, UserLookups \u003c 1).", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eFind-DbaDbUnusedIndex -SqlInstance sql2016 -Database db1, db2\nFinds unused indexes on db1 and db2 on sql2016\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eFind-DbaDbUnusedIndex -SqlInstance sql2016 -SqlCredential $cred\nFinds unused indexes on db1 and db2 on sql2016 using SQL Authentication to connect to the server\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2016 | Find-DbaDbUnusedIndex\nFinds unused indexes on all databases on sql2016\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2019 | Find-DbaDbUnusedIndex -Seeks 10 -Scans 100 -Lookups 1000\nFinds \u0027unused\u0027 indexes with user_seeks \u003c 10, user_scans \u003c 100, and user_lookups \u003c 1000 on all databases on sql2019.\r\nNote that these additional parameters provide flexibility to define what is considered an \u0027unused\u0027 index.", "Description": "Analyzes index usage statistics from sys.dm_db_index_usage_stats to identify indexes with minimal activity that consume storage space and slow down data modifications without providing query performance benefits.\n\nThis function helps DBAs optimize database performance by finding indexes that are rarely or never used, so you can safely remove them to reduce maintenance overhead, speed up INSERT/UPDATE/DELETE operations, and free up disk space. The function uses customizable thresholds for seeks, scans, and lookups to define what constitutes \"unused,\" with safety checks to ensure SQL Server has been running long enough (7+ days) for reliable statistics.\n\nSupports clustered and non-clustered indexes on SQL Server 2005 and higher, with additional data compression information available on SQL Server 2008+. Results include index size, row count, and detailed usage patterns to help prioritize which indexes to drop first.", "Links": "https://dbatools.io/Find-DbaDbUnusedIndex", "Synopsis": "Identifies database indexes with low usage statistics that may be candidates for removal", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The SQL Server you want to check for unused indexes.", "", false, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to analyze for unused indexes. Accepts wildcards for pattern matching.\r\nUse this when you want to focus on specific databases rather than scanning the entire instance, which is helpful for large environments or targeted maintenance windows.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific databases from the unused index analysis. Accepts wildcards for pattern matching.\r\nCommonly used to skip system databases, read-only databases, or databases undergoing maintenance that shouldn\u0027t be modified.", "", false, "false", "", "" ], [ "IgnoreUptime", "Bypasses the 7-day uptime check that normally prevents analysis on recently restarted instances.\r\nUse this when you need results from a server with recent restarts, but be aware that usage statistics may not reflect normal workload patterns.", "", false, "false", "False", "" ], [ "Seeks", "Sets the threshold for user seeks below which an index is considered unused. Default is 1.\r\nUser seeks occur when the query optimizer uses the index to efficiently locate specific rows. Increase this value to find indexes with very low seek activity rather than completely unused ones.", "", false, "false", "1", "" ], [ "Scans", "Sets the threshold for user scans below which an index is considered unused. Default is 1.\r\nUser scans happen when queries read multiple rows through the index, often for range queries or aggregations. Higher values help identify indexes with minimal scan activity.", "", false, "false", "1", "" ], [ "Lookups", "Sets the threshold for user lookups below which an index is considered unused. Default is 1.\r\nUser lookups occur when a nonclustered index is used to locate rows that are then retrieved from the clustered index. This typically indicates bookmark lookup operations.", "", false, "false", "1", "" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase for pipeline operations.\r\nThis allows you to chain commands and apply complex database filtering logic before analyzing unused indexes.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Instance", "Connect", "SqlServer", "Lookup" ], "CommandName": "Find-DbaInstance", "Name": "Find-DbaInstance", "Author": "Scott Sutherland, 2018 NetSPI | Friedrich Weinmann (@FredWeinmann)", "Syntax": "Find-DbaInstance [-Credential \u003cPSCredential\u003e] [-SqlCredential \u003cPSCredential\u003e] [-ScanType {TCPPort | SqlConnect | SqlService | DNSResolve | SPN | Browser | Ping | Default | All}] [-DomainController \u003cString\u003e] [-TCPPort \u003cInt32[]\u003e] [-MinimumConfidence {None | Low | Medium | High}] [-EnableException] [\u003cCommonParameters\u003e]\nFind-DbaInstance -ComputerName \u003cDbaInstanceParameter[]\u003e [-Credential \u003cPSCredential\u003e] [-SqlCredential \u003cPSCredential\u003e] [-ScanType {TCPPort | SqlConnect | SqlService | DNSResolve | SPN | Browser | Ping | Default | All}] [-DomainController \u003cString\u003e] [-TCPPort \u003cInt32[]\u003e] [-MinimumConfidence {None | Low | Medium | High}] [-EnableException] [\u003cCommonParameters\u003e]\nFind-DbaInstance -DiscoveryType {IPRange | DomainSPN | Domain | DataSourceEnumeration | DomainServer | All} [-Credential \u003cPSCredential\u003e] [-SqlCredential \u003cPSCredential\u003e] [-ScanType {TCPPort | SqlConnect | SqlService | DNSResolve | SPN | Browser | Ping | Default | All}] [-IpAddress \u003cString[]\u003e] [-DomainController \u003cString\u003e] [-TCPPort \u003cInt32[]\u003e] [-MinimumConfidence {None | Low | Medium | High}] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Dataplat.Dbatools.Discovery.DbaInstanceReport\nReturns one DbaInstanceReport object per SQL Server instance discovered and validated on target computers. Each object represents a potential SQL Server instance with details about how it was \r\ndetected and its current availability status.\nProperties:\r\n- MachineName: The network name of the computer where the instance was discovered\r\n- ComputerName: The computer name (same as MachineName for consistency)\r\n- InstanceName: The SQL Server instance name (e.g., \"SQLEXPRESS\", \"MSSQLSERVER\"). Null if only a port was detected\r\n- SqlInstance: The full SQL Server instance identifier (ComputerName\\InstanceName or ComputerName:Port)\r\n- Port: The TCP port number where the instance is listening (e.g., 1433). Null if InstanceName was discovered instead\r\n- Confidence: Confidence level of the discovery (High, Medium, or Low). High = certain instance found, Medium = likely instance, Low = possible instance\r\n- Availability: Instance availability status (Available, Unavailable, or Unknown). Set when SQL Service status is detected\r\n- DnsResolution: System.Net.IPHostEntry object containing DNS resolution results if DNSResolve scan was performed. Null if not resolved\r\n- Ping: Boolean indicating whether the computer responded to ping (True/False/Null)\r\n- TcpConnected: Boolean indicating whether the detected TCP port is open/connected (True/False)\r\n- SqlConnected: Boolean indicating whether a successful SQL connection was established (True/False). Only set if SqlConnect scan type is enabled\r\n- Timestamp: DateTime when the discovery scan was performed\r\n- ScanTypes: Bit-flag of scan types that were performed (Browser, SQLService, SPN, TCPPort, DNSResolve, Ping, SqlConnect, All)\r\n- Services: Array of SQL Service objects detected via WMI/CIM for this instance. Objects have properties: ServiceType, State, InstanceName, DisplayName\r\n- SystemServices: Array of system SQL Service objects detected (services without an InstanceName like SQL Server Agent service parent processes)\r\n- SPNs: Array of Service Principal Names registered in Active Directory for this computer/instance\r\n- BrowseReply: Custom object containing details from Browser service query if Browser scan was performed. Properties include InstanceName, TCPPort, Version, IsClustered\r\n- PortsScanned: Array of port scan results. Each object has properties: ComputerName, Port, IsOpen\nThe output is filtered by MinimumConfidence parameter - only instances meeting or exceeding the specified confidence level are returned.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eFind-DbaInstance -DiscoveryType Domain, DataSourceEnumeration\nPerforms a network search for SQL Instances by:\r\n- Looking up the Service Principal Names of computers in Active Directory\r\n- Using the UDP broadcast based auto-discovery of SSMS\r\nAfter that it will extensively scan all hosts thus discovered for instances.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eFind-DbaInstance -DiscoveryType All\nPerforms a network search for SQL Instances, using all discovery protocols:\r\n- Active directory search for Service Principal Names\r\n- SQL Instance Enumeration (same as SSMS does)\r\n- All IPAddresses in the current computer\u0027s subnets of all connected network interfaces\r\nNote: This scan will take a long time, due to including the IP Scan\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-ADComputer -Filter \"*\" | Find-DbaInstance\nScans all computers in the domain for SQL Instances, using a deep probe:\r\n- Tries resolving the name in DNS\r\n- Tries pinging the computer\r\n- Tries listing all SQL Services using CIM/WMI\r\n- Tries discovering all instances via the browser service\r\n- Tries connecting to the default TCP Port (1433)\r\n- Tries connecting to the TCP port of each discovered instance\r\n- Tries to establish a SQL connection to the server using default windows credentials\r\n- Tries looking up the Service Principal Names for each instance\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-Content .\\servers.txt | Find-DbaInstance -SqlCredential $cred -ScanType Browser, SqlConnect\nReads all servers from the servers.txt file (one server per line),\r\nthen scans each of them for instances using the browser service\r\nand finally attempts to connect to each instance found using the specified credentials.\r\nthen scans each of them for instances using the browser service and SqlService\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eFind-DbaInstance -ComputerName localhost | Get-DbaDatabase | Format-Table -Wrap\nScans localhost for instances using the browser service, traverses all instances for all databases and displays all information in a formatted table.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e$databases = Find-DbaInstance -ComputerName localhost | Get-DbaDatabase\nPS C:\\\u003e $results = $databases | Select-Object SqlInstance, Name, Status, RecoveryModel, SizeMB, Compatibility, Owner, LastFullBackup, LastDiffBackup, LastLogBackup\r\nPS C:\\\u003e $results | Format-Table -Wrap\nScans localhost for instances using the browser service, traverses all instances for all databases and displays a subset of the important information in a formatted table.\nUsing this method regularly is not recommended. Use Get-DbaService or Get-DbaRegServer instead.", "Description": "This function performs comprehensive SQL Server instance discovery across your network infrastructure using multiple detection methods. Perfect for creating complete SQL Server inventories, compliance auditing, and finding forgotten or undocumented instances that might pose security risks.\n\nThe function combines two distinct phases to systematically locate SQL Server instances:\n\nDiscovery Phase:\nCompiles target lists using several methods: Active Directory SPN lookups (finds registered SQL services), SQL Instance Enumeration (same method SSMS uses for browsing), IP address range scanning (scans entire subnets), and Domain Server searches (targets all Windows servers in AD).\nYou can specify explicit computer lists via -ComputerName or use automated discovery via -DiscoveryType.\n\nScan Phase:\nTests each discovered target using multiple verification methods: Browser service queries, WMI/CIM SQL service enumeration, TCP port connectivity testing (default 1433), DNS resolution checks, ping tests, and optional SQL connection attempts.\nResults include confidence levels (High/Medium/Low) based on scan success combinations.\n\nCommon DBA scenarios:\n- Audit all SQL instances before migrations or compliance reviews\n- Discover shadow IT databases that bypass standard deployment processes\n- Inventory instances across acquired companies or merged networks\n- Validate disaster recovery documentation against actual running instances\n- Identify instances running on non-standard ports or with unusual configurations\n\nSecurity considerations:\nThe Discovery phase is non-intrusive, but the Scan phase generates network traffic and authentication attempts across your infrastructure. This creates audit logs and may trigger security monitoring systems. Some scan types require elevated privileges for WMI access or SQL connections. Always coordinate with your security team before running network-wide scans, especially in regulated environments.", "Links": "https://dbatools.io/Find-DbaInstance", "Synopsis": "Discovers SQL Server instances across networks using multiple scanning methods", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies target computers to scan for SQL Server instances. Accepts computer names, IP addresses, or output from Get-ADComputer.\r\nUse this when you have a specific list of servers to inventory rather than performing network-wide discovery.\r\nOnly the computer name portion is used - connection strings or SQL instance details are ignored.", "", true, "true (ByValue)", "", "" ], [ "DiscoveryType", "Specifies which automatic discovery methods to use for finding SQL Server targets across your network.\r\nChoose discovery methods based on your environment: DomainSPN for registered services, DataSourceEnumeration for broadcasting instances, IPRange for subnet scanning, or DomainServer for all Windows \r\nservers.\r\nCombine multiple types for comprehensive coverage, but be aware that IPRange scanning can be time-intensive on large networks.\n---\n- SPN Lookup\n The function tries to connect active directory to look up all computers with registered SQL Instances.\r\n Not all instances need to be registered properly, making this not 100% reliable.\r\n By default, your nearest Domain Controller is contacted for this scan.\r\n However it is possible to explicitly state the DC to contact using its DistinguishedName and the \u0027-DomainController\u0027 parameter.\r\n If credentials were specified using the \u0027-Credential\u0027 parameter, those same credentials are used to perform this lookup, allowing the scan of other domains.\n- SQL Instance Enumeration\n This uses the default UDP Broadcast based instance enumeration used by SSMS to detect instances.\r\n Note that the result from this is not used in the actual scan, but only to compile a list of computers to scan.\r\n To enable the same results for the scan, ensure that the \u0027Browser\u0027 scan is enabled.\n- IP Address range:\n This \u0027Discovery\u0027 uses a range of IPAddresses and simply passes them on to be tested.\r\n See the \u0027Description\u0027 part of help on security issues of network scanning.\r\n By default, it will enumerate all ethernet network adapters on the local computer and scan the entire subnet they are on.\r\n By using the \u0027-IpAddress\u0027 parameter, custom network ranges can be specified.\n- Domain Server:\n This will discover every single computer in Active Directory that is a Windows Server and enabled.\r\n By default, your nearest Domain Controller is contacted for this scan.\r\n However it is possible to explicitly state the DC to contact using its DistinguishedName and the \u0027-DomainController\u0027 parameter.\r\n If credentials were specified using the \u0027-Credential\u0027 parameter, those same credentials are used to perform this lookup, allowing the scan of other domains.", "", true, "false", "", "" ], [ "Credential", "The credentials to use on windows network connection.\r\nThese credentials are used for:\r\n- Contact to domain controllers for SPN lookups (only if explicit Domain Controller is specified)\r\n- CIM/WMI contact to the scanned computers during the scan phase (see the \u0027-ScanType\u0027 parameter documentation on affected scans).", "", false, "false", "", "" ], [ "SqlCredential", "The credentials used to connect to SqlInstances to during the scan phase.\r\nSee the \u0027-ScanType\u0027 parameter documentation on affected scans.", "", false, "false", "", "" ], [ "ScanType", "Controls which verification methods are used to detect and validate SQL Server instances on target computers.\r\nUse specific scan types to optimize performance or reduce network impact - for example, use only Browser and SQLService for quick detection, or add SqlConnect for definitive verification.\r\nDefault performs all scans except SqlConnect, which requires explicit specification due to authentication overhead.\nScans:\r\n- Browser\r\n - Tries discovering all instances via the browser service\r\n - This scan detects instances.\r\n- SQLService\r\n - Tries listing all SQL Services using CIM/WMI\r\n - This scan uses credentials specified in the \u0027-Credential\u0027 parameter if any.\r\n - This scan detects instances.\r\n - Success in this scan guarantees high confidence (See parameter \u0027-MinimumConfidence\u0027 for details).\r\n- SPN\r\n - Tries looking up the Service Principal Names for each instance\r\n - Will use the nearest Domain Controller by default\r\n - Target a specific domain controller using the \u0027-DomainController\u0027 parameter\r\n - If using the \u0027-DomainController\u0027 parameter, use the \u0027-Credential\u0027 parameter to specify the credentials used to connect\r\n- TCPPort\r\n - Tries connecting to the TCP Ports.\r\n - By default, port 1433 is connected to.\r\n - The parameter \u0027-TCPPort\u0027 can be used to provide a list of port numbers to scan.\r\n - This scan detects possible instances. Since other services might bind to a given port, this is not the most reliable test.\r\n - This scan is also used to validate found SPNs if both scans are used in combination\r\n- DNSResolve\r\n - Tries resolving the computername in DNS\r\n- Ping\r\n - Tries pinging the computer. Failure will NOT terminate scans.\r\n- SqlConnect\r\n - Tries to establish a SQL connection to the server\r\n - Uses windows credentials by default\r\n - Specify custom credentials using the \u0027-SqlCredential\u0027 parameter\r\n - This scan is not used by default\r\n - Success in this scan guarantees high confidence (See parameter \u0027-MinimumConfidence\u0027 for details).\r\n- All\r\n - All of the above", "", false, "false", "Default", "Default,SQLService,Browser,TCPPort,All,SPN,Ping,SqlConnect,DNSResolve" ], [ "IpAddress", "Defines custom IP ranges to scan when using IPRange discovery instead of auto-detecting local subnets.\r\nUse this to target specific network segments like DMZ subnets or remote locations where SQL instances might exist.\r\nSupports multiple formats: single IPs (10.1.1.1), ranges (10.1.1.1-10.1.1.5), CIDR notation (10.1.1.1/24), or subnet masks (10.1.1.1/255.255.255.0).", "", false, "false", "", "" ], [ "DomainController", "Specifies a specific domain controller for Active Directory queries when using DomainSPN or DomainServer discovery.\r\nUse this when you need to target a specific DC for cross-domain searches or when the nearest DC is unavailable.\r\nRequires the \u0027-Credential\u0027 parameter when querying remote domains or when explicit authentication is needed.", "", false, "false", "", "" ], [ "TCPPort", "Specifies which TCP ports to test for SQL Server connectivity during port scanning.\r\nUse this to detect instances running on non-standard ports or to scan multiple common SQL Server ports like 1433, 1434, and custom ports.\r\nDefaults to 1433 (SQL Server default port).", "", false, "false", "1433", "" ], [ "MinimumConfidence", "Filters results based on how certain the scan is that a SQL Server instance exists on each target.\r\nUse High for definitive results when you need accurate inventories, Medium for likely instances, or Low for comprehensive discovery that includes potential false positives.\r\nHigh confidence requires successful SQL service detection or connection, Medium requires browser response or combined port+SPN validation, Low accepts single indicators like open ports or SPN records.", "", false, "false", "Low", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Login", "Group", "Lookup" ], "CommandName": "Find-DbaLoginInGroup", "Name": "Find-DbaLoginInGroup", "Author": "Stephen Bennett, sqlnotesfromtheunderground.wordpress.com | Simone Bizzotto (@niphlod)", "Syntax": "Find-DbaLoginInGroup [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Login] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per individual Active Directory user found within Windows group logins on the SQL Server instance(s). When -Login is specified, only groups containing that user are returned.\nDefault display properties (via Select-DefaultView):\r\n- SqlInstance: The SQL Server instance name (in the format COMPUTER\\INSTANCE or just COMPUTER for default instance)\r\n- Login: The individual user account in DOMAIN\\username format\r\n- DisplayName: The user\u0027s display name from Active Directory\r\n- MemberOf: The Windows AD group login on SQL Server that contains this user\r\n- ParentADGroupLogin: The original parent group login (same as MemberOf unless accessed through nested groups)\nAdditional properties available:\r\n- InstanceName: The SQL Server instance name only (without computer name)\r\n- ComputerName: The name of the computer hosting the SQL Server instance\nAll properties are accessible using Select-Object * or by directly referencing property names even though only default properties are displayed by default.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eFind-DbaLoginInGroup -SqlInstance DEV01 -Login \"MyDomain\\Stephen.Bennett\"\nReturns all active directory groups with logins on Sql Instance DEV01 that contain the AD user Stephen.Bennett.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eFind-DbaLoginInGroup -SqlInstance DEV01\nReturns all active directory users within all windows AD groups that have logins on the instance.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eFind-DbaLoginInGroup -SqlInstance DEV01 | Where-Object Login -like \u0027*stephen*\u0027\nReturns all active directory users within all windows AD groups that have logins on the instance whose login contains \"stephen\"", "Description": "Connects to SQL Server instances and recursively expands all Windows Active Directory group logins to reveal the individual user accounts that inherit access through group membership. This function queries Active Directory to enumerate all users within each Windows group login, including nested groups, providing a complete view of who actually has access to your SQL Server through group-based authentication. Essential for security audits, compliance reporting, and troubleshooting login access issues when you need to know which specific users can connect through group logins.", "Links": "https://dbatools.io/Find-DbaLoginInGroup", "Synopsis": "Discovers individual Active Directory users within Windows group logins on SQL Server instances.", "Availability": "Windows only", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "PSCredential object to connect under. If not specified, current Windows login will be used.", "", false, "false", "", "" ], [ "Login", "Filters results to show only Windows Active Directory groups that contain the specified individual user account(s).\r\nUse this when you need to find which AD groups give a specific user access to SQL Server, rather than seeing all users from all groups.\r\nAccepts multiple login names in DOMAIN\\username format and supports pipeline input.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Object", "Lookup", "Find" ], "CommandName": "Find-DbaObject", "Name": "Find-DbaObject", "Author": "the dbatools team + Claude", "Syntax": "Find-DbaObject [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-Pattern] \u003cString\u003e [[-ObjectType] \u003cString[]\u003e] [-IncludeColumns] [-IncludeSystemObjects] [-IncludeSystemDatabases] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per match found. When -IncludeColumns is used, there may be multiple results\r\nper database object (one for the object name match plus one per matching column name).\nProperties:\r\n- ComputerName: The computer name of the SQL Server instance\r\n- SqlInstance: The SQL Server instance name\r\n- Database: The database containing the matched object\r\n- Schema: The schema of the matched object (null for database DDL triggers)\r\n- Name: The name of the matched object\r\n- ObjectType: The SQL Server type description (e.g., USER_TABLE, VIEW, SQL_STORED_PROCEDURE)\r\n- MatchType: \"ObjectName\" when the object name matched, \"ColumnName\" when a column name matched\r\n- ColumnName: The matching column name when MatchType is \"ColumnName\", otherwise null\r\n- CreateDate: DateTime when the object was created\r\n- LastModified: DateTime when the object was last modified", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eFind-DbaObject -SqlInstance DEV01 -Pattern Service\nSearches all user databases on DEV01 for any object whose name contains \"Service\".\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eFind-DbaObject -SqlInstance DEV01 -Pattern Service -IncludeColumns\nSearches all user databases on DEV01 for objects named with \"Service\" and tables/views\r\nthat have columns whose names contain \"Service\".\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eFind-DbaObject -SqlInstance DEV01 -Pattern \"^Customer\" -ObjectType Table\nFinds all user tables on DEV01 whose names start with \"Customer\".\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eFind-DbaObject -SqlInstance DEV01 -Pattern \"Invoice\" -Database Accounting -IncludeColumns\nSearches the Accounting database for objects and columns related to \"Invoice\".\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eFind-DbaObject -SqlInstance sql2019 -Pattern \"Service|Product\" -ObjectType Table, View\nFinds all tables and views whose names contain either \"Service\" or \"Product\".", "Description": "Provides a unified search across all database object types (tables, views, stored procedures, functions,\nsynonyms, triggers) by matching their names against a regex pattern. Optionally extends the search to\ncolumn names within tables and views. This complements the existing Find-DbaStoredProcedure, Find-DbaView,\nand Find-DbaTrigger commands which search object definition text rather than object or column names.\n\nUses T-SQL queries against sys.objects and sys.columns for optimal performance. Pattern matching is\nperformed in PowerShell using full regex syntax.", "Links": "https://dbatools.io/Find-DbaObject", "Synopsis": "Searches database objects by name or column name across SQL Server databases using regex patterns.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory -\r\nIntegrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies one or more databases to search. When omitted, searches all user databases on the instance.\r\nUse this to focus searches on specific databases when you know where the objects are located.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies databases to skip during the search. Accepts multiple database names.\r\nUse this to exclude large databases or test environments from the search.", "", false, "false", "", "" ], [ "Pattern", "The regular expression pattern to match against object names (and optionally column names).\r\nSupports full regex syntax for complex pattern matching. For example, use \"^Customer\" to find objects\r\nstarting with \"Customer\", or \"Service|Product\" to find objects mentioning either term.", "", true, "false", "", "" ], [ "ObjectType", "Filters the search to specific object types. Accepts one or more of:\r\n- Table: User tables (sys.objects type U)\r\n- View: Views (sys.objects type V)\r\n- StoredProcedure: Stored procedures (sys.objects type P)\r\n- ScalarFunction: Scalar-valued functions (sys.objects type FN)\r\n- TableValuedFunction: Inline and multi-statement table-valued functions (sys.objects type IF/TF)\r\n- Synonym: Synonyms (sys.objects type SN)\r\n- Trigger: Object-level DML triggers plus database DDL SQL triggers\r\n- All: All of the above (default)", "", false, "false", "@(\"All\")", "Table,View,StoredProcedure,ScalarFunction,TableValuedFunction,Synonym,Trigger,All" ], [ "IncludeColumns", "When specified, additionally searches column names within tables and views for the given pattern.\r\nResults with column name matches include a MatchType of \"ColumnName\" and the matching column name.\r\nThis is useful for finding which tables or views contain a column related to a specific domain concept.", "", false, "false", "False", "" ], [ "IncludeSystemObjects", "Includes system objects (those shipped with SQL Server) in the search results.\r\nBy default, only user-created objects are searched.", "", false, "false", "False", "" ], [ "IncludeSystemDatabases", "Includes system databases (master, model, msdb, tempdb) in the search scope.\r\nBy default, only user databases are searched.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Orphan", "Database", "DatabaseFile", "Lookup" ], "CommandName": "Find-DbaOrphanedFile", "Name": "Find-DbaOrphanedFile", "Author": "Sander Stad (@sqlstad), sqlstad.nl", "Syntax": "Find-DbaOrphanedFile -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Path \u003cString[]\u003e] [-FileType \u003cString[]\u003e] [-LocalOnly] [-EnableException] [-Recurse] [\u003cCommonParameters\u003e]\nFind-DbaOrphanedFile -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Path \u003cString[]\u003e] [-FileType \u003cString[]\u003e] [-RemoteOnly] [-EnableException] [-Recurse] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.String (when -LocalOnly is specified)\nReturns the local file path to each orphaned file.\nSystem.String (when -RemoteOnly is specified)\nReturns the UNC path to each orphaned file.\nPSCustomObject (default)\nReturns one object per orphaned file found with the following properties:\n- ComputerName: The name of the computer where the SQL Server instance is running\r\n- InstanceName: The name of the SQL Server instance\r\n- SqlInstance: The full SQL Server instance name in the format ComputerName\\InstanceName\r\n- Server: The server name (same as ComputerName for most instances)\r\n- Filename: The local file path to the orphaned file\r\n- RemoteFilename: The UNC network path to the orphaned file (\\\\ComputerName\\share\\path format)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eFind-DbaOrphanedFile -SqlInstance sqlserver2014a\nConnects to sqlserver2014a, authenticating with Windows credentials, and searches for orphaned files. Returns server name, local filename, and unc path to file.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eFind-DbaOrphanedFile -SqlInstance sqlserver2014a -SqlCredential $cred\nConnects to sqlserver2014a, authenticating with SQL Server authentication, and searches for orphaned files. Returns server name, local filename, and unc path to file.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eFind-DbaOrphanedFile -SqlInstance sql2014 -Path \u0027E:\\Dir1\u0027, \u0027E:\\Dir2\u0027\nFinds the orphaned files in \"E:\\Dir1\" and \"E:Dir2\" in addition to the default directories.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eFind-DbaOrphanedFile -SqlInstance sql2014 -Path \u0027E:\\Dir1\u0027 -Recurse\nFinds the orphaned files in \"E:\\Dir1\" and any of its subdirectories in addition to the default directories.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eFind-DbaOrphanedFile -SqlInstance sql2014 -LocalOnly\nReturns only the local file paths for orphaned files.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eFind-DbaOrphanedFile -SqlInstance sql2014 -RemoteOnly\nReturns only the remote file path for orphaned files.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eFind-DbaOrphanedFile -SqlInstance sql2014, sql2016 -FileType fsf, mld\nFinds the orphaned ending with \".fsf\" and \".mld\" in addition to the default filetypes \".mdf\", \".ldf\", \".ndf\" for both the servers sql2014 and sql2016.", "Description": "Scans filesystem directories for database files (.mdf, .ldf, .ndf) that exist on disk but are not currently attached to the SQL Server instance. This is essential for cleanup operations after database drops, detaches, or failed restores that leave behind orphaned files consuming disk space.\n\nThe command compares files found via xp_dirtree against sys.master_files to identify true orphans. By default, it searches the root\\data directory, default data and log paths, system paths, and any directory currently used by attached databases.\n\nPerfect for storage cleanup scenarios where you need to reclaim disk space by identifying leftover database files that can be safely removed. You can specify additional file types using -FileType and additional search paths using -Path parameter.", "Links": "https://dbatools.io/Find-DbaOrphanedFile", "Synopsis": "Identifies database files on disk that are not attached to any SQL Server database instance", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or higher.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Path", "Specifies additional directories to search beyond the default SQL Server data and log paths. Use this when databases were stored in non-standard locations or when you suspect orphaned files exist in \r\ncustom backup/restore directories. Accepts multiple paths and searches them alongside the automatically detected SQL Server directories.", "", false, "false", "", "" ], [ "FileType", "Specifies additional file extensions to search for beyond the default database file types (mdf, ldf, ndf). Use this to find orphaned Full-Text catalog files (ftcat), backup files (bak, trn), or other \r\nSQL Server-related files. Do not include the dot when specifying extensions (use \"bak\" not \".bak\").", "", false, "false", "", "" ], [ "LocalOnly", "Returns only the local file paths without server or UNC information. Use this when you need simple file paths for scripting file removal operations or when working with a single server. Not \r\nrecommended for multi-server environments since it omits which server the file belongs to.", "", false, "false", "False", "" ], [ "RemoteOnly", "Returns only the UNC network paths to orphaned files. Use this when you need to access files remotely for cleanup operations or when building scripts that run from a central management server. \r\nProvides the \\\\server\\share\\path format needed for remote file operations.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "Recurse", "Searches all subdirectories within the specified paths in addition to the root directories. Use this when database files may be organized in nested folder structures or when conducting comprehensive \r\ncleanup of complex directory hierarchies. Without this switch, only the immediate directories are searched.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Table", "Lookup" ], "CommandName": "Find-DbaSimilarTable", "Name": "Find-DbaSimilarTable", "Author": "Jana Sattainathan (@SQLJana), sqljana.wordpress.com", "Syntax": "Find-DbaSimilarTable [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-SchemaName] \u003cString\u003e] [[-TableName] \u003cString\u003e] [-ExcludeViews] [-IncludeSystemDatabases] [[-MatchPercentThreshold] \u003cInt32\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per matching table pair found. Each object represents one source table matched against one similar table.\nProperties:\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance format)\r\n- Table: The fully qualified name of the source table (database.schema.table)\r\n- MatchingTable: The fully qualified name of the matching table found (database.schema.table)\r\n- MatchPercent: Percentage of matching column names between the two tables (0-100)\r\n- OriginalDatabaseName: Name of the database containing the source table\r\n- OriginalDatabaseId: System database ID for the source table\u0027s database\r\n- OriginalSchemaName: Name of the schema containing the source table\r\n- OriginalTableName: Name of the source table\r\n- OriginalTableNameRankInDB: Dense ranking of the table among all tables in its database (used for processing order)\r\n- OriginalTableType: Type of the source table (TABLE or VIEW)\r\n- OriginalColumnCount: Number of columns in the source table\r\n- MatchingDatabaseName: Name of the database containing the matching table\r\n- MatchingDatabaseId: System database ID for the matching table\u0027s database\r\n- MatchingSchemaName: Name of the schema containing the matching table\r\n- MatchingTableName: Name of the matching table\r\n- MatchingTableType: Type of the matching table (TABLE or VIEW)\r\n- MatchingColumnCount: Number of columns in the matching table", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eFind-DbaSimilarTable -SqlInstance DEV01\nSearches all user database tables and views for each, returns all tables or views with their matching tables/views and match percent\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eFind-DbaSimilarTable -SqlInstance DEV01 -Database AdventureWorks\nSearches AdventureWorks database and lists tables/views and their corresponding matching tables/views with match percent\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eFind-DbaSimilarTable -SqlInstance DEV01 -Database AdventureWorks -SchemaName HumanResource\nSearches AdventureWorks database and lists tables/views in the HumanResource schema with their corresponding matching tables/views with match percent\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eFind-DbaSimilarTable -SqlInstance DEV01 -Database AdventureWorks -SchemaName HumanResource -Table Employee\nSearches AdventureWorks database and lists tables/views in the HumanResource schema and table Employee with its corresponding matching tables/views with match percent\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eFind-DbaSimilarTable -SqlInstance DEV01 -Database AdventureWorks -MatchPercentThreshold 60\nSearches AdventureWorks database and lists all tables/views with its corresponding matching tables/views with match percent greater than or equal to 60", "Description": "Analyzes table and view structures across databases by comparing column names using INFORMATION_SCHEMA views. Returns a match percentage showing how similar structures are based on shared column names.\n\nPerfect for finding archive tables that mirror production structures, identifying tables that might serve similar purposes across databases, or discovering where specific table patterns are used throughout your SQL Server environment.\n\nYou can search across all databases or target specific databases, schemas, or tables. The function calculates match percentages so you can set minimum thresholds to filter results and focus on the most relevant matches.\n\nMore information can be found here: https://sqljana.wordpress.com/2017/03/31/sql-server-find-tables-with-similar-table-structure/", "Links": "https://dbatools.io/Find-DbaSimilarTable", "Synopsis": "Finds tables and views with similar structures by comparing column names across databases", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to search for similar table structures. Accepts multiple database names.\r\nUse this to limit the search scope when you know which databases contain the tables you\u0027re comparing.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific databases from the similarity search. Accepts multiple database names.\r\nUseful for skipping temp databases, development copies, or databases with known irrelevant structures.", "", false, "false", "", "" ], [ "SchemaName", "Limits the search to tables within a specific schema. Only tables in this schema will be used as reference structures.\r\nUse this when comparing tables within a logical grouping like \u0027Sales\u0027, \u0027HR\u0027, or \u0027Archive\u0027 schemas.", "", false, "false", "", "" ], [ "TableName", "Uses a specific table as the reference structure to find similar tables across databases.\r\nPerfect for finding archive versions of production tables or identifying tables that mirror a known structure.\r\nWhen the table exists in multiple schemas, all instances are used as reference points.", "", false, "false", "", "" ], [ "ExcludeViews", "Excludes views from both the reference objects and the comparison results, focusing only on physical tables.\r\nUse this when you need to find similar table structures for data migration or archiving where views aren\u0027t relevant.", "", false, "false", "False", "" ], [ "IncludeSystemDatabases", "Includes system databases (master, model, msdb, tempdb) in the similarity search.\r\nTypically used when troubleshooting system table relationships or comparing custom objects in system databases.", "", false, "false", "False", "" ], [ "MatchPercentThreshold", "Sets the minimum percentage of matching column names required to include a table pair in results.\r\nUse values like 50 for loose matches, 80 for close structural similarity, or 95 for near-identical tables.\r\nZero matches are always excluded regardless of this threshold.", "", false, "false", "0", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "StoredProcedure", "Proc", "Lookup" ], "CommandName": "Find-DbaStoredProcedure", "Name": "Find-DbaStoredProcedure", "Author": "Stephen Bennett, sqlnotesfromtheunderground.wordpress.com", "Syntax": "Find-DbaStoredProcedure [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-Pattern] \u003cString\u003e [-IncludeSystemObjects] [-IncludeSystemDatabases] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per stored procedure that matches the search pattern. Each object represents a matching stored procedure with details about where the pattern was found.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- SqlInstance: The SQL Server instance name\r\n- Database: The database containing the stored procedure\r\n- DatabaseId: The database ID (system assigned identifier)\r\n- Schema: The schema that owns the stored procedure\r\n- Name: The name of the stored procedure\r\n- Owner: The owner of the stored procedure\r\n- IsSystemObject: Boolean indicating if this is a system stored procedure\r\n- CreateDate: DateTime when the stored procedure was created\r\n- LastModified: DateTime when the stored procedure was last modified\r\n- StoredProcedureTextFound: Formatted string containing matching line numbers and the matched text lines (formatted as \"(LineNumber: #) matched text\")\nAdditional properties available via Select-Object * (excluded from default view):\r\n- StoredProcedure: The full Microsoft.SqlServer.Management.Smo.StoredProcedure object with all SMO properties\r\n- StoredProcedureFullText: The complete T-SQL source code of the stored procedure as a string", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eFind-DbaStoredProcedure -SqlInstance DEV01 -Pattern whatever\nSearches all user databases stored procedures for \"whatever\" in the text body\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eFind-DbaStoredProcedure -SqlInstance sql2016 -Pattern \u0027\\w+@\\w+\\.\\w+\u0027\nSearches all databases for all stored procedures that contain a valid email pattern in the text body\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eFind-DbaStoredProcedure -SqlInstance DEV01 -Database MyDB -Pattern \u0027some string\u0027 -Verbose\nSearches in \"mydb\" database stored procedures for \"some string\" in the text body\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eFind-DbaStoredProcedure -SqlInstance sql2016 -Database MyDB -Pattern RUNTIME -IncludeSystemObjects\nSearches in \"mydb\" database stored procedures for \"runtime\" in the text body", "Description": "Searches through stored procedure source code to find specific strings, patterns, or regex expressions within the procedure definitions. This is particularly useful for finding hardcoded values, deprecated function calls, security vulnerabilities, or specific business logic across your database environment. The function examines the actual T-SQL code stored in sys.sql_modules and can search across multiple databases simultaneously. Results include the matching line numbers and context, making it easy to locate exactly where patterns appear within each procedure. You can scope searches to specific databases and choose whether to include system stored procedures and system databases in the search.", "Links": "https://dbatools.io/Find-DbaStoredProcedure", "Synopsis": "Searches stored procedure definitions for specific text patterns or regex expressions across SQL Server databases.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to search for stored procedures containing the pattern. Accepts database names and supports wildcards.\r\nWhen omitted, searches all user databases on the instance. Use this to focus searches on specific databases when you know where procedures are located.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies databases to skip during the stored procedure search. Accepts database names and supports wildcards.\r\nUse this when you want to search most databases but exclude specific ones like test environments or databases with sensitive procedures.", "", false, "false", "", "" ], [ "Pattern", "Specifies the text pattern or regular expression to search for within stored procedure definitions. Supports full regex syntax for complex pattern matching.\r\nUse this to find hardcoded values, deprecated functions, security vulnerabilities, or specific business logic across procedure source code.", "", true, "false", "", "" ], [ "IncludeSystemObjects", "Includes system stored procedures (those shipped with SQL Server) in the search results. By default, only user-created procedures are searched.\r\nUse this when investigating system procedures or when patterns might exist in Microsoft-provided code. Warning: this significantly slows performance when searching multiple databases.", "", false, "false", "False", "" ], [ "IncludeSystemDatabases", "Includes system databases (master, model, msdb, tempdb) in the search scope. By default, only user databases are searched.\r\nUse this when investigating system procedures or when your pattern might exist in maintenance scripts stored in system databases.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Trigger", "Lookup" ], "CommandName": "Find-DbaTrigger", "Name": "Find-DbaTrigger", "Author": "Claudio Silva (@ClaudioESSilva)", "Syntax": "Find-DbaTrigger [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-Pattern] \u003cString\u003e [[-TriggerLevel] \u003cString\u003e] [-IncludeSystemObjects] [-IncludeSystemDatabases] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per trigger found that matches the Pattern. Objects are returned for matches at any of the three trigger levels (Server, Database, or Object).\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- SqlInstance: The SQL Server instance name\r\n- TriggerLevel: The type of trigger (Server, Database, or Object)\r\n- Database: The name of the database containing the trigger (null for server-level triggers)\r\n- DatabaseId: The ID of the database (null for server-level triggers)\r\n- Object: The name of the parent object (table/view) for object-level triggers, null for server and database-level\r\n- Name: The name of the trigger\r\n- IsSystemObject: Boolean indicating if this is a system-created trigger\r\n- CreateDate: DateTime when the trigger was created\r\n- LastModified: DateTime when the trigger was last modified\r\n- TriggerTextFound: String containing matching lines with line numbers in format \"(LineNumber: #) matched_text\"\nAdditional properties available (not displayed by default):\r\n- Trigger: The SMO Trigger object\r\n- TriggerFullText: The complete T-SQL definition of the trigger", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eFind-DbaTrigger -SqlInstance DEV01 -Pattern whatever\nSearches all user databases triggers for \"whatever\" in the text body\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eFind-DbaTrigger -SqlInstance sql2016 -Pattern \u0027\\w+@\\w+\\.\\w+\u0027\nSearches all databases for all triggers that contain a valid email pattern in the text body\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eFind-DbaTrigger -SqlInstance DEV01 -Database MyDB -Pattern \u0027some string\u0027 -Verbose\nSearches in \"mydb\" database triggers for \"some string\" in the text body\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eFind-DbaTrigger -SqlInstance sql2016 -Database MyDB -Pattern RUNTIME -IncludeSystemObjects\nSearches in \"mydb\" database triggers for \"runtime\" in the text body", "Description": "Searches through SQL Server trigger definitions to find specific text patterns, supporting both literal strings and regular expressions. Examines triggers at three levels: server-level triggers, database-level DDL triggers, and object-level DML triggers on tables and views.\n\nThis is particularly useful when you need to find triggers that reference specific objects before making schema changes, locate hardcoded values that need updating, or audit trigger code for compliance requirements. The function returns matching lines with line numbers, making it easy to pinpoint exactly where patterns occur in trigger code.\n\nWhen you specify specific databases, server-level trigger searches are skipped to focus the search scope. The function uses efficient SQL queries against system catalog views to examine trigger definitions without loading all trigger objects into memory.", "Links": "https://dbatools.io/Find-DbaTrigger", "Synopsis": "Searches trigger code across server, database, and object levels for specific text patterns or regex matches.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to search for triggers. Accepts an array of database names for targeting specific databases.\r\nWhen specified, server-level triggers are automatically excluded from the search to focus on database and object-level triggers.\r\nIf omitted, searches all user databases plus any server-level triggers.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific databases from the trigger search. Accepts an array of database names to skip during processing.\r\nUse this when you want to search most databases but avoid specific ones like staging or temporary databases.", "", false, "false", "", "" ], [ "Pattern", "The text pattern or regular expression to search for within trigger definitions. Supports full regex syntax for complex pattern matching.\r\nUse this to find triggers containing specific table names, column references, or code patterns before making schema changes.\r\nResults show matching lines with line numbers to pinpoint exactly where the pattern occurs.", "", true, "false", "", "" ], [ "TriggerLevel", "Controls which types of triggers to search: Server (instance-level logon triggers), Database (DDL triggers), Object (DML triggers on tables and views), or All.\r\nUse specific levels to narrow your search when you know what type of trigger contains the pattern you\u0027re looking for.\r\nDefaults to All, which searches server-level triggers, database DDL triggers, and object-level DML triggers.", "", false, "false", "All", "All,Server,Database,Object" ], [ "IncludeSystemObjects", "Includes system-created triggers in the search results. By default, only user-created triggers are searched.\r\nUse this when you need to examine built-in triggers for troubleshooting or audit purposes.\r\nWarning: This significantly impacts performance when searching across multiple databases.", "", false, "false", "False", "" ], [ "IncludeSystemDatabases", "Includes system databases (master, model, msdb, tempdb) in the trigger search. By default, only user databases are searched.\r\nUse this when troubleshooting system-level issues or when you need to examine triggers in system databases for audit purposes.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Object", "Lookup" ], "CommandName": "Find-DbaUserObject", "Name": "Find-DbaUserObject", "Author": "Stephen Bennett, sqlnotesfromtheunderground.wordpress.com", "Syntax": "Find-DbaUserObject [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Pattern] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per user-owned SQL Server object found. The function scans multiple object types across the instance and all accessible databases, so you may receive many objects from a single \r\ninstance.\nProperties:\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name (ServiceName from SMO)\r\n- SqlInstance: The full SQL Server instance name (computer\\instance format)\r\n- Type: The category of object found. Possible values include:\r\n * Database\r\n * Agent Job\r\n * Credential\r\n * Proxy\r\n * Agent Step\r\n * Endpoint\r\n * Server Role\r\n * Schema\r\n * Database Role\r\n * Database Assembly\r\n * Database Synonyms\r\n- Owner: The login or user account that owns the object (string format for logins, domain\\username for Windows accounts)\r\n- Name: The name of the object\r\n- Parent: The name of the parent container for the object (e.g., server name for databases, job name for job steps, database name for schemas)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eFind-DbaUserObject -SqlInstance DEV01 -Pattern ad\\stephen\nSearches user objects for owner ad\\stephen\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eFind-DbaUserObject -SqlInstance DEV01 -Verbose\nShows all user owned (non-sa, non-dbo) objects and verbose output", "Description": "Scans SQL Server instances to identify objects with non-standard ownership, which is critical for security auditing and user management.\nWhen removing user accounts or performing security reviews, you need to know what objects they own to avoid breaking dependencies.\nThis function searches databases, SQL Agent jobs, credentials, proxies, endpoints, server roles, schemas, database roles, assemblies, and synonyms.\nUse the Pattern parameter to search for objects owned by a specific user, or run without it to find all user-owned objects that aren\u0027t owned by system accounts.", "Links": "https://dbatools.io/Find-DbaUserObject", "Synopsis": "Finds SQL Server objects owned by users other than sa or dbo, or searches for objects owned by a specific user pattern.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Pattern", "Searches for objects owned by accounts matching this regex pattern. Use this when looking for objects owned by a specific user or group of users.\r\nWhen omitted, finds all objects not owned by system accounts (sa/dbo). Supports Windows domain accounts like \u0027DOMAIN\\username\u0027 or SQL logins.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "View", "Lookup" ], "CommandName": "Find-DbaView", "Name": "Find-DbaView", "Author": "Claudio Silva (@ClaudioESSilva)", "Syntax": "Find-DbaView [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-Pattern] \u003cString\u003e [-IncludeSystemObjects] [-IncludeSystemDatabases] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per view matching the specified pattern. Each object represents a single matching view with the matching text lines highlighted.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The name of the server where the view is located\r\n- SqlInstance: The SQL Server instance name\r\n- Database: The database name containing the view\r\n- DatabaseId: The internal database ID\r\n- Schema: The schema of the view\r\n- Name: The name of the view\r\n- Owner: The owner of the view\r\n- IsSystemObject: Boolean indicating if this is a system view (affected by -IncludeSystemObjects parameter)\r\n- CreateDate: DateTime when the view was created\r\n- LastModified: DateTime when the view was last modified\r\n- ViewTextFound: String containing the matching lines with line numbers in format \"(LineNumber: N) matched text\"\nAdditional properties available (via Select-Object *):\r\n- View: The SMO View object itself\r\n- ViewFullText: The complete text body of the view definition", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eFind-DbaView -SqlInstance DEV01 -Pattern whatever\nSearches all user databases views for \"whatever\" in the text body\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eFind-DbaView -SqlInstance sql2016 -Pattern \u0027\\w+@\\w+\\.\\w+\u0027\nSearches all databases for all views that contain a valid email pattern in the text body\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eFind-DbaView -SqlInstance DEV01 -Database MyDB -Pattern \u0027some string\u0027 -Verbose\nSearches in \"mydb\" database views for \"some string\" in the text body\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eFind-DbaView -SqlInstance sql2016 -Database MyDB -Pattern RUNTIME -IncludeSystemObjects\nSearches in \"mydb\" database views for \"runtime\" in the text body", "Description": "Scans view definitions across one or more databases to locate specific text patterns, table references, or code constructs. This helps DBAs identify views that reference particular tables before schema changes, find views containing sensitive data patterns like email addresses or SSNs, or locate views with specific business logic during troubleshooting. The function searches the actual view definition text (TextBody) and returns the matching views along with line numbers showing exactly where the pattern was found, making it easy to understand the context of each match.", "Links": "https://dbatools.io/Find-DbaView", "Synopsis": "Searches database views for specific text patterns or regular expressions in their definitions.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to search for views containing the pattern. Accepts wildcards and multiple database names.\r\nUse this when you need to limit the search scope to specific databases instead of scanning all databases on the instance.\r\nParticularly useful for large instances where you only need to check certain application databases.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies databases to skip during the view search operation. Accepts multiple database names.\r\nUse this to exclude large databases that you know don\u0027t contain relevant views, speeding up the search process.\r\nCommon exclusions include development copies, archive databases, or third-party application databases.", "", false, "false", "", "" ], [ "Pattern", "Specifies the text pattern or regular expression to search for within view definitions. Supports full regex syntax for complex pattern matching.\r\nUse this to find views referencing specific tables before schema changes, locate sensitive data patterns like email addresses or SSNs, or identify views containing particular business logic.\r\nCommon patterns include table names, column references, function calls, or data validation expressions.", "", true, "false", "", "" ], [ "IncludeSystemObjects", "Includes system views in the search operation alongside user-created views. System views are excluded by default.\r\nUse this when troubleshooting issues that might involve system view dependencies or when documenting complete database schemas.\r\nWarning: Including system views significantly slows down the search, especially when scanning multiple databases or large instances.", "", false, "false", "False", "" ], [ "IncludeSystemDatabases", "Includes system databases (master, model, msdb, tempdb) in the view search operation. System databases are excluded by default.\r\nUse this when investigating SQL Server internals, troubleshooting replication issues, or documenting complete instance configurations.\r\nMost DBA tasks focus on user databases, so this parameter is typically used for advanced troubleshooting scenarios.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "DisasterRecovery", "Backup", "Restore" ], "CommandName": "Format-DbaBackupInformation", "Name": "Format-DbaBackupInformation", "Author": "Stuart Moore (@napalmgram), stuart-moore.com", "Syntax": "Format-DbaBackupInformation [-BackupHistory] \u003cObject[]\u003e [[-ReplaceDatabaseName] \u003cObject\u003e] [-ReplaceDbNameInFile] [[-DataFileDirectory] \u003cString\u003e] [[-LogFileDirectory] \u003cString\u003e] [[-DestinationFileStreamDirectory] \u003cString\u003e] [[-DatabaseNamePrefix] \u003cString\u003e] [[-DatabaseFilePrefix] \u003cString\u003e] [[-DatabaseFileSuffix] \u003cString\u003e] [[-RebaseBackupFolder] \u003cString\u003e] [-Continue] [[-FileMapping] \u003cHashtable\u003e] [[-PathSep] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Dataplat.Dbatools.Database.BackupHistory\nReturns the modified backup history objects with updated metadata for restore operations. The same number of objects that were passed in are returned, with any requested modifications applied.\nDefault properties (from input backup history object):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: The database name (modified if -ReplaceDatabaseName or -DatabaseNamePrefix was used)\r\n- UserName: The user who performed the backup\r\n- Start: DateTime when the backup started\r\n- End: DateTime when the backup completed\r\n- Duration: TimeSpan of the backup operation\r\n- Path: Array of backup file paths (modified if -RebaseBackupFolder was used)\r\n- FileList: Array of file objects containing Type, LogicalName, PhysicalName, and Size (modified if -DataFileDirectory, -LogFileDirectory, -DestinationFileStreamDirectory, -DatabaseFilePrefix, \r\n-DatabaseFileSuffix, -ReplaceDbNameInFile, or -FileMapping was used)\r\n- TotalSize: Total size of the backup in bytes\r\n- CompressedBackupSize: Size of compressed backup in bytes\r\n- Type: Backup type (Database, Database Differential, or Transaction Log)\r\n- BackupSetId: Unique identifier for the backup set (GUID)\r\n- DeviceType: Type of backup device (typically Disk)\r\n- FullName: Array of full paths to backup files (modified if -RebaseBackupFolder was used)\r\n- Position: Position of the backup within the device\r\n- FirstLsn: First Log Sequence Number in this backup\r\n- DatabaseBackupLsn: Log Sequence Number of the database backup\r\n- CheckpointLSN: Checkpoint Log Sequence Number\r\n- LastLsn: Last Log Sequence Number in this backup\r\n- SoftwareVersionMajor: Major version of SQL Server that created the backup\r\n- RecoveryModel: Database recovery model at time of backup\r\n- IsCopyOnly: Boolean indicating if this is a copy-only backup\nAdditional properties added by this function:\r\n- OriginalDatabase: String containing the original database name before any replacements or prefixes\r\n- OriginalFileList: Object array containing the original FileList before any path modifications\r\n- OriginalFullName: String array containing the original backup file paths before rebasing\r\n- IsVerified: Boolean indicating if the backup has been verified (initialized to $False)\nAll properties from the input backup history objects are preserved and accessible, with selective properties modified based on the parameters specified.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$History | Format-DbaBackupInformation -ReplaceDatabaseName NewDb -ReplaceDbNameInFile\nChanges as database name references to NewDb, both in the database name and any restore paths. Note, this will fail if the BackupHistory object contains backups for more than 1 database\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$History | Format-DbaBackupInformation -ReplaceDatabaseName @{\u0027OldB\u0027=\u0027NewDb\u0027;\u0027ProdHr\u0027=\u0027DevHr\u0027}\nWill change all occurrences of original database name in the backup history (names and restore paths) using the mapping in the hashtable.\r\nIn this example any occurrence of OldDb will be replaced with NewDb and ProdHr with DevPR\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$History | Format-DbaBackupInformation -DataFileDirectory \u0027D:\\DataFiles\\\u0027 -LogFileDirectory \u0027E:\\LogFiles\\\nThis example with change the restore path for all data files (everything that is not a log file) to d:\\datafiles\r\nAnd all Transaction Log files will be restored to E:\\Logfiles\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$History | Format-DbaBackupInformation -RebaseBackupFolder f:\\backups\nThis example changes the location that SQL Server will look for the backups. This is useful if you\u0027ve moved the backups to a different location", "Description": "Takes backup history objects from Select-DbaBackupInformation and transforms them for restore scenarios where you need to change database names, file locations, or backup paths. This is essential for disaster recovery situations where you\u0027re restoring to different servers, renaming databases, or moving files to new storage locations. The function handles all the metadata transformations needed so you don\u0027t have to manually edit restore paths and database references before running Restore-DbaDatabase.", "Links": "https://dbatools.io/Format-DbaBackupInformation", "Synopsis": "Modifies backup history metadata to prepare database restores with different names, paths, or locations", "Availability": "Windows, Linux, macOS", "Params": [ [ "BackupHistory", "Backup history objects from Select-DbaBackupInformation that contain metadata about database backups.\r\nUse this to pass backup information that needs to be modified for restore operations to different locations or with different names.", "", true, "true (ByValue)", "", "" ], [ "ReplaceDatabaseName", "Changes the database name in backup history to prepare for restoring with a different name. Pass a single string to rename one database, or a hashtable to map multiple old names to new names.\r\nUse this when restoring databases to different environments or creating copies with new names.\r\nDatabase names in file paths are also updated, but logical file names require separate ALTER DATABASE commands after restore.", "", false, "false", "", "" ], [ "ReplaceDbNameInFile", "Replaces occurrences of the original database name within physical file names with the new database name.\r\nUse this in combination with ReplaceDatabaseName to ensure file names match the new database name and avoid confusion during restore operations.", "", false, "false", "False", "" ], [ "DataFileDirectory", "Sets the destination directory for all data files during restore. This overrides the original file locations stored in the backup.\r\nUse this when restoring to servers with different drive configurations or when consolidating database files to specific storage locations.", "", false, "false", "", "" ], [ "LogFileDirectory", "Sets the destination directory specifically for transaction log files during restore. This takes precedence over DataFileDirectory for log files only.\r\nUse this to place log files on separate storage from data files for performance optimization or storage management requirements.", "", false, "false", "", "" ], [ "DestinationFileStreamDirectory", "Sets the destination directory for FileStream data files during restore. This takes precedence over DataFileDirectory for FileStream files only.\r\nUse this when databases contain FileStream data that needs to be stored on specific storage optimized for large file handling.", "", false, "false", "", "" ], [ "DatabaseNamePrefix", "Adds a prefix to all database names during the restore operation. The prefix is applied after any name replacements from ReplaceDatabaseName.\r\nUse this to create standardized naming conventions like adding environment identifiers (Dev_, Test_, etc.) to restored databases.", "", false, "false", "", "" ], [ "DatabaseFilePrefix", "Adds a prefix to the physical file names of all restored database files (both data and log files).\r\nUse this to avoid file name conflicts when restoring to servers that already have files with the same names.", "", false, "false", "", "" ], [ "DatabaseFileSuffix", "Adds a suffix to the physical file names of all restored database files (both data and log files).\r\nUse this to create unique file names when restoring multiple copies of the same database or to add version identifiers to restored files.", "", false, "false", "", "" ], [ "RebaseBackupFolder", "Changes the path where SQL Server will look for backup files during the restore operation.\r\nUse this when backup files have been moved to a different location since the backup was created, such as copying backups to a disaster recovery site.", "", false, "false", "", "" ], [ "Continue", "Marks this as part of an ongoing restore sequence that will have additional transaction log backups applied later.\r\nUse this when performing point-in-time recovery scenarios where you need to restore a full backup followed by multiple log backups.", "", false, "false", "False", "" ], [ "FileMapping", "Maps specific logical file names to custom physical file paths during restore. Use hashtable format like @{\u0027LogicalName1\u0027=\u0027C:\\NewPath\\file1.mdf\u0027}.\r\nUse this when you need granular control over where individual database files are restored, overriding directory-based parameters.\r\nFiles not specified in the mapping retain their original locations, and this parameter takes precedence over all other file location settings.", "", false, "false", "", "" ], [ "PathSep", "Specifies the path separator character for file paths. Defaults to backslash (\\) for Windows.\r\nUse forward slash (/) when working with Linux SQL Server instances or when backup history contains Unix-style paths.", "", false, "false", "\\", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "AG", "HA" ], "CommandName": "Get-DbaAgBackupHistory", "Name": "Get-DbaAgBackupHistory", "Author": "Chrissy LeMaire (@cl) | Stuart Moore (@napalmgram), Andreas Jordan", "Syntax": "Get-DbaAgBackupHistory -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] -AvailabilityGroup \u003cString\u003e [-Database \u003cString[]\u003e] [-ExcludeDatabase \u003cString[]\u003e] [-IncludeCopyOnly] [-Since \u003cDateTime\u003e] [-RecoveryFork \u003cString\u003e] [-Last] [-LastFull] [-LastDiff] [-LastLog] [-DeviceType \u003cString[]\u003e] [-Raw] [-LastLsn \u003cBigInteger\u003e] [-IncludeMirror] [-Type \u003cString[]\u003e] [-LsnSort \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]\nGet-DbaAgBackupHistory -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] -AvailabilityGroup \u003cString\u003e [-Database \u003cString[]\u003e] [-ExcludeDatabase \u003cString[]\u003e] [-IncludeCopyOnly] [-Force] [-Since \u003cDateTime\u003e] [-RecoveryFork \u003cString\u003e] [-Last] [-LastFull] [-LastDiff] [-LastLog] [-DeviceType \u003cString[]\u003e] [-Raw] [-LastLsn \u003cBigInteger\u003e] [-IncludeMirror] [-Type \u003cString[]\u003e] [-LsnSort \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Dataplat.Dbatools.Database.BackupHistory\nReturns one backup history object per physical backup file or per logical backup set (when backups are striped across multiple files). Each object represents backup metadata from MSDB including \r\ntiming, size, location, and LSN sequence information.\nWhen using -Last, -LastFull, -LastDiff, or -LastLog switches, returns only the most recent backup(s) of the specified type across all replicas. When using -Raw, returns individual backup file details \r\ninstead of grouping striped files into single logical sets.\nDefault display properties (via Format-Table):\r\n- SqlInstance: The SQL Server instance name (computer\\instance)\r\n- Database: The database name\r\n- Type: Backup type (Full, Differential, Log, etc.)\r\n- TotalSize: Total backup size in bytes\r\n- DeviceType: Storage device type (Disk, Tape, URL, Virtual Device)\r\n- Start: Backup start time\r\n- Duration: Time span of the backup operation\r\n- End: Backup completion time\nAdditional properties available (can be accessed via Select-Object *):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- DatabaseId: System database identifier\r\n- UserName: User account that performed the backup\r\n- CompressedBackupSize: Compressed size in bytes (null for SQL Server 2005)\r\n- CompressionRatio: Ratio of TotalSize to CompressedBackupSize\r\n- BackupSetId: Unique identifier for the backup set\r\n- Software: Backup software name and version\r\n- FullName: Full path to backup files (array of paths for striped backups)\r\n- FileList: Details of database and log files in the backup\r\n- Position: Position of the backup within a media set\r\n- FirstLsn: Starting log sequence number\r\n- DatabaseBackupLsn: LSN of the last database backup (for log/differential backups)\r\n- CheckpointLsn: LSN of the checkpoint during backup\r\n- LastLsn: Ending log sequence number\r\n- SoftwareVersionMajor: Major version of SQL Server that created the backup\r\n- IsCopyOnly: Boolean indicating if this is a copy-only backup\r\n- LastRecoveryForkGuid: GUID of the recovery fork (for point-in-time restore scenarios)\r\n- RecoveryModel: Database recovery model at time of backup (Simple, Full, BulkLogged)\r\n- EncryptorThumbprint: Thumbprint of backup encryption certificate (SQL Server 2014+)\r\n- EncryptorType: Type of encryption used (SQL Server 2014+)\r\n- KeyAlgorithm: Encryption algorithm used (SQL Server 2014+)\r\n- AvailabilityGroupName: Name of the availability group being queried (added by Get-DbaAgBackupHistory)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAgBackupHistory -SqlInstance AgListener -AvailabilityGroup AgTest1\nReturns information for all database backups still in msdb history on all replicas of availability group AgTest1 using the listener AgListener to determine all replicas.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgBackupHistory -SqlInstance Replica1, Replica2, Replica3 -AvailabilityGroup AgTest1\nReturns information for all database backups still in msdb history on the given replicas of availability group AgTest1.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaAgBackupHistory -SqlInstance \u0027Replica1:14331\u0027, \u0027Replica2:14332\u0027, \u0027Replica3:14333\u0027 -AvailabilityGroup AgTest1\nReturns information for all database backups still in msdb history on the given replicas of availability group AgTest1 using custom ports.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$ListOfReplicas | Get-DbaAgBackupHistory -AvailabilityGroup AgTest1\nReturns information for all database backups still in msdb history on the replicas in $ListOfReplicas of availability group AgTest1.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$serverWithAllAgs = Connect-DbaInstance -SqlInstance MyServer\nPS C:\\\u003e $allAgResults = foreach ( $ag in $serverWithAllAgs.AvailabilityGroups ) {\r\n\u003e\u003e Get-DbaAgBackupHistory -SqlInstance $ag.AvailabilityReplicas.Name -AvailabilityGroup $ag.Name\r\n\u003e\u003e }\r\n\u003e\u003e\r\nPS C:\\\u003e $allAgResults | Format-Table\nReturns information for all database backups on all replicas for all availability groups on SQL instance MyServer.", "Description": "Queries the msdb backup history tables across all replicas in an Availability Group and aggregates the results into a unified view. This function automatically discovers all replicas (either through a listener or by querying individual replicas) and combines their backup history data, which is essential since backups can be taken from any replica but are only recorded in the local msdb.\n\nThis solves the common AG challenge where DBAs need to piece together backup history from multiple replicas for compliance reporting, recovery planning, or troubleshooting backup strategies. You can filter by backup type, date ranges, or get just the latest backups, and the function adds availability group context to help identify which replica performed each backup.\n\nReference: http://www.sqlhub.com/2011/07/find-your-backup-history-in-sql-server.html", "Links": "https://dbatools.io/Get-DbaAgBackupHistory", "Synopsis": "Retrieves backup history from msdb across all replicas in a SQL Server Availability Group", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.\nIf you pass in one availability group listener, all replicas are automatically determined and queried.\r\nIf you pass in a list of individual replicas, they will be queried. This enables you to use custom ports for the replicas.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Credential object used to connect to the SQL Server instance as a different user. This can be a Windows or SQL Server account. Windows users are determined by the existence of a backslash, so if you \r\nare intending to use an alternative Windows connection instead of a SQL login, ensure it contains a backslash.", "", false, "false", "", "" ], [ "AvailabilityGroup", "Specifies the name of the availability group to query for backup history.\r\nRequired parameter that identifies which AG\u0027s databases should be included in the backup history retrieval.", "", true, "false", "", "" ], [ "Database", "Specifies which databases within the availability group to include in the backup history.\r\nIf omitted, backup history for all databases in the availability group will be returned.\r\nUseful when you need backup history for specific databases rather than the entire AG.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies databases within the availability group to exclude from backup history results.\r\nUse this when you want most AG databases but need to omit specific ones like test or temporary databases.", "", false, "false", "", "" ], [ "IncludeCopyOnly", "Includes copy-only backups in the results, which are normally excluded by default.\r\nCopy-only backups don\u0027t affect the backup chain sequence and are often used for ad-hoc copies or third-party backup tools.\r\nEnable this when you need a complete view of all backup activity including copy-only operations.", "", false, "false", "False", "" ], [ "Force", "Returns detailed backup information including additional metadata fields normally hidden for readability.\r\nUse this when you need comprehensive backup details for troubleshooting or detailed analysis beyond the standard summary view.", "", false, "false", "False", "" ], [ "Since", "Filters backup history to only include backups taken after this date and time.\r\nDefaults to January 1, 1970 if not specified, effectively including all backup history.\r\nUse this to limit results to recent backups or investigate backup activity within a specific timeframe.", "", false, "false", "(Get-Date \u002701/01/1970\u0027)", "" ], [ "RecoveryFork", "Filters backup history to a specific recovery fork identified by its GUID.\r\nRecovery forks occur after point-in-time restores and create branching backup chains.\r\nUse this when investigating backup history related to a specific restore operation or recovery scenario.", "", false, "false", "", "" ], [ "Last", "Returns the most recent complete backup chain (full, differential, and log backups) needed for point-in-time recovery.\r\nThis provides the minimum set of backups required to restore each database to its most recent recoverable state.\r\nEssential for recovery planning and validating that you have all necessary backup files.", "", false, "false", "False", "" ], [ "LastFull", "Returns only the most recent full backup for each database in the availability group.\r\nUse this to quickly identify the latest full backup baseline for each database, which is the foundation for any restore operation.", "", false, "false", "False", "" ], [ "LastDiff", "Returns only the most recent differential backup for each database in the availability group.\r\nUseful for identifying the latest differential backup that can reduce restore time by applying changes since the last full backup.", "", false, "false", "False", "" ], [ "LastLog", "Returns only the most recent transaction log backup for each database in the availability group.\r\nCritical for determining the latest point-in-time recovery option and ensuring log backup chains are current.", "", false, "false", "False", "" ], [ "DeviceType", "Filters backup history by the storage device type where backups were written.\r\nCommon values include \u0027Disk\u0027 for local/network storage, \u0027URL\u0027 for Azure/S3 cloud storage, or \u0027Tape\u0027 for tape devices.\r\nUse this when you need to locate backups stored on specific media types or troubleshoot backup destinations.", "", false, "false", "", "" ], [ "Raw", "Returns individual backup file details instead of grouping striped backup files into single backup set objects.\r\nEnable this when you need to see each physical backup file separately, useful for investigating striped backups or file-level backup issues.\r\nBy default, related backup files are grouped together as logical backup sets.", "", false, "false", "False", "" ], [ "LastLsn", "Filters backup history to only include backups with Log Sequence Numbers greater than this value.\r\nUse this to find backups taken after a specific point in the transaction log, improving performance when dealing with large backup histories.\r\nCommonly used when building incremental backup chains or investigating activity after a known LSN checkpoint.", "", false, "false", "", "" ], [ "IncludeMirror", "Includes mirrored backup sets in the results, which are normally excluded for clarity.\r\nMirrored backups are identical copies written simultaneously to multiple destinations during backup operations.\r\nEnable this when you need to see all backup copies or verify mirror backup destinations.", "", false, "false", "False", "" ], [ "Type", "Filters results to specific backup types such as \u0027Full\u0027, \u0027Log\u0027, or \u0027Differential\u0027.\r\nUse this when you need to focus on particular backup types, like reviewing only transaction log backups for log shipping validation.\r\nIf not specified, all backup types are included unless using one of the Last switches.", "", false, "false", "", "Full,Log,Differential,File,Differential File,Partial Full,Partial Differential" ], [ "LsnSort", "Determines which LSN field to use for sorting when filtering with Last switches (LastFull, LastDiff, LastLog).\r\nOptions are \u0027FirstLsn\u0027 (default), \u0027DatabaseBackupLsn\u0027, or \u0027LastLsn\u0027 to control chronological ordering.\r\nUse \u0027LastLsn\u0027 when you need backups sorted by their ending checkpoint rather than starting point.", "", false, "false", "FirstLsn", "FirstLsn,DatabaseBackupLsn,LastLsn" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "AG", "HA" ], "CommandName": "Get-DbaAgDatabase", "Name": "Get-DbaAgDatabase", "Author": "Shawn Melton (@wsmelton), wsmelton.github.io", "Syntax": "Get-DbaAgDatabase [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-AvailabilityGroup] \u003cString[]\u003e] [[-Database] \u003cString[]\u003e] [[-ExcludeDatabase] \u003cString[]\u003e] [[-Pattern] \u003cString[]\u003e] [[-InputObject] \u003cAvailabilityGroup[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.AvailabilityDatabase\nReturns one AvailabilityDatabase object for each database found in the availability groups on the specified instances.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- AvailabilityGroup: Name of the availability group\r\n- LocalReplicaRole: Role of this replica (Primary or Secondary)\r\n- Name: Database name\r\n- SynchronizationState: Current synchronization state (NotSynchronizing, Synchronizing, Synchronized, Reverting, Initializing)\r\n- IsFailoverReady: Boolean indicating if the database is ready for failover\r\n- IsJoined: Boolean indicating if the database has joined the availability group\r\n- IsSuspended: Boolean indicating if data movement is suspended\nAdditional properties available (from SMO AvailabilityDatabase object):\r\n- DatabaseGuid: Unique identifier for the database\r\n- EstimatedDataLoss: Estimated data loss in seconds\r\n- EstimatedRecoveryTime: Estimated recovery time in seconds\r\n- FileStreamSendRate: Rate of FILESTREAM data being sent (bytes/sec)\r\n- GroupDatabaseId: Unique identifier for the database within the AG\r\n- ID: Internal object ID\r\n- IsAvailabilityDatabaseSuspended: Boolean indicating suspension state\r\n- IsDatabaseDiskHealthy: Boolean indicating if database disk health is good\r\n- IsDatabaseJoined: Boolean indicating database join state\r\n- IsInstanceDiskHealthy: Boolean indicating if instance disk health is good\r\n- IsInstanceHealthy: Boolean indicating overall instance health\r\n- IsPendingSecondarySuspend: Boolean indicating if secondary suspend is pending\r\n- LastCommitLsn: Last commit log sequence number\r\n- LastCommitTime: Timestamp of last committed transaction\r\n- LastHardenedLsn: Last hardened log sequence number\r\n- LastHardenedTime: Timestamp when last LSN was hardened\r\n- LastReceivedLsn: Last received log sequence number\r\n- LastReceivedTime: Timestamp when last LSN was received\r\n- LastRedoneLsn: Last redone log sequence number\r\n- LastRedoneTime: Timestamp when last LSN was redone\r\n- LastSentLsn: Last sent log sequence number\r\n- LastSentTime: Timestamp when last LSN was sent\r\n- LogSendQueue: Size of log send queue in KB\r\n- LogSendRate: Rate of log sending (bytes/sec)\r\n- LowWaterMarkForGhostCleanup: Low water mark LSN for ghost cleanup\r\n- Parent: Reference to parent AvailabilityGroup SMO object\r\n- RecoveryLsn: Recovery log sequence number\r\n- RedoQueue: Size of redo queue in KB\r\n- RedoRate: Rate of redo operations (bytes/sec)\r\n- SecondaryLagSeconds: Lag in seconds for secondary replica\r\n- State: SMO object state (Existing, Creating, Pending, etc.)\r\n- SuspendReason: Reason for suspension if database is suspended\r\n- Urn: Uniform Resource Name for the SMO object", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAgDatabase -SqlInstance sql2017a\nReturns all the databases in each availability group found on sql2017a\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgDatabase -SqlInstance sql2017a -AvailabilityGroup AG101\nReturns all the databases in the availability group AG101 on sql2017a\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaAgDatabase -SqlInstance sql2017a -ExcludeDatabase TestDB,StagingDB\nReturns all the databases in each availability group found on sql2017a, excluding TestDB and StagingDB.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaAgDatabase -SqlInstance sql2017a -Pattern \"^dbatools_\"\nReturns all databases in each availability group found on sql2017a that match the regex pattern \"^dbatools_\" (e.g., dbatools_example1, dbatools_example2)\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sqlcluster -AvailabilityGroup SharePoint | Get-DbaAgDatabase -Database Sharepoint_Config\nReturns the database Sharepoint_Config found in the availability group SharePoint on server sqlcluster", "Description": "Retrieves detailed information about databases participating in SQL Server availability groups, including their synchronization state, failover readiness, and replica-specific status. This function queries the availability group configuration from each SQL Server instance to return database-level health and status information that varies depending on whether the replica is primary or secondary.\n\nUse this command to monitor availability group database health, troubleshoot synchronization issues, verify failover readiness, or generate compliance reports showing which databases are properly synchronized across your availability group replicas. The returned data includes critical operational details like suspension status, join state, and synchronization health that help DBAs quickly identify databases requiring attention.", "Links": "https://dbatools.io/Get-DbaAgDatabase", "Synopsis": "Retrieves availability group database information and synchronization status from SQL Server instances.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "AvailabilityGroup", "Specifies which availability groups to query for database information. Accepts multiple availability group names.\r\nUse this to limit results to specific availability groups when you have multiple AGs on the same instance.", "", false, "false", "", "" ], [ "Database", "Specifies which availability group databases to return information for. Accepts multiple database names with tab completion.\r\nUse this to focus on specific databases when troubleshooting AG issues or monitoring particular applications.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies one or more databases to exclude from the results using exact name matching.\r\nUse this to filter out specific databases like test or staging environments from your results.", "", false, "false", "", "" ], [ "Pattern", "Specifies a pattern for filtering databases using regular expressions.\r\nUse this when you need to match databases by pattern, such as \"^dbatools_\" or \".*_prod$\".\r\nThis parameter supports standard .NET regular expression syntax.", "", false, "false", "", "" ], [ "InputObject", "Accepts availability group objects from Get-DbaAvailabilityGroup via pipeline input.\r\nUse this when you want to chain commands to get database details from already retrieved availability groups.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "AG", "HA", "Monitoring", "Health" ], "CommandName": "Get-DbaAgDatabaseReplicaState", "Name": "Get-DbaAgDatabaseReplicaState", "Author": "Andreas Jordan (@andreasjordan)", "Syntax": "Get-DbaAgDatabaseReplicaState [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-AvailabilityGroup] \u003cString[]\u003e] [[-Database] \u003cString[]\u003e] [[-InputObject] \u003cAvailabilityGroup[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database on each replica in the availability group. For example, a database on an AG with two replicas returns two objects - one for the primary and one for the secondary.\nProperties returned:\r\n- ComputerName: The computer name of the SQL Server instance (string)\r\n- InstanceName: The SQL Server instance name (string)\r\n- SqlInstance: The full SQL Server instance name (computer\\instance format) (string)\r\n- AvailabilityGroup: Name of the availability group (string)\r\n- PrimaryReplica: Server name of the primary replica (string)\r\n- ReplicaServerName: Server name of this replica (string)\r\n- ReplicaRole: Role of this replica - Primary or Secondary (AvailabilityReplicaRole enum)\r\n- ReplicaAvailabilityMode: Availability mode of this replica - Asynchronous or Synchronous (AvailabilityReplicaAvailabilityMode enum)\r\n- ReplicaFailoverMode: Failover mode of this replica - Automatic or Manual (AvailabilityReplicaFailoverMode enum)\r\n- ReplicaConnectionState: Connection state of this replica - Connected, Disconnected, or Failed (ReplicaConnectionState enum)\r\n- ReplicaJoinState: Join state of this replica - Joined or NotJoined (ReplicaJoinState enum)\r\n- ReplicaSynchronizationState: Rollup synchronization state for all databases on this replica (SynchronizationState enum)\r\n- DatabaseName: Name of the database (string)\r\n- SynchronizationState: Database synchronization state on this replica - Synchronized, Synchronizing, NotSynchronizing, Reverting, or Initializing (SynchronizationState enum)\r\n- IsFailoverReady: Boolean indicating if the database is ready for failover (bool)\r\n- IsJoined: Boolean indicating if the database has joined the availability group (bool)\r\n- IsSuspended: Boolean indicating if data movement is suspended for this database (bool)\r\n- SuspendReason: Reason why data movement was suspended - None, UserAction, PartnerSuspended, etc. (SuspendReason enum)\r\n- EstimatedRecoveryTime: Estimated time to recover the database (TimeSpan)\r\n- EstimatedDataLoss: Estimated amount of data loss in case of failover (TimeSpan)\r\n- SynchronizationPerformance: Synchronization performance level - NotApplicable, High, Medium, Low (SynchronizationPerformance enum)\r\n- LogSendQueueSize: Size of the unsent log queue in KB (long)\r\n- LogSendRate: Rate at which log records are being sent in KB/sec (long)\r\n- RedoQueueSize: Size of the redo queue in KB (long)\r\n- RedoRate: Rate at which redo records are being applied in KB/sec (long)\r\n- FileStreamSendRate: Rate at which FILESTREAM records are being sent in KB/sec (long)\r\n- EndOfLogLSN: Log sequence number (LSN) of the end of the log (string)\r\n- RecoveryLSN: LSN for recovery point (string)\r\n- TruncationLSN: LSN for truncation point (string)\r\n- LastCommitLSN: LSN of the last committed transaction (string)\r\n- LastCommitTime: Timestamp when the last transaction was committed (DateTime)\r\n- LastHardenedLSN: LSN that was last hardened to disk (string)\r\n- LastHardenedTime: Timestamp when the last record was hardened to disk (DateTime)\r\n- LastReceivedLSN: LSN of the last received log record (string)\r\n- LastReceivedTime: Timestamp when the last log record was received (DateTime)\r\n- LastRedoneLSN: LSN of the last redo operation (string)\r\n- LastRedoneTime: Timestamp when the last redo operation completed (DateTime)\r\n- LastSentLSN: LSN of the last sent log record (string)\r\n- LastSentTime: Timestamp when the last log record was sent (DateTime)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAgDatabaseReplicaState -SqlInstance sql2017a\nReturns database replica state information for all databases in all availability groups on sql2017a\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgDatabaseReplicaState -SqlInstance sql2017a -AvailabilityGroup AG101\nReturns database replica state information for all databases in the availability group AG101 on sql2017a\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaAgDatabaseReplicaState -SqlInstance sql2017a -AvailabilityGroup AG101 -Database AppDB\nReturns database replica state information for the AppDB database in the availability group AG101 on sql2017a\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sqlcluster -AvailabilityGroup SharePoint | Get-DbaAgDatabaseReplicaState\nReturns database replica state information for all databases in the availability group SharePoint on server sqlcluster\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sqlcluster -AvailabilityGroup SharePoint | Get-DbaAgDatabaseReplicaState -Database Sharepoint_Config\nReturns database replica state information for the Sharepoint_Config database in the availability group SharePoint on server sqlcluster", "Description": "Retrieves comprehensive health monitoring information about databases participating in SQL Server availability groups, similar to the SSMS AG Dashboard. This function returns detailed database replica state information for all replicas in the availability group.\n\nThe class Microsoft.SqlServer.Management.Smo.DatabaseReplicaState represents the runtime state of a database that\u0027s participating in an availability group. This database may be located on any of the replicas that compose the availability group.\n\nUse this command to monitor availability group health, troubleshoot synchronization issues, verify failover readiness, identify data loss risks, and generate detailed operational reports showing the state of each database on each replica in your availability groups.", "Links": "https://dbatools.io/Get-DbaAgDatabaseReplicaState", "Synopsis": "Retrieves the runtime state of databases participating in availability groups across all replicas.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "AvailabilityGroup", "Specifies which availability groups to query for database replica state information. Accepts multiple availability group names.\r\nUse this to limit results to specific availability groups when you have multiple AGs on the same instance.", "", false, "false", "", "" ], [ "Database", "Specifies which availability group databases to return replica state information for. Accepts multiple database names.\r\nUse this to focus on specific databases when troubleshooting AG issues or monitoring particular applications.", "", false, "false", "", "" ], [ "InputObject", "Accepts availability group objects from Get-DbaAvailabilityGroup via pipeline input.\r\nUse this when you want to chain commands to get database replica state details from already retrieved availability groups.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Agent", "Alert" ], "CommandName": "Get-DbaAgentAlert", "Name": "Get-DbaAgentAlert", "Author": "Klaas Vandenberghe (@PowerDBAKlaas)", "Syntax": "Get-DbaAgentAlert [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Alert] \u003cString[]\u003e] [[-ExcludeAlert] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Alert\nReturns one Alert object per SQL Agent alert found on the specified instances.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Name: Name of the alert\r\n- ID: Unique identifier of the alert in the msdb database\r\n- JobName: Name of the job that responds to this alert (if any)\r\n- AlertType: Type of alert (EventAlert, ErrorNumberAlert, etc.)\r\n- CategoryName: Category name assigned to the alert\r\n- Severity: SQL Server error severity level (0-25) that triggers this alert\r\n- MessageId: SQL Server message ID that triggers this alert (if alert is message-based)\r\n- IsEnabled: Boolean indicating if the alert is enabled\r\n- DelayBetweenResponses: Delay in seconds between repeated alert responses\r\n- LastRaised: DateTime when this alert was last triggered (dbatools custom property)\r\n- OccurrenceCount: Number of times this alert has been raised\nAdditional properties available (from SMO Alert object):\r\n- CategoryId: Unique identifier of the alert category\r\n- CreateDate: DateTime when the alert was created\r\n- DateLastModified: DateTime when the alert was last modified\r\n- DatabaseName: Name of the database this alert applies to (for database-specific alerts)\r\n- Urn: Uniform Resource Name for the SMO object\r\n- State: SMO object state (Existing, Creating, Pending, etc.)\nCustom properties added by this function:\r\n- Notifications: DataTable from EnumNotifications() containing operators notified by this alert and their notification methods (Email, Pager, NetSend)\nAll properties from the base SMO Alert object are accessible even though only default properties are displayed without using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAgentAlert -SqlInstance ServerA,ServerB\\instanceB\nReturns all SQL Agent alerts on serverA and serverB\\instanceB\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgentAlert -SqlInstance ServerA,ServerB\\instanceB -Alert MyAlert*\nReturns SQL Agent alert on serverA and serverB\\instanceB whose names match \u0027MyAlert*\u0027\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e\u0027serverA\u0027,\u0027serverB\\instanceB\u0027 | Get-DbaAgentAlert\nReturns all SQL Agent alerts on serverA and serverB\\instanceB", "Description": "Retrieves alert configurations from SQL Server Agent, including alert names, types, severity levels, message IDs, and notification settings. Use this to audit alert configurations across multiple servers, troubleshoot missing or misconfigured alerts, or gather information for compliance reporting. The function returns detailed alert properties like enabled status, last occurrence dates, and response delays, making it essential for monitoring your alerting infrastructure and ensuring critical system events are properly configured for notification.", "Links": "https://dbatools.io/Get-DbaAgentAlert", "Synopsis": "Retrieves SQL Server Agent alert configurations from one or more instances", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Alert", "Specifies the specific SQL Agent alert names to retrieve from the target instances. Accepts wildcards for pattern matching.\r\nUse this when you need to check specific alerts like \u0027Severity 016*\u0027 or \u0027DB Mail*\u0027 instead of retrieving all alerts on the server.", "", false, "false", "", "" ], [ "ExcludeAlert", "Specifies SQL Agent alert names to exclude from the results. Accepts wildcards for pattern matching.\r\nUse this to filter out unwanted alerts when auditing or when you need to focus on specific alert categories without built-in system alerts.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Agent", "Alert", "AlertCategory" ], "CommandName": "Get-DbaAgentAlertCategory", "Name": "Get-DbaAgentAlertCategory", "Author": "Patrick Flynn (@sqllensman)", "Syntax": "Get-DbaAgentAlertCategory [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Category] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Agent.AlertCategory\nReturns one AlertCategory object per alert category on the SQL Server instance. Custom properties are added to provide connection context and alert count information.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Name: The name of the alert category\r\n- ID: The unique identifier of the alert category\r\n- AlertCount: The number of alerts currently assigned to this category (integer)\nAdditional properties available (from SMO AlertCategory object):\r\n- Parent: Reference to the parent JobServer object\r\n- Urn: The Unified Resource Name that uniquely identifies the alert category\r\n- State: The state of the object (Existing, Creating, Dropping, Pending)\nAll properties from the base SMO AlertCategory object are accessible by using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAgentAlertCategory -SqlInstance sql1\nReturn all the agent alert categories.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgentAlertCategory -SqlInstance sql1 -Category \u0027Severity Alert\u0027\nReturn all the agent alert categories that have the name \u0027Severity Alert\u0027.", "Description": "Retrieves all SQL Server Agent alert categories from the target instances, showing how alerts are organized and grouped. Categories help DBAs manage alerts logically by grouping related notifications (such as severity-based alerts, database maintenance alerts, or custom business alerts). The function also returns a count of how many alerts are currently assigned to each category, making it useful for understanding your alerting structure and identifying unused or heavily-used categories.", "Links": "https://dbatools.io/Get-DbaAgentAlertCategory", "Synopsis": "Retrieves SQL Server Agent alert categories and their associated alert counts", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Category", "Specifies one or more alert category names to return from the SQL Server Agent. Accepts multiple values and wildcards are not supported.\r\nUse this when you need to examine specific alert categories rather than retrieving all categories on the instance.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Agent", "Job" ], "CommandName": "Get-DbaAgentJob", "Name": "Get-DbaAgentJob", "Author": "Garry Bargsley (@gbargsley), blog.garrybargsley.com", "Syntax": "Get-DbaAgentJob [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Job] \u003cString[]\u003e] [[-ExcludeJob] \u003cString[]\u003e] [[-Database] \u003cString[]\u003e] [[-Category] \u003cString[]\u003e] [[-ExcludeCategory] \u003cString[]\u003e] [-ExcludeDisabledJobs] [-IncludeExecution] [[-Type] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Job\nReturns one SQL Agent Job object per job matching the specified criteria. Each object represents a SQL Server Agent job with its configuration and execution status.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The name of the SQL Server computer\r\n- InstanceName: The name of the SQL Server instance\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Name: The name of the SQL Agent job\r\n- Category: The category assigned to the job\r\n- OwnerLoginName: The login that owns the job\r\n- CurrentRunStatus: Current execution status (Idle, Running, etc.)\r\n- CurrentRunRetryAttempt: Number of retry attempts for the current execution\r\n- Enabled: Boolean indicating if the job is enabled (True/False)\r\n- LastRunDate: DateTime of the last job execution\r\n- LastRunOutcome: Outcome of the last execution (Succeeded, Failed, Cancelled, Retried, etc.)\r\n- HasSchedule: Boolean indicating if the job has an associated schedule\r\n- OperatorToEmail: Email address of the operator to notify on completion\r\n- CreateDate: DateTime when the job was created\r\n- StartDate: DateTime when the job started executing (only when -IncludeExecution is specified)\nAdditional properties available from the SMO Job object (accessible via Select-Object *):\r\n- JobId: Unique identifier (GUID) for the job\r\n- JobType: Type of job (Local or MultiServer)\r\n- JobSteps: Collection of job steps belonging to this job\r\n- CategoryID: Internal ID of the job category\r\n- Description: Job description/notes\r\n- IsSystemObject: Boolean indicating if this is a system object\nNote: When -IncludeExecution is specified, the StartDate property is added to the default display properties showing when the currently executing job started.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAgentJob -SqlInstance localhost\nReturns all SQL Agent Jobs on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgentJob -SqlInstance localhost, sql2016\nReturns all SQl Agent Jobs for the local and sql2016 SQL Server instances\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaAgentJob -SqlInstance localhost -Job BackupData, BackupDiff\nReturns all SQL Agent Jobs named BackupData and BackupDiff from the local SQL Server instance.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaAgentJob -SqlInstance localhost -ExcludeJob BackupDiff\nReturns all SQl Agent Jobs for the local SQL Server instances, except the BackupDiff Job.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaAgentJob -SqlInstance localhost -ExcludeDisabledJobs\nReturns all SQl Agent Jobs for the local SQL Server instances, excluding the disabled jobs.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e$servers | Get-DbaAgentJob | Out-GridView -PassThru | Start-DbaAgentJob -WhatIf\nFind all of your Jobs from SQL Server instances in the $servers collection, select the jobs you want to start then see jobs would start if you ran Start-DbaAgentJob\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eGet-DbaAgentJob -SqlInstance sqlserver2014a | Where-Object Category -eq \"Report Server\" | Export-DbaScript -Path \"C:\\temp\\sqlserver2014a_SSRSJobs.sql\"\nExports all SSRS jobs from SQL instance sqlserver2014a to a file.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eGet-DbaAgentJob -SqlInstance sqlserver2014a -Database msdb\nFinds all jobs on sqlserver2014a that T-SQL job steps associated with msdb database", "Description": "Retrieves detailed information about SQL Server Agent jobs including their configuration, status, schedules, and execution history. This function connects to SQL instances and queries the msdb database to return job properties like owner, category, last run outcome, and current execution status. Use this to monitor job health across your environment, audit job configurations before deployments, or identify jobs associated with specific databases for maintenance planning.", "Links": "https://dbatools.io/Get-DbaAgentJob", "Synopsis": "Retrieves SQL Server Agent job details and execution status from one or more instances.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Job", "Specifies specific SQL Agent job names to retrieve. Accepts an array of job names for targeting multiple jobs.\r\nUse this when you need to check status or configuration of specific jobs instead of retrieving all jobs on the instance.", "", false, "false", "", "" ], [ "ExcludeJob", "Excludes specific SQL Agent job names from the results. Accepts an array of job names to skip.\r\nUseful when you want most jobs except for specific ones like test jobs or jobs you\u0027re not responsible for managing.", "", false, "false", "", "" ], [ "Database", "Filters jobs to only those containing T-SQL job steps that target specific databases.\r\nEssential for database-specific maintenance planning or identifying which jobs will be affected by database operations like restores or migrations.", "", false, "false", "", "" ], [ "Category", "Filters jobs by their assigned category such as \u0027Database Maintenance\u0027, \u0027Report Server\u0027, or custom categories.\r\nHelpful for organizing job management tasks by functional area or finding jobs related to specific SQL Server features.", "", false, "false", "", "" ], [ "ExcludeCategory", "Excludes jobs from specific categories from the results. Accepts an array of category names.\r\nUse this to filter out jobs you don\u0027t manage, such as third-party application jobs or SSRS jobs when focusing on database maintenance.", "", false, "false", "", "" ], [ "ExcludeDisabledJobs", "Excludes disabled SQL Agent jobs from the results, showing only enabled jobs.\r\nUse this when focusing on active job monitoring or troubleshooting since disabled jobs won\u0027t execute.", "", false, "false", "False", "" ], [ "IncludeExecution", "Adds execution start date information for currently running jobs to the output.\r\nEssential for troubleshooting long-running jobs or monitoring active job execution in real-time.", "", false, "false", "False", "" ], [ "Type", "Specifies whether to return Local jobs, MultiServer jobs, or both. Local jobs run only on the current instance while MultiServer jobs are managed centrally.\r\nUse \u0027Local\u0027 when managing single-instance environments or \u0027MultiServer\u0027 when working with SQL Server multi-server administration setups.", "", false, "false", "@(\"MultiServer\", \"Local\")", "MultiServer,Local" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Agent", "Job", "Category" ], "CommandName": "Get-DbaAgentJobCategory", "Name": "Get-DbaAgentJobCategory", "Author": "Sander Stad (@sqlstad), sqlstad.nl", "Syntax": "Get-DbaAgentJobCategory [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Category] \u003cString[]\u003e] [[-CategoryType] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Agent.JobCategory\nReturns one JobCategory object per job category on the SQL Server instance. Custom properties are added to provide connection context and job count information.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Name: The name of the job category\r\n- ID: The unique identifier of the job category\r\n- CategoryType: The type of category (LocalJob, MultiServerJob, or None)\r\n- JobCount: The number of jobs currently assigned to this category (integer)\nAdditional properties available (from SMO JobCategory object):\r\n- Parent: Reference to the parent JobServer object\r\n- Urn: The Unified Resource Name that uniquely identifies the job category\r\n- State: The state of the object (Existing, Creating, Dropping, Pending)\nAll properties from the base SMO JobCategory object are accessible by using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAgentJobCategory -SqlInstance sql1\nReturn all the job categories.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgentJobCategory -SqlInstance sql1 -Category \u0027Log Shipping\u0027\nReturn all the job categories that have the name \u0027Log Shipping\u0027.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaAgentJobCategory -SqlInstance sstad-pc -CategoryType MultiServerJob\nReturn all the job categories that have a type MultiServerJob.", "Description": "Returns SQL Server Agent job categories from one or more instances, showing how many jobs are assigned to each category. Job categories help organize and group related SQL Agent jobs for easier management and reporting. This function retrieves both built-in categories (like Database Maintenance, Log Shipping) and custom categories created by DBAs. You can filter by specific category names or types (LocalJob for single-instance jobs, MultiServerJob for MSX/TSX environments, or None for uncategorized jobs) to focus on particular organizational schemes.", "Links": "https://dbatools.io/Get-DbaAgentJobCategory", "Synopsis": "Retrieves SQL Server Agent job categories with usage counts and filtering options", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Category", "Specifies one or more job category names to return, filtering the results to only those categories. Accepts multiple values and supports built-in categories like \u0027Database Maintenance\u0027, \u0027Log \r\nShipping\u0027, \u0027Replication\u0027, and custom categories created by DBAs.\r\nUse this when you need to check specific categories for job assignments or verify custom organizational schemes. If not specified, all job categories are returned.", "", false, "false", "", "" ], [ "CategoryType", "Filters job categories by their deployment type: \u0027LocalJob\u0027 for single-instance jobs, \u0027MultiServerJob\u0027 for Master Server/Target Server (MSX/TSX) environments, or \u0027None\u0027 for uncategorized jobs.\r\nUse this in MSX/TSX configurations to distinguish between locally managed jobs and multi-server jobs, or to identify jobs that haven\u0027t been assigned a proper category. If not specified, all category \r\ntypes are returned.", "", false, "false", "", "LocalJob,MultiServerJob,None" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Agent", "Job" ], "CommandName": "Get-DbaAgentJobHistory", "Name": "Get-DbaAgentJobHistory", "Author": "Klaas Vandenberghe (@PowerDbaKlaas) | Simone Bizzotto (@niphold)", "Syntax": "Get-DbaAgentJobHistory [-SqlCredential \u003cPSCredential\u003e] [-Job \u003cObject[]\u003e] [-ExcludeJob \u003cObject[]\u003e] [-StartDate \u003cDateTime\u003e] [-EndDate \u003cDateTime\u003e] [-OutcomeType {Failed | Succeeded | Retry | Cancelled | InProgress | Unknown}] [-ExcludeJobSteps] [-WithOutputFile] [-EnableException] [\u003cCommonParameters\u003e]\nGet-DbaAgentJobHistory -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Job \u003cObject[]\u003e] [-ExcludeJob \u003cObject[]\u003e] [-StartDate \u003cDateTime\u003e] [-EndDate \u003cDateTime\u003e] [-OutcomeType {Failed | Succeeded | Retry | Cancelled | InProgress | Unknown}] [-ExcludeJobSteps] [-WithOutputFile] [-EnableException] [\u003cCommonParameters\u003e]\nGet-DbaAgentJobHistory [-SqlCredential \u003cPSCredential\u003e] [-Job \u003cObject[]\u003e] [-ExcludeJob \u003cObject[]\u003e] [-StartDate \u003cDateTime\u003e] [-EndDate \u003cDateTime\u003e] [-OutcomeType {Failed | Succeeded | Retry | Cancelled | InProgress | Unknown}] [-ExcludeJobSteps] [-WithOutputFile] -JobCollection \u003cJob\u003e [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Agent.JobExecutionHistory\nReturns one execution history record per job execution, with calculated fields added for easier interpretation. Each record represents either a job-level summary (StepID = 0) or individual step \r\nexecution within a job.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Job: Name of the SQL Server Agent job (aliased from JobName property)\r\n- StepName: Name of the job step that executed\r\n- RunDate: DateTime when the execution started\r\n- StartDate: DateTime when the execution started (formatted as DbaDatTime)\r\n- EndDate: DateTime when the execution completed, calculated from RunDate plus duration\r\n- Duration: PrettyTimeSpan formatted duration (e.g., \"00:05:23\") calculated from RunDuration\r\n- Status: Human-readable execution status (Failed, Succeeded, Retry, or Canceled)\r\n- OperatorEmailed: Boolean indicating if an operator was emailed about this execution\r\n- Message: Job step execution message or failure reason\nWhen -WithOutputFile is specified, additional properties are included:\r\n- OutputFileName: Resolved output file path with SQL Agent token placeholders replaced\r\n- RemoteOutputFileName: UNC path to the output file on the remote server\nAll additional SMO JobExecutionHistory properties are accessible (not displayed by default):\r\n- JobID: Unique identifier for the job\r\n- StepID: Step number (0 = job level, \u003e0 = step level)\r\n- Retries: Number of retries for this execution\r\n- RunDuration: Duration in integer format (hhmmss)\nUse Select-Object * to view all available properties.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAgentJobHistory -SqlInstance localhost\nReturns all SQL Agent Job execution results on the local default SQL Server instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgentJobHistory -SqlInstance localhost, sql2016\nReturns all SQL Agent Job execution results for the local and sql2016 SQL Server instances.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e\u0027sql1\u0027,\u0027sql2\\Inst2K17\u0027 | Get-DbaAgentJobHistory\nReturns all SQL Agent Job execution results for sql1 and sql2\\Inst2K17.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaAgentJobHistory -SqlInstance sql2\\Inst2K17 | Select-Object *\nReturns all properties for all SQl Agent Job execution results on sql2\\Inst2K17.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaAgentJobHistory -SqlInstance sql2\\Inst2K17 -Job \u0027Output File Cleanup\u0027\nReturns all properties for all SQl Agent Job execution results of the \u0027Output File Cleanup\u0027 job on sql2\\Inst2K17.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaAgentJobHistory -SqlInstance sql2\\Inst2K17 -Job \u0027Output File Cleanup\u0027 -WithOutputFile\nReturns all properties for all SQl Agent Job execution results of the \u0027Output File Cleanup\u0027 job on sql2\\Inst2K17,\r\nwith additional properties that show the output filename path\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eGet-DbaAgentJobHistory -SqlInstance sql2\\Inst2K17 -ExcludeJobSteps\nReturns the SQL Agent Job execution results for the whole jobs on sql2\\Inst2K17, leaving out job step execution results.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eGet-DbaAgentJobHistory -SqlInstance sql2\\Inst2K17 -StartDate \u00272017-05-22\u0027 -EndDate \u00272017-05-23 12:30:00\u0027\nReturns the SQL Agent Job execution results between 2017/05/22 00:00:00 and 2017/05/23 12:30:00 on sql2\\Inst2K17.\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003eGet-DbaAgentJob -SqlInstance sql2016 | Where-Object Name -Match backup | Get-DbaAgentJobHistory\nGets all jobs with the name that match the regex pattern \"backup\" and then gets the job history from those. You can also use -Like *backup* in this example.\n-------------------------- EXAMPLE 10 --------------------------\nPS C:\\\u003eGet-DbaAgentJobHistory -SqlInstance sql2016 -OutcomeType Failed\nReturns only the failed SQL Agent Job execution results for the sql2016 SQL Server instance.", "Description": "Get-DbaAgentJobHistory queries the msdb database to retrieve detailed execution records for SQL Server Agent jobs, helping you troubleshoot failures, monitor performance trends, and generate compliance reports. This function accesses the same historical data you\u0027d find in SQL Server Management Studio\u0027s Job Activity Monitor, but with powerful filtering and output options.\n\nThe function is essential when investigating why jobs failed, analyzing execution patterns over time, or preparing audit documentation. You can filter results by specific jobs, date ranges, or outcome types (failed, succeeded, retry, etc.), and optionally include job step details or just summary-level information.\n\nResults include calculated fields like duration, formatted start/end dates, and readable status descriptions. When used with -WithOutputFile, it resolves SQL Agent token placeholders in output file paths, making it easier to locate job logs for further investigation.\n\nHistorical data availability depends on your SQL Agent history cleanup settings - older executions may have been purged based on your retention configuration.\n\nhttps://msdn.microsoft.com/en-us/library/ms201680.aspx\nhttps://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.agent.jobhistoryfilter(v=sql.120).aspx", "Links": "https://dbatools.io/Get-DbaAgentJobHistory", "Synopsis": "Retrieves SQL Server Agent job execution history from msdb database for troubleshooting and compliance reporting.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Job", "Specifies specific SQL Agent jobs to retrieve history for by name. Accepts wildcards and arrays for multiple jobs.\r\nUse this when investigating specific job failures or monitoring particular maintenance routines instead of reviewing all job history.", "", false, "false", "", "" ], [ "ExcludeJob", "Excludes specified jobs from the history results by name. Accepts arrays for multiple job exclusions.\r\nUseful when you want to review most jobs but skip noisy or less critical ones like frequent maintenance jobs.", "", false, "false", "", "" ], [ "StartDate", "Sets the earliest date and time for job history records to include. Defaults to 1900-01-01 to include all available history.\r\nSpecify this when investigating issues within a specific timeframe or when older history isn\u0027t relevant to your troubleshooting.", "", false, "false", "1900-01-01", "" ], [ "EndDate", "Sets the latest date and time for job history records to include. Defaults to current date and time.\r\nUse this with StartDate to focus on a specific time window when troubleshooting incidents or analyzing patterns during maintenance windows.", "", false, "false", "$(Get-Date)", "" ], [ "OutcomeType", "Filters job history to only show executions with a specific completion result. Valid values are Failed, Succeeded, Retry, Cancelled, InProgress, Unknown.\r\nMost commonly used with \u0027Failed\u0027 when troubleshooting job failures or \u0027Succeeded\u0027 when verifying successful completion patterns.", "", false, "false", "", "Failed,Succeeded,Retry,Cancelled,InProgress,Unknown" ], [ "ExcludeJobSteps", "Returns only job-level execution summaries, excluding individual step details. Shows overall job success/failure without step-by-step breakdown.\r\nUse this when you need high-level job completion status for reporting or when step details aren\u0027t needed for your analysis.", "", false, "false", "False", "" ], [ "WithOutputFile", "Includes resolved output file paths for job steps that write to files. Automatically resolves SQL Agent token placeholders like $(SQLLOGDIR) to actual paths.\r\nEssential when you need to locate and review job output files for troubleshooting failures or verifying job step results.", "", false, "false", "False", "" ], [ "JobCollection", "Accepts an array of SQL Server Management Objects (SMO) job objects instead of job names. Enables pipeline input from Get-DbaAgentJob.\r\nUse this when you need to filter jobs by complex criteria first, then get their history, such as jobs matching specific patterns or properties.", "", true, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Agent", "Job" ], "CommandName": "Get-DbaAgentJobOutputFile", "Name": "Get-DbaAgentJobOutputFile", "Author": "Rob Sewell (sqldbawithabeard.com) | Simone Bizzotto (@niphlod)", "Syntax": "Get-DbaAgentJobOutputFile [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Job \u003cObject[]\u003e] [-ExcludeJob \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per job step that has an output file configured. When a job step has no output file configured, it is not returned (though a verbose message is logged when -Verbose is used).\nDefault display properties:\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name (service name)\r\n- SqlInstance: The full SQL Server instance name (ComputerName\\InstanceName format)\r\n- Job: The name of the SQL Agent job containing this step\r\n- JobStep: The name of the job step\r\n- OutputFileName: The local file path where this job step writes its output\r\n- RemoteOutputFileName: The UNC (Universal Naming Convention) path for accessing the output file from remote systems\nAdditional properties available:\r\n- StepId: The numeric identifier of this job step within the job (hidden from default display)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAgentJobOutputFile -SqlInstance SERVERNAME -Job \u0027The Agent Job\u0027\nThis will return the configured paths to the output files for each of the job step of the The Agent Job Job\r\non the SERVERNAME instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgentJobOutputFile -SqlInstance SERVERNAME\nThis will return the configured paths to the output files for each of the job step of all the Agent Jobs\r\non the SERVERNAME instance\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaAgentJobOutputFile -SqlInstance SERVERNAME,SERVERNAME2 -Job \u0027The Agent Job\u0027\nThis will return the configured paths to the output files for each of the job step of the The Agent Job Job\r\non the SERVERNAME instance and SERVERNAME2\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaAgentJobOutputFile -SqlInstance SERVERNAME | Out-GridView\nThis will return the configured paths to the output files for each of the job step of all the Agent Jobs\r\non the SERVERNAME instance and Pipe them to Out-GridView\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaAgentJobOutputFile -SqlInstance SERVERNAME -Verbose\nThis will return the configured paths to the output files for each of the job step of all the Agent Jobs\r\non the SERVERNAME instance and also show the job steps without an output file", "Description": "This function returns the file paths where SQL Agent job steps write their output logs. When troubleshooting failed jobs or reviewing execution history, DBAs often need to locate these output files to examine detailed error messages and execution details. The function returns both the local file path and the UNC path for remote access, but only displays job steps that have an output file configured.", "Links": "https://dbatools.io/Get-DbaAgentJobOutputFile", "Synopsis": "Retrieves output file paths configured for SQL Agent job steps", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.", "", true, "true (ByValue, ByPropertyName)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance. be it Windows or SQL Server. Windows users are determined by the existence of a backslash, so if you are intending to use an alternative Windows \r\nconnection instead of a SQL login, ensure it contains a backslash.", "", false, "true (ByPropertyName)", "", "" ], [ "Job", "Specifies specific SQL Agent jobs to examine for output file configurations. Accepts job names as strings and supports multiple values.\r\nUse this when you need to check output file paths for specific jobs rather than scanning all jobs on the instance.", "", false, "false", "", "" ], [ "ExcludeJob", "Specifies SQL Agent jobs to exclude from the output file search. Accepts job names as strings and supports multiple values.\r\nUse this when you want to scan most jobs but skip specific ones, such as excluding system maintenance jobs or jobs you know don\u0027t use output files.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Agent", "Job" ], "CommandName": "Get-DbaAgentJobStep", "Name": "Get-DbaAgentJobStep", "Author": "Klaas Vandenberghe (@PowerDbaKlaas), powerdba.eu", "Syntax": "Get-DbaAgentJobStep [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Job] \u003cString[]\u003e] [[-ExcludeJob] \u003cString[]\u003e] [[-InputObject] \u003cJob[]\u003e] [-ExcludeDisabledJobs] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Agent.JobStep\nReturns one SQL Agent Job Step object per step within each specified job. Each object represents a discrete step within a SQL Server Agent job with its configuration and execution details.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The name of the SQL Server computer where the step is located\r\n- InstanceName: The name of the SQL Server instance\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- AgentJob: The name of the parent SQL Agent job containing this step\r\n- Name: The name of the job step\r\n- SubSystem: The subsystem type for the step (TransactSql, PowerShell, CmdExec, AnalysisCommand, AnalysisQuery, Ssis, etc.)\r\n- LastRunDate: DateTime of the last execution of this step\r\n- LastRunOutcome: Outcome of the last execution (Succeeded, Failed, Retry, Cancelled, Unknown, etc.)\r\n- State: Current state of the step (Enabled, Disabled, etc.)\nAdditional properties available from the SMO JobStep object (accessible via Select-Object *):\r\n- ID: Internal step ID number\r\n- CreateDate: DateTime when the step was created\r\n- DateLastModified: DateTime when the step was last modified\r\n- Command: The command or script to execute for this step\r\n- CommandExecutionSuccessCode: Exit code indicating success (0 for success by default)\r\n- DatabaseName: Database context for the step execution\r\n- DatabaseUserName: User context for step execution\r\n- Description: Step description/notes\r\n- IncludeStepOutput: Boolean indicating if step output is included in job history\r\n- IsLastStep: Boolean indicating if this is the last step in the job\r\n- LogToTable: Boolean indicating if output is logged to a table\r\n- OutputFileName: File path for step output logging\r\n- ProxyID: ID of the proxy account used for this step\r\n- RetryAttempts: Number of retry attempts if the step fails\r\n- RetryInterval: Interval in minutes between retry attempts\nNote: The ComputerName, InstanceName, SqlInstance, and AgentJob properties are added by the function and are not native SMO properties.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAgentJobStep -SqlInstance localhost\nReturns all SQL Agent Job Steps on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgentJobStep -SqlInstance localhost, sql2016\nReturns all SQL Agent Job Steps for the local and sql2016 SQL Server instances\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaAgentJobStep -SqlInstance localhost -Job BackupData, BackupDiff\nReturns all SQL Agent Job Steps for the jobs named BackupData and BackupDiff from the local SQL Server instance.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaAgentJobStep -SqlInstance localhost -ExcludeJob BackupDiff\nReturns all SQL Agent Job Steps for the local SQL Server instances, except for the BackupDiff Job.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaAgentJobStep -SqlInstance localhost -ExcludeDisabledJobs\nReturns all SQL Agent Job Steps for the local SQL Server instances, excluding the disabled jobs.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e$servers | Get-DbaAgentJobStep\nFind all of your Job Steps from SQL Server instances in the $servers collection", "Description": "Collects comprehensive details about SQL Agent job steps across one or more SQL Server instances. Returns information about each step\u0027s subsystem type, last execution date, outcome, and current state, which is essential for monitoring job performance and troubleshooting failed automation tasks. You can filter results by specific jobs, exclude disabled jobs, or process job objects from Get-DbaAgentJob to focus on particular maintenance routines or scheduled processes.", "Links": "https://dbatools.io/Get-DbaAgentJobStep", "Synopsis": "Retrieves detailed SQL Agent job step information including execution status and configuration from SQL Server instances.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.", "", false, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Job", "Specifies which SQL Agent jobs to include by name when retrieving job steps. Accepts wildcards for pattern matching.\r\nUse this when you need to examine steps for specific jobs like backup routines or maintenance tasks instead of processing all jobs on the instance.", "", false, "false", "", "" ], [ "ExcludeJob", "Specifies which SQL Agent jobs to exclude by name when retrieving job steps. Accepts wildcards for pattern matching.\r\nUse this when you want to review most jobs but skip certain ones like test jobs or jobs that generate excessive output.", "", false, "false", "", "" ], [ "InputObject", "Accepts SQL Agent job objects from the pipeline, typically from Get-DbaAgentJob output.\r\nUse this when you want to process job steps for a pre-filtered set of jobs or when building complex pipelines that combine job filtering with step analysis.", "", false, "true (ByValue)", "", "" ], [ "ExcludeDisabledJobs", "Filters out disabled SQL Agent jobs from the results, showing only currently active jobs.\r\nUse this when troubleshooting production issues or monitoring active automation to avoid reviewing steps from jobs that aren\u0027t currently running.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": "Agent", "CommandName": "Get-DbaAgentLog", "Name": "Get-DbaAgentLog", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaAgentLog [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-LogNumber] \u003cInt32[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.LogFileEntry\nReturns one LogFileEntry object per log entry found. If multiple log numbers are specified, all entries from all requested log files are returned.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- LogDate: The date and time when the log entry was created (DateTime)\r\n- ProcessInfo: The process ID or source component that created the entry (typically spid or component name)\r\n- Text: The full text content of the log entry message\nAdditional properties available (from SMO LogFileEntry object):\r\n- Id: Unique identifier for the log entry\nAll properties from the base SMO object are accessible even though only default properties are displayed without using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAgentLog -SqlInstance sql01\\sharepoint\nReturns the entire error log for the SQL Agent on sql01\\sharepoint\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgentLog -SqlInstance sql01\\sharepoint -LogNumber 3, 6\nReturns log numbers 3 and 6 for the SQL Agent on sql01\\sharepoint\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$servers = \"sql2014\",\"sql2016\", \"sqlcluster\\sharepoint\"\nPS C:\\\u003e $servers | Get-DbaAgentLog -LogNumber 0\nReturns the most recent SQL Agent error logs for \"sql2014\",\"sql2016\" and \"sqlcluster\\sharepoint\"", "Description": "Retrieves SQL Server Agent error log entries from the target instance, providing detailed information about agent service activity, job failures, and system events. This function accesses the agent\u0027s historical error logs (numbered 0-9, where 0 is the current log) so you don\u0027t have to manually navigate through SQL Server Management Studio or query system views. Essential for troubleshooting job failures, monitoring agent service health, and compliance auditing of automated processes.", "Links": "https://dbatools.io/Get-DbaAgentLog", "Synopsis": "Retrieves SQL Server Agent error log entries for troubleshooting and monitoring", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.", "", false, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "LogNumber", "Specifies which numbered agent error log files to retrieve (0-9). Log 0 contains the most recent entries, while higher numbers contain older historical logs that get cycled as new logs are created.\r\nUse this when you need to examine historical agent activity or troubleshoot issues that occurred days or weeks ago, rather than just current entries.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Agent", "Operator" ], "CommandName": "Get-DbaAgentOperator", "Name": "Get-DbaAgentOperator", "Author": "Klaas Vandenberghe (@PowerDBAKlaas)", "Syntax": "Get-DbaAgentOperator [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Operator] \u003cObject[]\u003e] [[-ExcludeOperator] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Operator\nReturns one Operator object per SQL Agent operator found on the SQL Server instance. Each object represents an operator configured to receive notifications through email, pager, or net send.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name where the SQL Server instance is running\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance format)\r\n- Name: The operator name\r\n- ID: The unique ID of the operator in SQL Agent\r\n- IsEnabled: Boolean indicating whether the operator is enabled to receive notifications\r\n- EmailAddress: Email address configured for the operator\r\n- LastEmail: DateTime when the operator last received an email notification\nAdditional properties added by this command:\r\n- RelatedJobs: Array of job objects (Microsoft.SqlServer.Management.Smo.Job) that notify this operator via email, net send, or pager\r\n- RelatedAlerts: Array of alert names (strings) for which this operator is configured to receive notifications\r\n- AlertLastEmail: DateTime when the operator last received notification from any alert\r\n- Enabled: Boolean indicating the operator\u0027s enabled status (same as IsEnabled in default view)\r\n- LastEmailDate: DateTime of last email notification (raw SMO property)\nOther SMO properties available (select with Select-Object *):\r\n- FullyQualifiedName: Fully qualified name of the operator\r\n- NetSendAddress: Net send address configured for the operator\r\n- PagerAddress: Pager address configured for the operator\r\n- PagerDayFridayEnd: End time for Friday pager notifications\r\n- PagerDayFridayStart: Start time for Friday pager notifications\r\n- PagerDayMondayEnd: End time for Monday pager notifications\r\n- PagerDayMondayStart: Start time for Monday pager notifications\r\n- PagerDaySaturdayEnd: End time for Saturday pager notifications\r\n- PagerDaySaturdayStart: Start time for Saturday pager notifications\r\n- PagerDaySundayEnd: End time for Sunday pager notifications\r\n- PagerDaySundayStart: Start time for Sunday pager notifications\r\n- PagerDayThursdayEnd: End time for Thursday pager notifications\r\n- PagerDayThursdayStart: Start time for Thursday pager notifications\r\n- PagerDayTuesdayEnd: End time for Tuesday pager notifications\r\n- PagerDayTuesdayStart: Start time for Tuesday pager notifications\r\n- PagerDayWednesdayEnd: End time for Wednesday pager notifications\r\n- PagerDayWednesdayStart: Start time for Wednesday pager notifications\r\n- SaturdayPagerStartTime: Saturday pager start time\r\n- SaturdayPagerEndTime: Saturday pager end time\r\n- State: Current state of the SMO object", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAgentOperator -SqlInstance ServerA,ServerB\\instanceB\nReturns any SQL Agent operators on serverA and serverB\\instanceB\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027ServerA\u0027,\u0027ServerB\\instanceB\u0027 | Get-DbaAgentOperator\nReturns all SQL Agent operators on serverA and serverB\\instanceB\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaAgentOperator -SqlInstance ServerA -Operator Dba1,Dba2\nReturns only the SQL Agent Operators Dba1 and Dba2 on ServerA.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaAgentOperator -SqlInstance ServerA,ServerB -ExcludeOperator Dba3\nReturns all the SQL Agent operators on ServerA and ServerB, except the Dba3 operator.", "Description": "Retrieves detailed information about SQL Server Agent operators, including email addresses, enabled status, and relationships to jobs and alerts that notify them. Essential for auditing notification configurations, troubleshooting alert delivery issues, and maintaining disaster recovery contact lists. Shows which jobs notify each operator and tracks the last time each operator received email notifications, helping DBAs verify their monitoring and alerting infrastructure is properly configured.", "Links": "https://dbatools.io/Get-DbaAgentOperator", "Synopsis": "Retrieves SQL Server Agent operators with their notification settings and related jobs and alerts.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Operator", "Specifies which SQL Agent operators to retrieve by name. Accepts an array of operator names for targeting specific notification contacts.\r\nUse this when you need to check configuration or troubleshoot notification issues for particular operators instead of reviewing all operators on the instance.", "", false, "false", "", "" ], [ "ExcludeOperator", "Excludes specified SQL Agent operators from the results by name. Useful for filtering out test operators or disabled contacts during audits.\r\nCommonly used when reviewing active notification configurations while ignoring legacy or temporary operator accounts.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Agent", "Proxy" ], "CommandName": "Get-DbaAgentProxy", "Name": "Get-DbaAgentProxy", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaAgentProxy [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Proxy] \u003cString[]\u003e] [[-ExcludeProxy] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Agent.ProxyAccount\nReturns one ProxyAccount object per proxy account found on the target instance(s).\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- InstanceName: The SQL Server instance name (service name)\r\n- Name: The name of the proxy account\r\n- ID: Unique identifier for the proxy account\r\n- CredentialID: ID of the credential associated with this proxy\r\n- CredentialIdentity: The Windows account identity of the associated credential\r\n- CredentialName: The name of the credential used by this proxy\r\n- Description: Description text for the proxy account\r\n- IsEnabled: Boolean indicating if the proxy is enabled and available for use\nAdditional properties available (from SMO ProxyAccount object):\r\n- State: SMO object state (Existing, Creating, Pending, etc.)\r\n- Urn: Uniform Resource Name for the SQL Server object\r\n- Parent: Reference to the parent JobServer object\nAll properties from the base SMO object are accessible via Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAgentProxy -SqlInstance ServerA,ServerB\\instanceB\nReturns all SQL Agent proxies on serverA and serverB\\instanceB\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027serverA\u0027,\u0027serverB\\instanceB\u0027 | Get-DbaAgentProxy\nReturns all SQL Agent proxies on serverA and serverB\\instanceB", "Description": "Retrieves SQL Server Agent proxy accounts which allow job steps to execute under different security contexts than the SQL Agent service account.\nThis function is essential for security auditing, compliance reporting, and troubleshooting job step execution permissions.\nReturns detailed information including proxy names, associated credentials, descriptions, and enabled status across multiple SQL Server instances.", "Links": "https://dbatools.io/Get-DbaAgentProxy", "Synopsis": "Retrieves SQL Server Agent proxy accounts and their associated credentials from target instances.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Proxy", "Specifies which SQL Agent proxy accounts to retrieve by name. Supports wildcards for pattern matching.\r\nUse this to filter results when you only need specific proxy accounts instead of all proxies on the instance.\r\nCommon when auditing specific service accounts or troubleshooting particular job step failures.", "", false, "false", "", "" ], [ "ExcludeProxy", "Specifies which SQL Agent proxy accounts to exclude from results by name. Supports wildcards for pattern matching.\r\nUseful when you want to review all proxies except certain ones, such as excluding system or test proxies from security audits.\r\nCan be combined with the Proxy parameter for fine-grained filtering.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Agent", "Schedule" ], "CommandName": "Get-DbaAgentSchedule", "Name": "Get-DbaAgentSchedule", "Author": "Chris McKeown (@devopsfu), devopsfu.com", "Syntax": "Get-DbaAgentSchedule [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Schedule] \u003cString[]\u003e] [[-ScheduleUid] \u003cString[]\u003e] [[-Id] \u003cInt32[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.SharedSchedule\nReturns one SharedSchedule object per shared schedule found. Shared schedules can be reused across multiple SQL Server Agent jobs to standardize maintenance windows and reduce administrative overhead.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- ScheduleName: The display name of the shared schedule\r\n- ActiveStartDate: The date when the schedule becomes active (format depends on system locale)\r\n- ActiveStartTimeOfDay: The time of day when the schedule becomes active\r\n- ActiveEndDate: The date when the schedule stops being active (year 9999 indicates no end date)\r\n- ActiveEndTimeOfDay: The time of day when the schedule stops being active\r\n- DateCreated: Timestamp when the schedule was created in SQL Agent\r\n- FrequencyTypes: How often the schedule runs (Once, Daily, Weekly, Monthly, MonthlyRelative, AutoStart, OnIdle)\r\n- FrequencyInterval: The interval at which the schedule recurs (meaning depends on FrequencyTypes)\r\n- FrequencySubDayTypes: How often within a day the schedule runs (None, Once, Seconds, Minutes, Hours)\r\n- FrequencySubDayInterval: The interval in seconds, minutes, or hours between executions\r\n- FrequencyRecurrenceFactor: The number of periods between schedule executions (e.g., 2 for every 2 weeks)\r\n- FrequencyRelativeIntervals: Relative position for monthly schedules (First, Second, Third, Fourth, Last)\r\n- IsEnabled: Boolean indicating whether the schedule is active and available for job execution\r\n- JobCount: Number of SQL Server Agent jobs currently using this shared schedule\r\n- ScheduleUid: The unique GUID identifier for this schedule (immutable even if schedule is renamed)\r\n- Description: Human-readable description of the schedule timing pattern (auto-generated from frequency settings)\nAdditional properties available from the SMO SharedSchedule object:\r\n- Id: Numeric identifier for the shared schedule (assigned sequentially by SQL Server)\r\n- Name: Display name of the shared schedule\r\n- Owner: Login name that owns the schedule\nAll properties from the base SMO object are accessible using Select-Object *, even though only default properties are displayed without explicit selection.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAgentSchedule -SqlInstance localhost\nReturns all SQL Agent Shared Schedules on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgentSchedule -SqlInstance localhost, sql2016\nReturns all SQL Agent Shared Schedules for the local and sql2016 SQL Server instances\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaAgentSchedule -SqlInstance localhost, sql2016 -Id 3\nReturns the SQL Agent Shared Schedules with the Id of 3\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaAgentSchedule -SqlInstance localhost, sql2016 -ScheduleUid \u0027bf57fa7e-7720-4936-85a0-87d279db7eb7\u0027\nReturns the SQL Agent Shared Schedules with the UID\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaAgentSchedule -SqlInstance sql2016 -Schedule \"Maintenance10min\",\"Maintenance60min\"\nReturns the \"Maintenance10min\" \u0026 \"Maintenance60min\" schedules from the sql2016 SQL Server instance", "Description": "Retrieves all shared schedules from SQL Server Agent along with human-readable descriptions of their timing patterns. These shared schedules can be reused across multiple jobs to standardize maintenance windows and reduce schedule management overhead. The function provides filtering options by schedule name, unique identifier, or numeric ID, making it useful for schedule auditing, documentation, and troubleshooting automated job execution patterns.", "Links": "https://dbatools.io/Get-DbaAgentSchedule", "Synopsis": "Retrieves SQL Agent shared schedules with detailed timing and recurrence information.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Schedule", "Specifies one or more schedule names to retrieve from the SQL Agent shared schedules collection.\r\nUse this when you need to examine specific schedules by their display names, such as checking timing details for maintenance windows or job execution patterns.\r\nAccepts multiple schedule names and supports wildcards for pattern matching.", "", false, "false", "", "" ], [ "ScheduleUid", "Specifies the GUID-based unique identifier of one or more shared schedules to retrieve.\r\nUse this when you need to target schedules by their immutable identifiers, particularly useful for automation scripts or when schedule names might change.\r\nEach shared schedule has a persistent UID that remains constant even if the schedule is renamed.", "", false, "false", "", "" ], [ "Id", "Specifies the numeric identifier of one or more shared schedules to retrieve from SQL Agent.\r\nUse this when you know the internal ID numbers of specific schedules, often obtained from previous queries or database system tables.\r\nSchedule IDs are assigned sequentially by SQL Server and remain constant unless the schedule is deleted and recreated.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Job", "Agent" ], "CommandName": "Get-DbaAgentServer", "Name": "Get-DbaAgentServer", "Author": "Claudio Silva (@claudioessilva), claudioessilva.eu", "Syntax": "Get-DbaAgentServer [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Agent.JobServer\nReturns one JobServer object per instance. The object represents the SQL Server Agent configuration for that instance.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name (service name)\r\n- SqlInstance: The full SQL Server instance name (computer\\instance or computer for default instance)\r\n- AgentDomainGroup: The Active Directory domain group for SQL Server Agent\r\n- AgentLogLevel: The verbosity level for SQL Server Agent error log (Errors, Warnings, Informational, etc.)\r\n- AgentMailType: The mail system used by SQL Server Agent (SqlAgentMail or DatabaseMail)\r\n- AgentShutdownWaitTime: The number of seconds SQL Server waits for Agent to shut down during restart\r\n- ErrorLogFile: Full path to the SQL Server Agent error log file\r\n- IdleCpuDuration: The number of seconds CPU must remain below threshold to be considered idle (seconds)\r\n- IdleCpuPercentage: The CPU usage percentage threshold below which CPU is considered idle (percent)\r\n- IsCpuPollingEnabled: Boolean indicating if CPU idle condition monitoring is enabled\r\n- JobServerType: The role of the server in SQL Server Agent topology (Master, Target, etc.)\r\n- LoginTimeout: The timeout period for Agent connections to SQL Server (seconds)\r\n- JobHistoryIsEnabled: Boolean indicating if job history collection is enabled (computed from MaximumHistoryRows)\r\n- MaximumHistoryRows: The maximum number of job history rows to retain in MSDB; -1 for unlimited\r\n- MaximumJobHistoryRows: The maximum number of history rows to retain per individual job\r\n- MsxAccountCredentialName: The credential name for Multi-Server Administration master account\r\n- MsxAccountName: The login account for Multi-Server Administration\r\n- MsxServerName: The name of the Multi-Server Administration master server\r\n- Name: The name of the JobServer instance\r\n- NetSendRecipient: The recipient for legacy net send notifications from SQL Server Agent\r\n- ServiceAccount: The user account running the SQL Server Agent service\r\n- ServiceStartMode: The startup mode of the SQL Server Agent service (Automatic, Manual, Disabled)\r\n- SqlAgentAutoStart: Boolean indicating if SQL Server Agent starts automatically with SQL Server\r\n- SqlAgentMailProfile: The name of the legacy SQL Agent Mail profile for notifications\r\n- SqlAgentRestart: Boolean indicating if SQL Server Agent automatically restarts if stopped unexpectedly\r\n- SqlServerRestart: Boolean indicating if SQL Server Agent can restart the SQL Server service\r\n- State: The current state of the SQL Server Agent service (Running, Stopped, etc.)\r\n- SysAdminOnly: Boolean indicating if only sysadmin-level users can access SQL Server Agent\nAdditional properties available (from SMO JobServer object):\r\n- AlertCategories: Collection of alert categories configured on this instance\r\n- Alerts: Collection of alerts configured on this instance\r\n- AlertSystem: The alert system configuration object\r\n- DatabaseEngineEdition: The edition of SQL Server Database Engine (Enterprise, Standard, Express, etc.)\r\n- DatabaseEngineType: The type of Database Engine (Standalone, SqlAzureDatabase, etc.)\r\n- DatabaseMailProfile: The name of the Database Mail profile used for alerts and notifications\r\n- ExecutionManager: The job execution manager object\r\n- HostLoginName: The login name of the host running SQL Server Agent\r\n- JobCategories: Collection of job categories configured on this instance\r\n- Jobs: Collection of SQL Server Agent jobs configured on this instance\r\n- LocalHostAlias: The alias SQL Server Agent uses to reference the local server\r\n- OperatorCategories: Collection of operator categories configured on this instance\r\n- Operators: Collection of database mail operators configured on this instance\r\n- Parent: The parent SQL Server object\r\n- ProxyAccounts: Collection of proxy accounts configured for job step execution\r\n- ReplaceAlertTokensEnabled: Boolean indicating if alert notification tokens are replaced with actual values\r\n- SaveInSentFolder: Boolean indicating if copies of agent notifications are saved to Database Mail sent items\r\n- ServerVersion: The version of SQL Server\r\n- SharedSchedules: Collection of shared job schedules configured on this instance\r\n- TargetServerGroups: Collection of target server groups for Multi-Server Administration\r\n- TargetServers: Collection of target servers for Multi-Server Administration\r\n- WriteOemErrorLog: Boolean indicating if SQL Server Agent writes errors to the Windows Application Event Log\nAll properties from the SMO JobServer object are accessible via Select-Object * even though only the default properties are displayed without explicit column selection.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAgentServer -SqlInstance localhost\nReturns SQL Agent Server on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgentServer -SqlInstance localhost, sql2016\nReturns SQL Agent Servers for the localhost and sql2016 SQL Server instances", "Description": "Returns detailed SQL Server Agent configuration including service state, logging levels, job history settings, and service accounts. This is essential for auditing Agent configurations across multiple instances, troubleshooting job failures, and documenting environment settings for compliance or migration planning. The function provides a standardized view of Agent properties that would otherwise require connecting to each instance individually through SSMS.", "Links": "https://dbatools.io/Get-DbaAgentServer", "Synopsis": "Retrieves SQL Server Agent service configuration and status information", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "AG", "HA" ], "CommandName": "Get-DbaAgHadr", "Name": "Get-DbaAgHadr", "Author": "Shawn Melton (@wsmelton), wsmelton.github.io", "Syntax": "Get-DbaAgHadr [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance queried, containing the current HADR status.\nProperties:\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name (e.g., MSSQLSERVER or named instance)\r\n- SqlInstance: The full SQL Server instance identifier in the format ComputerName\\InstanceName or instance name for default\r\n- IsHadrEnabled: Boolean value indicating whether HADR is enabled ($true) or disabled ($false) on the instance", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAgHadr -SqlInstance sql2016\nReturns a status of the Hadr setting for sql2016 SQL Server instance.", "Description": "Checks whether Availability Groups are enabled at the service level on SQL Server instances. This is a prerequisite for creating and managing Availability Groups, as HADR must be enabled before you can configure any AG functionality. Returns the computer name, instance name, and the current HADR enabled status (true/false) for each specified instance, making it useful for environment audits and troubleshooting AG setup issues.", "Links": "https://dbatools.io/Get-DbaAgHadr", "Synopsis": "Retrieves the High Availability Disaster Recovery (HADR) service status for SQL Server instances.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "AG", "HA" ], "CommandName": "Get-DbaAgListener", "Name": "Get-DbaAgListener", "Author": "Viorel Ciucu (@viorelciucu)", "Syntax": "Get-DbaAgListener [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-AvailabilityGroup] \u003cString[]\u003e] [[-Listener] \u003cString[]\u003e] [[-InputObject] \u003cAvailabilityGroup[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.AvailabilityGroupListener\nReturns one listener object per availability group listener found on the specified instance(s) or availability group(s).\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance hosting the Availability Group\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- AvailabilityGroup: Name of the Availability Group that owns this listener\r\n- Name: Network name of the listener that clients use for connections\r\n- PortNumber: TCP port number for client connections (default 1433)\r\n- ClusterIPConfiguration: WSFC cluster IP resource configuration details\nAdditional properties available (from SMO AvailabilityGroupListener object):\r\n- AvailabilityGroupListenerIPAddresses: Collection of IP address configurations for this listener (one per subnet in multi-subnet scenarios)\r\n- Urn: Unique resource name for programmatic identification\r\n- State: SMO object state (Existing, Creating, Pending, etc.)\r\n- Properties: Collection of object properties and their values\nAll properties from the base SMO AvailabilityGroupListener object are accessible via Select-Object * even though only default properties are displayed by default.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAgListener -SqlInstance sql2017a\nReturns all listeners found on sql2017a\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgListener -SqlInstance sql2017a -AvailabilityGroup AG-a\nReturns all listeners found on sql2017a on sql2017a for the availability group AG-a\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sql2017a -AvailabilityGroup OPP | Get-DbaAgListener\nReturns all listeners found on sql2017a on sql2017a for the availability group OPP", "Description": "Retrieves availability group listener configurations from SQL Server instances, providing essential network details needed for client connections and troubleshooting. This function returns listener names, port numbers, IP configurations, and associated availability groups, which is crucial for validating listener setup and diagnosing connection issues. Use this when you need to document your AG infrastructure, verify listener configurations after setup, or troubleshoot client connectivity problems.", "Links": "https://dbatools.io/Get-DbaAgListener", "Synopsis": "Retrieves availability group listener configurations including IP addresses and port numbers.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "AvailabilityGroup", "Specifies which availability groups to include when retrieving listener information. Supports wildcards for pattern matching.\r\nUse this when you only need listener details for specific availability groups rather than all groups on the instance.", "", false, "false", "", "" ], [ "Listener", "Specifies which availability group listeners to return by name. Accepts multiple listener names for filtering results.\r\nUse this when you need to examine specific listeners during troubleshooting or when documenting particular AG configurations.", "", false, "false", "", "" ], [ "InputObject", "Accepts availability group objects from Get-DbaAvailabilityGroup for pipeline operations.\r\nUse this when chaining commands to get listener details for specific availability groups you\u0027ve already retrieved.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "AG", "HA" ], "CommandName": "Get-DbaAgReplica", "Name": "Get-DbaAgReplica", "Author": "Shawn Melton (@wsmelton) | Chrissy LeMaire (@cl)", "Syntax": "Get-DbaAgReplica [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-AvailabilityGroup] \u003cString[]\u003e] [[-Replica] \u003cString[]\u003e] [[-InputObject] \u003cAvailabilityGroup[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.AvailabilityReplica\nReturns one AvailabilityReplica object per replica found in the queried availability groups. The objects include added properties for context about the parent SQL Server instance and availability \r\ngroup.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance hosting the replica\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- AvailabilityGroup: Name of the availability group that contains this replica\r\n- Name: The name/display name of the availability group replica\r\n- Role: Current role of the replica (Primary or Secondary)\r\n- ConnectionState: Current connectivity state with the local server (Connected, Disconnected, etc.)\r\n- RollupSynchronizationState: Overall database synchronization state (NotSynchronizing, Synchronizing, Synchronized, Reverting, Initializing)\r\n- AvailabilityMode: Commit mode (SynchronousCommit or AsynchronousCommit)\r\n- BackupPriority: Backup preference priority value (0-100, where higher values are preferred for backups)\r\n- EndpointUrl: Database mirroring endpoint URL used for replica communication (format: TCP://hostname:port)\r\n- SessionTimeout: Session timeout in seconds for detecting communication failures (minimum 10 seconds recommended)\r\n- FailoverMode: Failover capability (Automatic or Manual)\r\n- ReadonlyRoutingList: Priority-ordered list of secondary replicas for routing read-only connections\nAdditional properties available (from SMO AvailabilityReplica object):\r\n- ConnectionModeInPrimaryRole: Connection mode when this replica is primary (AllowAllConnections or AllowReadWriteConnections)\r\n- ConnectionModeInSecondaryRole: Connection mode when this replica is secondary (AllowNoConnections, AllowReadIntentConnectionsOnly, or AllowAllConnections)\r\n- ReadonlyRoutingConnectionUrl: Connection URL used by read-only routing for this replica\r\n- SeedingMode: Database seeding mode (Automatic or Manual) - SQL Server 2016+\r\n- Parent: Reference to the parent AvailabilityGroup object\r\n- State: The state of the SMO object (Existing, Creating, Pending, etc.)\r\n- Urn: Uniform resource name for programmatic identification of the replica\nAll properties from the base SMO AvailabilityReplica object are accessible using Select-Object *, even though only default properties are displayed by default.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAgReplica -SqlInstance sql2017a\nReturns basic information on all the availability group replicas found on sql2017a\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgReplica -SqlInstance sql2017a -AvailabilityGroup SharePoint\nShows basic information on the replicas found on availability group SharePoint on sql2017a\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaAgReplica -SqlInstance sql2017a | Select-Object *\nReturns full object properties on all availability group replicas found on sql2017a", "Description": "Retrieves detailed information about availability group replicas including their current role, connection state, synchronization status, and failover configuration. This function helps DBAs monitor replica health, verify failover readiness, and troubleshoot availability group issues without manually querying system views. Returns comprehensive replica properties like backup priority, endpoint URLs, session timeouts, and read-only routing lists for availability group management and compliance reporting.", "Links": "https://dbatools.io/Get-DbaAgReplica", "Synopsis": "Retrieves availability group replica configuration and status information from SQL Server instances.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "AvailabilityGroup", "Specifies which availability groups to query for replica information. Accepts multiple values and wildcards for pattern matching.\r\nUse this when you need to focus on specific availability groups instead of retrieving replicas from all AGs on the instance.", "", false, "false", "", "" ], [ "Replica", "Filters results to return only the specified replica names. Accepts multiple values for querying specific replicas across availability groups.\r\nUse this when troubleshooting specific replicas or when you only need information about particular secondary replicas in your environment.", "", false, "false", "", "" ], [ "InputObject", "Accepts availability group objects piped from Get-DbaAvailabilityGroup, allowing for more efficient processing in pipeline scenarios.\r\nUse this when chaining commands or when you already have availability group objects and want to retrieve their replica details without additional server queries.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Diagnostic", "Buffer", "HADR", "AvailabilityGroup", "AG", "AlwaysOn" ], "CommandName": "Get-DbaAgRingBuffer", "Name": "Get-DbaAgRingBuffer", "Author": "the dbatools team + Claude", "Syntax": "Get-DbaAgRingBuffer [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-RingBufferType] \u003cString[]\u003e] [[-CollectionMinutes] \u003cInt32\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per ring buffer record retrieved from the SQL Server instance.\nProperties:\r\n- ComputerName : The computer name of the SQL Server instance\r\n- InstanceName : The SQL Server instance name\r\n- SqlInstance : The full SQL Server instance name (computer\\instance)\r\n- RingBufferType : The type of ring buffer (e.g. RING_BUFFER_HADRDBMGR_API)\r\n- RecordId : The unique record identifier from the ring buffer entry\r\n- EventTime : Approximate DateTime of the event (in local server time)\r\n- Record : The raw XML record containing event-specific diagnostic fields", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAgRingBuffer -SqlInstance sql2019\nReturns HADR ring buffer records from the last 60 minutes from the sql2019 instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgRingBuffer -SqlInstance sql2019 -CollectionMinutes 240\nReturns HADR ring buffer records from the last 240 minutes from the sql2019 instance.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaAgRingBuffer -SqlInstance sql2019 -RingBufferType RING_BUFFER_HADRDBMGR_API\nReturns only RING_BUFFER_HADRDBMGR_API records from the last 60 minutes from the sql2019 instance.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaAgRingBuffer -SqlInstance sql2019 -RingBufferType RING_BUFFER_HADRDBMGR_API, RING_BUFFER_HADR_TRANSPORT_STATE\nReturns API and transport state records from sql2019.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e\u0027sql2019\u0027, \u0027sql2022\u0027 | Get-DbaAgRingBuffer\nReturns all HADR ring buffer records from sql2019 and sql2022.", "Description": "This command queries sys.dm_os_ring_buffers for HADR-specific ring buffer types to provide diagnostic\ninformation about Always On availability groups. These ring buffers record state transitions, role changes,\ncommit activity, and transport state events useful for troubleshooting AG health and failover issues.\n\nAs noted in Microsoft\u0027s documentation, the ring buffers are not officially supported, but they provide\nvaluable post-mortem diagnostic data, especially when SQL Server stops responding or has crashed.\n\nReference: https://learn.microsoft.com/en-us/sql/database-engine/availability-groups/windows/always-on-ring-buffers", "Links": "https://dbatools.io/Get-DbaAgRingBuffer", "Synopsis": "Retrieves Always On availability group diagnostic data from SQL Server\u0027s internal HADR ring buffers.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance. To use:\r\n$cred = Get-Credential, this pass this $cred to the param.\nWindows Authentication will be used if SqlCredential is not specified. To connect as a different Windows user, run PowerShell as that user.", "", false, "false", "", "" ], [ "RingBufferType", "Specifies which HADR ring buffer types to query. Defaults to all four HADR ring buffer types.\nValid values:\r\n- RING_BUFFER_HADRDBMGR_API : State transitions at the API level\r\n- RING_BUFFER_HADRDBMGR_STATE : Database manager state change records\r\n- RING_BUFFER_HADRDBMGR_COMMIT : Commit-level activity records\r\n- RING_BUFFER_HADR_TRANSPORT_STATE: Connection and transport state transitions", "", false, "false", "", "RING_BUFFER_HADRDBMGR_API,RING_BUFFER_HADRDBMGR_STATE,RING_BUFFER_HADRDBMGR_COMMIT,RING_BUFFER_HADR_TRANSPORT_STATE" ], [ "CollectionMinutes", "Specifies how many minutes of historical data to retrieve from the ring buffer. Defaults to 60 minutes.\r\nUse this to extend the analysis window when investigating longer-term AG issues or to focus on recent activity with shorter periods.", "", false, "false", "60", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "AG", "HA" ], "CommandName": "Get-DbaAvailabilityGroup", "Name": "Get-DbaAvailabilityGroup", "Author": "Shawn Melton (@wsmelton) | Chrissy LeMaire (@cl)", "Syntax": "Get-DbaAvailabilityGroup [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-AvailabilityGroup] \u003cString[]\u003e] [-IsPrimary] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.AvailabilityGroup\nReturns one AvailabilityGroup object per availability group found on the specified instance(s). Three custom properties are added to each object for convenience: ComputerName, InstanceName, and \r\nSqlInstance.\nDefault display properties (without -IsPrimary):\r\n- ComputerName: The computer name of the SQL Server instance hosting the availability group\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- LocalReplicaRole: The role of the current replica in the availability group (Primary or Secondary)\r\n- AvailabilityGroup: Name of the availability group (from the Name property)\r\n- PrimaryReplica: The server name of the primary replica (from PrimaryReplicaServerName property)\r\n- ClusterType: Type of cluster supporting the availability group (Wsfc, External, None)\r\n- DtcSupportEnabled: Boolean indicating if Distributed Transaction Coordinator support is enabled\r\n- AutomatedBackupPreference: Preference for automated backups (Primary, SecondaryOnly, Secondary, None)\r\n- AvailabilityReplicas: Collection of replicas that are part of this availability group\r\n- AvailabilityDatabases: Collection of databases that are part of this availability group\r\n- AvailabilityGroupListeners: Collection of listeners configured for this availability group\nDefault display properties (with -IsPrimary):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- AvailabilityGroup: Name of the availability group (from the Name property)\r\n- IsPrimary: Boolean indicating whether the queried instance is the primary replica for this availability group\nAdditional properties available from the SMO AvailabilityGroup object:\r\n- Name: Name of the availability group\r\n- DtcSupportEnabled: Boolean for DTC support\r\n- AutomatedBackupPreference: Backup preference setting\r\n- FailureConditionLevel: Failure condition threshold level\r\n- HealthCheckTimeout: Health check timeout in milliseconds\r\n- BasicAvailabilityGroup: Boolean indicating if this is a basic availability group (SQL Server 2016+)\r\n- DatabaseHealthTrigger: Boolean for database health trigger setting\r\n- Urn: Uniform Resource Name for the SMO object\nAll properties from the SMO AvailabilityGroup object are accessible by using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sqlserver2014a\nReturns basic information on all the Availability Group(s) found on sqlserver2014a.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sqlserver2014a -AvailabilityGroup AG-a\nShows basic information on the Availability Group AG-a on sqlserver2014a.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sqlserver2014a | Select-Object *\nReturns full object properties on all Availability Group(s) on sqlserver2014a.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sqlserver2014a | Select-Object -ExpandProperty PrimaryReplicaServerName\nReturns the SQL Server instancename of the primary replica as a string\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sqlserver2014a -AvailabilityGroup AG-a -IsPrimary\nReturns true/false if the server, sqlserver2014a, is the primary replica for AG-a Availability Group.", "Description": "Retrieves detailed Availability Group information including replica roles, cluster configuration, database membership, and listener details from SQL Server 2012+ instances.\n\nThis command helps DBAs monitor AG health, identify primary replicas for failover planning, and generate inventory reports for compliance or troubleshooting. The default view shows essential properties like replica roles, primary replica location, and cluster type, while the full object contains comprehensive AG configuration details.", "Links": "https://dbatools.io/Get-DbaAvailabilityGroup", "Synopsis": "Retrieves Availability Group configuration and status information from SQL Server instances.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2012 or higher.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "AvailabilityGroup", "Specifies one or more Availability Group names to filter results to specific AGs. Supports wildcards for pattern matching.\r\nUse this when you need to check status or configuration of particular AGs rather than retrieving information for all AGs on the instance.", "", false, "false", "", "" ], [ "IsPrimary", "Returns a boolean value indicating whether the queried SQL Server instance is currently serving as the Primary replica for each Availability Group.\r\nUse this switch when you need to quickly identify which replica in your AG topology is currently primary, particularly useful for automated failover scripts or health monitoring.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Collation", "Configuration", "Management" ], "CommandName": "Get-DbaAvailableCollation", "Name": "Get-DbaAvailableCollation", "Author": "Bryan Hamby (@galador)", "Syntax": "Get-DbaAvailableCollation [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Collation\nReturns one collation object per collation supported by each SQL Server instance, enhanced with human-readable descriptions.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server service name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Name: The collation name (e.g., SQL_Latin1_General_CP1_CI_AS)\r\n- CodePage: The numeric code page identifier (e.g., 1252 for Latin1)\r\n- CodePageName: Human-readable code page encoding name (e.g., iso-8859-1)\r\n- LocaleID: The numeric locale identifier (LCID) representing the language/culture\r\n- LocaleName: Human-readable locale/language name (e.g., English_United States, Japanese_Unicode)\r\n- Description: SQL Server collation description with sorting and case sensitivity information\nAdditional properties available from SMO Collation object (use Select-Object * to access):\r\n- BinaryOrder: Boolean indicating if the collation uses binary sort order\r\n- BuiltInComparisonStyle: The comparison style constant used by SQL Server\r\n- IsCodePageCompatible: Boolean indicating code page compatibility\r\n- IsCaseSensitive: Boolean indicating if the collation is case-sensitive\r\n- IsAccentSensitive: Boolean indicating if the collation is accent-sensitive\r\n- IsKanaTypeSensitive: Boolean indicating if the collation distinguishes between Hiragana and Katakana\r\n- IsWidthSensitive: Boolean indicating if the collation distinguishes between full-width and half-width characters\nAll properties from the base SMO Collation object are accessible even though only default properties are displayed without using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAvailableCollation -SqlInstance sql2016\nGets all the collations from server sql2016 using NT authentication", "Description": "Returns the complete list of collations supported by each SQL Server instance, along with their associated code page names, locale descriptions, and detailed properties.\nThis information is essential when creating new databases, changing database collations, or planning migrations where collation compatibility matters.\nThe function enhances the raw collation data with human-readable code page and locale descriptions to help DBAs make informed collation choices.\nOnly connect permission is required to retrieve this information.", "Links": "https://dbatools.io/Get-DbaAvailableCollation", "Synopsis": "Retrieves all available collations from SQL Server instances with detailed locale and code page information", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. Only connect permission is required.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Backup", "General" ], "CommandName": "Get-DbaBackupDevice", "Name": "Get-DbaBackupDevice", "Author": "Garry Bargsley (@gbargsley), blog.garrybargsley.com", "Syntax": "Get-DbaBackupDevice [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.BackupDevice\nReturns one BackupDevice object per configured backup device on each SQL Server instance.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The name of the computer hosting the SQL Server instance\r\n- InstanceName: The name of the SQL Server instance\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Name: The logical name of the backup device\r\n- BackupDeviceType: The type of backup device (Disk, Tape, or Url)\r\n- PhysicalLocation: The physical path or location of the backup device (file path, tape device, or URL)\r\n- SkipTapeLabel: Boolean indicating whether to skip tape label validation\nAdditional properties available (from SMO BackupDevice object):\r\n- Urn: The Uniform Resource Name identifying the backup device\r\n- State: The state of the SMO object (Existing, Creating, Pending, etc.)\r\n- Parent: Reference to the parent Server object\nAll properties from the SMO BackupDevice object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaBackupDevice -SqlInstance localhost\nReturns all Backup Devices on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaBackupDevice -SqlInstance localhost, sql2016\nReturns all Backup Devices for the local and sql2016 SQL Server instances", "Description": "This function returns all backup devices configured on SQL Server instances, including their type (disk, tape, URL), physical locations, and settings. Backup devices are logical names that map to physical backup destinations, allowing DBAs to create standardized backup locations that can be referenced in backup scripts and maintenance plans. Use this to audit backup device configurations across your environment, verify backup paths are accessible, or document your backup infrastructure for compliance and disaster recovery planning.", "Links": "https://dbatools.io/Get-DbaBackupDevice", "Synopsis": "Retrieves configured backup devices from SQL Server instances for inventory and management", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function\r\nto be executed against multiple SQL Server instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "DisasterRecovery", "Backup", "Restore" ], "CommandName": "Get-DbaBackupInformation", "Name": "Get-DbaBackupInformation", "Author": "Chrissy LeMaire (@cl) | Stuart Moore (@napalmgram)", "Syntax": "Get-DbaBackupInformation -Path \u003cObject[]\u003e -SqlInstance \u003cDbaInstanceParameter\u003e [-SqlCredential \u003cPSCredential\u003e] [-DatabaseName \u003cString[]\u003e] [-SourceInstance \u003cString[]\u003e] [-NoXpDirTree] [-NoXpDirRecurse] [-DirectoryRecurse] [-EnableException] [-MaintenanceSolution] [-IgnoreLogBackup] [-IgnoreDiffBackup] [-ExportPath \u003cString\u003e] [-StorageCredential \u003cString\u003e] [-Anonymise] [-NoClobber] [-PassThru] [\u003cCommonParameters\u003e]\nGet-DbaBackupInformation -Path \u003cObject[]\u003e [-DatabaseName \u003cString[]\u003e] [-SourceInstance \u003cString[]\u003e] [-EnableException] [-MaintenanceSolution] [-IgnoreLogBackup] [-IgnoreDiffBackup] [-ExportPath \u003cString\u003e] [-StorageCredential \u003cString\u003e] [-Import] [-Anonymise] [-NoClobber] [-PassThru] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Dataplat.Dbatools.Database.BackupHistory\nReturns one BackupHistory object per backup set (group of files from the same backup operation). This object contains all necessary information to restore databases using Restore-DbaDatabase and \r\nsupports being piped directly into that command.\nThe object includes the following properties:\n- ComputerName: The computer name where the backup originated from (SQL Server host)\r\n- InstanceName: The SQL Server instance name where the backup was taken\r\n- SqlInstance: The full SQL Server instance name (ComputerName\\InstanceName)\r\n- Database: The name of the database that was backed up\r\n- UserName: The Windows/SQL login that performed the backup\r\n- Start: DateTime of when the backup started\r\n- End: DateTime of when the backup finished\r\n- Duration: TimeSpan representing the duration of the backup operation\r\n- Type: String indicating the backup type (Full, Differential, or Log)\r\n- Path: String array of file paths containing the backup files\r\n- FullName: Array of backup file paths (same as Path)\r\n- FileList: Array of PSCustomObjects containing backup file details with properties: Type (MDF/LDF/NDF), LogicalName, PhysicalName, Size\r\n- TotalSize: Total size of the backup in bytes\r\n- CompressedBackupSize: Size of the compressed backup in bytes\r\n- BackupSetId: GUID uniquely identifying this backup set\r\n- Position: Position of the backup within the device\r\n- DeviceType: The type of backup device (typically \u0027Disk\u0027)\r\n- FirstLsn: BigInt representing the first log sequence number in the backup\r\n- DatabaseBackupLsn: BigInt representing the database backup LSN for log backups\r\n- CheckpointLSN: BigInt representing the checkpoint LSN\r\n- LastLsn: BigInt representing the last log sequence number in the backup\r\n- SoftwareVersionMajor: Major version of SQL Server that created the backup\r\n- RecoveryModel: The recovery model of the database (Simple, Full, or BulkLogged)\r\n- IsCopyOnly: Boolean indicating if this is a copy-only backup\nWhen -Anonymise is specified, the following properties are hashed: ComputerName, InstanceName, SqlInstance, Database, UserName, Path, FullName, and file logical/physical names in FileList.\nWhen -Import is specified, the BackupHistory object is deserialized from the exported CliXml file, preserving all properties for later use with Restore-DbaDatabase.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaBackupInformation -SqlInstance Server1 -Path c:\\backups\\ -DirectoryRecurse\nWill use the Server1 instance to recursively read all backup files under c:\\backups, and return a dbatools BackupHistory object\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaBackupInformation -SqlInstance Server1 -Path c:\\backups\\ -DirectoryRecurse -ExportPath c:\\store\\BackupHistory.xml\nPS C:\\\u003e robocopy c:\\store\\ \\\\remoteMachine\\C$\\store\\ BackupHistory.xml\r\nPS C:\\\u003e Get-DbaBackupInformation -Import -Path c:\\store\\BackupHistory.xml | Restore-DbaDatabase -SqlInstance Server2 -TrustDbBackupHistory\nThis example creates backup history output from server1 and copies the file to the remote machine in order to preserve backup history. It is then used to restore the databases onto server2.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaBackupInformation -SqlInstance Server1 -Path c:\\backups\\ -DirectoryRecurse -ExportPath C:\\store\\BackupHistory.xml -PassThru | Restore-DbaDatabase -SqlInstance Server2 \r\n-TrustDbBackupHistory\nIn this example we gather backup information, export it to an xml file, and then pass it on through to Restore-DbaDatabase.\r\nThis allows us to repeat the restore without having to scan all the backup files again\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-ChildItem c:\\backups\\ -recurse -files | Where-Object {$_.extension -in (\u0027.bak\u0027,\u0027.trn\u0027) -and $_.LastWriteTime -gt (get-date).AddMonths(-1)} | Get-DbaBackupInformation -SqlInstance Server1 \r\n-ExportPath C:\\backupHistory.xml\nThis lets you keep a record of all backup history from the last month on hand to speed up refreshes\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$Backups = Get-DbaBackupInformation -SqlInstance Server1 -Path \\\\network\\backups\nPS C:\\\u003e $Backups += Get-DbaBackupInformation -SqlInstance Server2 -NoXpDirTree -Path c:\\backups\nScan the unc folder \\\\network\\backups with Server1, and then scan the C:\\backups folder on\r\nServer2 not using xp_dirtree, adding the results to the first set.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e$Backups = Get-DbaBackupInformation -SqlInstance Server1 -Path \\\\network\\backups -MaintenanceSolution\nWhen MaintenanceSolution is indicated we know we are dealing with the output from Ola Hallengren backup scripts. So we make sure that a FULL folder exists in the first level of Path, if not we \r\nshortcut scanning all the files as we have nothing to work with\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003e$Backups = Get-DbaBackupInformation -SqlInstance Server1 -Path \\\\network\\backups -MaintenanceSolution -IgnoreLogBackup\nAs we know we are dealing with an Ola Hallengren style backup folder from the MaintenanceSolution switch, when IgnoreLogBackup is also included we can ignore the LOG folder to skip any scanning of \r\nlog backups. Note this also means they WON\u0027T be restored\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003e$Backups = Get-DbaBackupInformation -SqlInstance sql2022 -Path s3://s3.us-west-2.amazonaws.com/mybucket/backups/mydb.bak -StorageCredential MyS3Credential\nGets backup information from an S3-compatible object storage location. Requires SQL Server 2022 or higher. The credential must be configured with Identity = \u0027S3 Access Key\u0027 and Secret containing the \r\naccess key and secret key.", "Description": "Reads the headers of SQL Server backup files to extract metadata and creates BackupHistory objects compatible with Restore-DbaDatabase. This eliminates the need to manually track backup chains and file locations when planning database restores.\n\nThe function identifies valid SQL Server backup files from a given path, reads their headers using the SQL Server instance, and organizes them into backup sets. It handles full, differential, and log backups, automatically determining backup types, LSN chains, and file dependencies.\n\nBy default, the function uses xp_dirtree to scan remote paths accessible to the SQL Server instance. This means paths must be accessible from the SQL Server service account. The -NoXpDirTree switch allows scanning local files instead.\n\nSpecial support is included for Ola Hallengren maintenance solution backup folder structures, which can significantly speed up scanning of organized backup directories.", "Links": "https://dbatools.io/Get-DbaBackupInformation", "Synopsis": "Scans backup files and reads their headers to create structured backup history objects for restore operations", "Availability": "Windows, Linux, macOS", "Params": [ [ "Path", "Path to SQL Server backup files.\nPaths passed in as strings will be scanned using the desired method, default is a non recursive folder scan\r\nAccepts multiple paths separated by \u0027,\u0027\nOr it can consist of FileInfo objects, such as the output of Get-ChildItem or Get-Item. This allows you to work with\r\nyour own file structures as needed", "", true, "true (ByValue)", "", "" ], [ "SqlInstance", "The SQL Server instance to be used to read the headers of the backup files", "", true, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "DatabaseName", "An array of Database Names to filter by. If empty all databases are returned.", "", false, "false", "", "" ], [ "SourceInstance", "If provided only backup originating from this destination will be returned. This SQL instance will not be connected to or involved in this work", "", false, "false", "", "" ], [ "NoXpDirTree", "If specified, this switch will cause the files to be parsed as local files to the SQL Server Instance provided. Errors may be observed when the SQL Server Instance cannot access the files being \r\nparsed.", "", false, "false", "False", "" ], [ "NoXpDirRecurse", "If specified, this switch changes xp_dirtree behavior to not recurse the folder structure.", "", false, "false", "False", "" ], [ "DirectoryRecurse", "If specified the provided path/directory will be traversed (only applies if not using XpDirTree)", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "MaintenanceSolution", "This switch tells the function that the folder is the root of a Ola Hallengren backup folder", "", false, "false", "False", "" ], [ "IgnoreLogBackup", "This switch only works with the MaintenanceSolution switch. With an Ola Hallengren style backup we can be sure that the LOG folder contains only log backups and skip it.\r\nFor all other scenarios we need to read the file headers to be sure.", "", false, "false", "False", "" ], [ "IgnoreDiffBackup", "This switch only works with the MaintenanceSolution switch. With an Ola Hallengren style backup we can be sure that the DIFF folder contains only differential backups and skip it.\r\nFor all other scenarios we need to read the file headers to be sure.", "", false, "false", "False", "" ], [ "ExportPath", "If specified the output will export via CliXml format to the specified file. This allows you to store the backup history object for later usage, or move it between computers", "", false, "false", "", "" ], [ "StorageCredential", "The name of the SQL Server credential to be used if restoring from cloud storage (Azure Blob Storage or S3-compatible object storage).\r\nFor Azure, this is typically a credential with access to the storage account.\r\nFor S3, this should be a credential created with Identity \u0027S3 Access Key\u0027 matching the S3 URL path.", "AzureCredential,S3Credential", false, "false", "", "" ], [ "Import", "When specified along with a path the command will import a previously exported BackupHistory object from an xml file.", "", false, "false", "False", "" ], [ "Anonymise", "If specified we will output the results with ComputerName, InstanceName, Database, UserName, Paths, and Logical and Physical Names hashed out\r\nThis options is mainly for use if we need you to submit details for fault finding to the dbatools team", "Anonymize", false, "false", "False", "" ], [ "NoClobber", "If specified will stop Export from overwriting an existing file, the default is to overwrite", "", false, "false", "False", "" ], [ "PassThru", "When data is exported the cmdlet will return no other output, this switch means it will also return the normal output which can be then piped into another command", "", false, "false", "False", "" ] ] }, { "Tags": [ "Migration", "Backup", "Export" ], "CommandName": "Get-DbaBinaryFileTable", "Name": "Get-DbaBinaryFileTable", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaBinaryFileTable [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-Table] \u003cString[]\u003e] [[-Schema] \u003cString[]\u003e] [[-InputObject] \u003cTable[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Table\nReturns one Table object for each table found containing binary columns (binary, varbinary, or image data types).\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: The database name containing the table\r\n- Schema: The schema name containing the table\r\n- Name: The table name\r\n- BinaryColumn: The name(s) of the column(s) containing binary data; multiple values if multiple binary columns exist\r\n- FileNameColumn: The name of the column identified as containing filenames for extraction; empty if no column matches the pattern or multiple matches were found\nAdditional properties available from the base SMO Table object include:\r\n- IndexSpaceUsed: Space consumed by indexes on the table (bytes)\r\n- DataSpaceUsed: Space consumed by table data (bytes)\r\n- RowCount: Number of rows in the table\r\n- HasClusteredIndex: Boolean indicating if the table has a clustered index\r\n- IsPartitioned: Boolean indicating if the table uses partitioning (SQL Server 2005+)\r\n- ChangeTrackingEnabled: Boolean indicating if change tracking is enabled (SQL Server 2008+)\r\n- IsFileTable: Boolean indicating if the table is a FileTable (SQL Server 2012+)\r\n- IsMemoryOptimized: Boolean indicating if the table is memory-optimized (SQL Server 2014+)\r\n- IsNode: Boolean indicating if the table is a node table (SQL Server 2017+)\r\n- IsEdge: Boolean indicating if the table is an edge table (SQL Server 2017+)\r\n- FullTextIndex: Full-text index configuration for the table if present\nAll properties from the SMO Table object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaBinaryFileTable -SqlInstance sqlcs -Database test\nReturns a table with binary columns which can be used with Export-DbaBinaryFile and Import-DbaBinaryFile.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaBinaryFileTable -SqlInstance sqlcs -Database test | Out-GridView -Passthru | Export-DbaBinaryFile -Path C:\\temp\nAllows you to pick tables with columns to be exported by Export-DbaBinaryFile", "Description": "Scans database tables to find those containing binary data columns (binary, varbinary, image) and automatically identifies potential filename columns for file extraction workflows. This function is essential when you need to extract files that have been stored as BLOBs in SQL Server tables but aren\u0027t sure which tables contain binary data or how the filenames are stored.\n\nThe function enhances table objects by adding BinaryColumn and FileNameColumn properties, making it easy to pipe results directly to Export-DbaBinaryFile for automated file extraction. This is particularly useful for legacy applications where files were stored in the database rather than the file system, or when you need to audit what binary content exists across your databases.", "Links": "https://dbatools.io/Get-DbaBinaryFileTable", "Synopsis": "Identifies tables containing binary columns and their associated filename columns for file extraction operations.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input.", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to scan for tables containing binary columns. Accepts wildcards for pattern matching.\r\nUse this to limit the search scope when you know which databases might contain file storage tables, reducing scan time on large instances.", "", false, "false", "", "" ], [ "Table", "Targets specific tables to analyze for binary columns instead of scanning all tables in the database. Supports three-part naming (database.schema.table) and wildcards.\r\nUse this when you already know which tables contain binary data, such as document storage tables or attachment tables in applications.\r\nWrap table names with special characters in square brackets, and escape actual ] characters by doubling them.", "", false, "false", "", "" ], [ "Schema", "Restricts the search to tables within specific database schemas. Accepts multiple schema names and wildcards.\r\nUseful for focusing on application-specific schemas that typically contain file storage tables, such as \u0027Documents\u0027 or \u0027Attachments\u0027 schemas.", "", false, "false", "", "" ], [ "InputObject", "Accepts table objects piped directly from Get-DbaDbTable, allowing you to pre-filter tables before binary column analysis.\r\nUse this approach when you want to combine complex table filtering with binary column detection in a pipeline workflow.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "SqlBuild", "Utility" ], "CommandName": "Get-DbaBuild", "Name": "Get-DbaBuild", "Author": "Simone Bizzotto (@niphold) | Friedrich Weinmann (@FredWeinmann)", "Syntax": "Get-DbaBuild [[-Build] \u003cVersion[]\u003e] [[-Kb] \u003cString[]\u003e] [[-MajorVersion] \u003cString\u003e] [[-ServicePack] \u003cString\u003e] [[-CumulativeUpdate] \u003cString\u003e] [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [-Update] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "Get-DbaBuildReference", "Outputs": "PSCustomObject\nReturns one object per build queried, containing SQL Server version and patch level information.\nDefault properties when querying by -SqlInstance (all 9 properties displayed):\r\n- SqlInstance: The SQL Server instance name (computer\\instance format)\r\n- Build: The full build version number (e.g., 12.00.4502)\r\n- NameLevel: SQL Server product name (e.g., \"SQL Server 2014\", \"SQL Server 2019\")\r\n- SPLevel: Service pack level (e.g., \"SP1\", \"SP2\", or \"RTM\" for initial release)\r\n- CULevel: Cumulative update level (e.g., \"CU11\", \"CU15\", or empty string if none applied)\r\n- KBLevel: Array of Knowledge Base (KB) article numbers associated with this build\r\n- BuildLevel: The normalized build version object\r\n- SupportedUntil: DateTime indicating when this build version reaches end of support from Microsoft\r\n- ReleaseDate: DateTime indicating when this build was released by Microsoft (null if not available in the index)\r\n- MatchType: Match precision (\"Exact\" for precise match or \"Approximate\" if closest available match)\r\n- Warning: Alert message if the build is retired or other issues detected (null if no warnings)\nProperties when querying by -Build, -Kb, or -MajorVersion (SqlInstance excluded from display):\r\nWhen using these parameters, the SqlInstance property is excluded from the default display but all 10 properties remain accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaBuild -Build \"12.00.4502\"\nReturns information about a build identified by \"12.00.4502\" (which is SQL 2014 with SP1 and CU11)\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaBuild -Build \"12.00.4502\" -Update\nReturns information about a build trying to fetch the most up to date index online. When the online version is newer, the local one gets overwritten\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaBuild -Build \"12.0.4502\",\"10.50.4260\"\nReturns information builds identified by these versions strings\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaRegServer -SqlInstance sqlserver2014a | Get-DbaBuild\nIntegrate with other cmdlets to have builds checked for all your registered servers on sqlserver2014a", "Description": "Identifies the specific build version of SQL Server instances and translates build numbers into meaningful patch levels with their corresponding KB articles.\nThis function helps DBAs quickly determine what service packs and cumulative updates are installed, whether builds have been retired by Microsoft, and when support ends.\nYou can query live SQL Server instances, look up specific build numbers, search by KB article numbers, or find builds by specifying major version with service pack and cumulative update combinations.\nThe function maintains an offline reference index that can be updated online to ensure current patch information and accurate support lifecycle dates.", "Links": "https://dbatools.io/Get-DbaBuild", "Synopsis": "Retrieves detailed SQL Server build information including service pack, cumulative update, KB articles, and support lifecycle dates", "Availability": "Windows, Linux, macOS", "Params": [ [ "Build", "Specifies SQL Server build numbers to look up without connecting to live instances. Accepts version strings like \"12.00.4502\" or \"13.0.5026\".\r\nUse this when you need to identify what service pack and cumulative update a specific build number represents, or to verify patch levels from installation logs.", "", false, "false", "", "" ], [ "Kb", "Looks up SQL Server build information using Knowledge Base article numbers. Accepts formats like \"KB4057119\" or just \"4057119\".\r\nUse this when you have a KB number from Microsoft documentation or patch notes and need to identify the corresponding SQL Server build version and patch level.", "", false, "false", "", "" ], [ "MajorVersion", "Specifies the SQL Server major version to look up build information for specific version and patch level combinations. Accepts formats like \"SQL2016\", \"2016\", or \"2008R2\".\r\nUse this with -ServicePack and -CumulativeUpdate parameters when you need to find the exact build number for a specific SQL Server version and patch level combination.", "", false, "false", "", "" ], [ "ServicePack", "Specifies the service pack level when looking up builds by major version. Accepts formats like \"SP1\", \"1\", or \"RTM\" for initial release. Defaults to \"RTM\".\r\nRequires the -MajorVersion parameter and can be combined with -CumulativeUpdate to pinpoint exact patch levels.", "SP", false, "false", "RTM", "" ], [ "CumulativeUpdate", "Specifies the cumulative update level when looking up builds by major version and service pack. Accepts formats like \"CU5\", \"5\", or \"CU0\" for base service pack.\r\nRequires the -MajorVersion parameter and works in combination with -ServicePack to identify exact patch levels within a service pack.", "CU", false, "false", "", "" ], [ "SqlInstance", "Target any number of instances, in order to return their build state.", "", false, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Update", "Forces an online refresh of the local SQL Server build reference index from Microsoft sources. Updates the cached build database with the latest patch information and support lifecycle dates.\r\nUse this when the function warns about stale index data or when you need the most current patch and support information for accurate compliance reporting.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "SqlClient", "Alias" ], "CommandName": "Get-DbaClientAlias", "Name": "Get-DbaClientAlias", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaClientAlias [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server client alias found in the registry. Each object represents a single alias configured on the specified computer(s).\nProperties:\r\n- ComputerName: The name of the computer where the client alias is configured\r\n- NetworkLibrary: The network protocol type for the alias (TCP/IP or Named Pipes)\r\n- ServerName: The target server name or instance (with protocol prefix removed)\r\n- AliasName: The alias name as defined in the registry\r\n- AliasString: The complete registry value including protocol prefix (e.g., DBMSSOCN,servername,1433)\r\n- Architecture: The registry hive architecture where the alias was found (32-bit or 64-bit)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaClientAlias\nGets all SQL Server client aliases on the local computer\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaClientAlias -ComputerName workstationx\nGets all SQL Server client aliases on Workstationx\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaClientAlias -ComputerName workstationx -Credential ad\\sqldba\nLogs into workstationx as ad\\sqldba then retrieves all SQL Server client aliases on Workstationx\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e\u0027Server1\u0027, \u0027Server2\u0027 | Get-DbaClientAlias\nGets all SQL Server client aliases on Server1 and Server2", "Description": "Retrieves all configured SQL Server client aliases by reading the Windows registry paths where SQL Server Native Client stores alias definitions. Client aliases allow DBAs to create friendly names that map to actual SQL Server instances, making connection strings simpler and more portable across environments. This is particularly useful when managing multiple instances, non-default ports, or when you need to abstract the actual server names from applications and connection strings.", "Links": "https://dbatools.io/Get-DbaClientAlias", "Synopsis": "Retrieves SQL Server client aliases from the Windows registry on local or remote computers", "Availability": "Windows only", "Params": [ [ "ComputerName", "Specifies the computer(s) to retrieve SQL Server client aliases from. Accepts multiple computers via pipeline input.\r\nUse this when you need to audit client alias configurations across multiple workstations or servers in your environment.", "", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Allows you to login to remote computers using alternative credentials", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Management", "Protocol", "OS" ], "CommandName": "Get-DbaClientProtocol", "Name": "Get-DbaClientProtocol", "Author": "Klaas Vandenberghe (@PowerDBAKlaas)", "Syntax": "Get-DbaClientProtocol [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.Management.Infrastructure.CimInstance#root\\Microsoft\\SQLServer\\ComputerManagement*\\ClientNetworkProtocol\nReturns one ClientNetworkProtocol WMI object per protocol found on each computer.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name where the protocol is configured (alias for PSComputerName)\r\n- DisplayName: The friendly display name of the protocol (alias for ProtocolDisplayName), such as \"TCP/IP\", \"Named Pipes\", \"Shared Memory\", or \"VIA\"\r\n- DLL: The DLL file associated with the protocol (alias for ProtocolDll), typically sqlncli10.dll, sqlncli11.dll, or msoledbsql.dll\r\n- Order: The protocol precedence order (alias for ProtocolOrder); lower numbers indicate higher priority, 0 means disabled\r\n- IsEnabled: Boolean indicating if the protocol is enabled (based on ProtocolOrder value)\nAdditional properties available from the WMI object:\r\n- ProtocolDisplayName: Friendly name of the protocol\r\n- ProtocolDll: Path to the protocol DLL file\r\n- ProtocolOrder: Numeric precedence order (0 = disabled, 1+ = enabled and ordered)\r\n- PSComputerName: Computer name from WMI\r\n- PSPath: WMI object path\r\n- PSProvider: WMI provider name\nMethods:\r\n- Enable(): Enables the protocol by calling the WMI SetEnable method; returns exit code 0 on success\r\n- Disable(): Disables the protocol by calling the WMI SetDisable method; returns exit code 0 on success\nAll properties and methods are accessible even though only default properties are displayed without using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaClientProtocol -ComputerName sqlserver2014a\nGets the SQL Server related client protocols on computer sqlserver2014a.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027sql1\u0027,\u0027sql2\u0027,\u0027sql3\u0027 | Get-DbaClientProtocol\nGets the SQL Server related client protocols on computers sql1, sql2 and sql3.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaClientProtocol -ComputerName sql1,sql2 | Out-GridView\nGets the SQL Server related client protocols on computers sql1 and sql2, and shows them in a grid view.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e(Get-DbaClientProtocol -ComputerName sql2 | Where-Object { $_.DisplayName -eq \u0027Named Pipes\u0027 }).Disable()\nDisables the VIA ClientNetworkProtocol on computer sql2.\r\nIf successful, return code 0 is shown.", "Description": "Retrieves the configuration and status of SQL Server client network protocols (Named Pipes, TCP/IP, Shared Memory, VIA) from local or remote computers. This function helps DBAs audit and troubleshoot client connectivity issues by showing which protocols are enabled, their order of precedence, and associated DLL files.\n\nThe returned objects include Enable() and Disable() methods, allowing you to modify protocol settings directly without opening SQL Server Configuration Manager. This is particularly useful for standardizing client configurations across multiple servers or troubleshooting connectivity problems.\n\nRequires Local Admin rights on destination computer(s) and SQL Server 2005 or later.\nThe client protocols can be enabled and disabled when retrieved via WSMan.", "Links": "https://dbatools.io/Get-DbaClientProtocol", "Synopsis": "Retrieves SQL Server client network protocol configuration and status from local or remote computers.", "Availability": "Windows only", "Params": [ [ "ComputerName", "Specifies the target computer(s) to retrieve SQL Server client protocol configuration from. Accepts computer names, IP addresses, or SQL Server instance names.\r\nUse this when you need to audit client protocol settings on remote servers or troubleshoot connectivity issues across multiple machines.\r\nDefaults to the local computer if not specified.", "cn,host,Server", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Credential object used to connect to the computer as a different user.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "ComputerManagement", "CIM" ], "CommandName": "Get-DbaCmConnection", "Name": "Get-DbaCmConnection", "Author": "Friedrich Weinmann (@FredWeinmann)", "Syntax": "Get-DbaCmConnection [[-ComputerName] \u003cString[]\u003e] [[-UserName] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Dataplat.Dbatools.Connection.ManagementConnection\nReturns one ManagementConnection object per cached connection matching the filter criteria. Each object represents a cached remote computer management connection that dbatools uses for Windows \r\nManagement and CIM operations.\nDefault display properties (displayed in table format):\r\n- ComputerName: The name of the remote computer that this connection is cached for\r\n- Available: Whether any connection protocol (CIM, WMI, or PowerShell Remoting) is available to this computer\r\n- User: The username being used for this connection (either from stored credentials or the current Windows user)\r\n- OverrideExplicitCredential: Boolean indicating if this connection ignores explicitly provided credentials and uses cached ones instead\r\n- DisabledConnectionTypes: Which connection protocols are disabled for this computer (CimRM, CimDCOM, Wmi, PowerShellRemoting, or combinations)\nAdditional properties available on the object (use Select-Object * to view all):\r\n- Credentials: The stored PSCredential object used for this connection (if any). Contains UserName property.\r\n- UseWindowsCredentials: Boolean indicating if Windows authentication should be used\r\n- DisableBadCredentialCache: Boolean indicating if failed credentials are not cached for this computer\r\n- DisableCimPersistence: Boolean indicating if CIM sessions are not reused for this computer\r\n- DisableCredentialAutoRegister: Boolean indicating if successful credentials are not automatically cached\r\n- WindowsCredentialsAreBad: Boolean indicating if Windows authentication has been marked as non-functional\r\n- CimRM: Connection test result for CIM over WinRM protocol (Success or Error)\r\n- CimDCOM: Connection test result for CIM over DCOM protocol (Success or Error)\r\n- Wmi: Connection test result for WMI protocol (Success or Error)\r\n- PowerShellRemoting: Connection test result for PowerShell Remoting protocol (Success or Error)\r\n- CimWinRMOptions: Advanced WinRM session options configured for this connection\r\n- CimDCOMOptions: Advanced DCOM session options configured for this connection", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaCmConnection\nList all cached connections.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaCmConnection sql2014\nList the cached connection - if any - to the server sql2014.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaCmConnection -UserName \"*charles*\"\nList all cached connection that use a username containing \"charles\" as default or override credentials.", "Description": "Shows which remote computer connections are currently cached by dbatools for Windows Management and CIM operations. This helps you understand what authentication contexts are active and troubleshoot connection issues when running dbatools commands against remote SQL Server instances. Cached connections are automatically created when you run dbatools commands that need to access Windows services, registry, or file system on remote servers.", "Links": "https://dbatools.io/Get-DbaCmConnection", "Synopsis": "Retrieves cached Windows Management and CIM connections used by dbatools commands", "Availability": "Windows only", "Params": [ [ "ComputerName", "Filters cached connections by computer name or server name. Supports wildcards for pattern matching.\r\nUse this to check connections to specific SQL Server hosts or to search for connections matching a pattern like \"sql*prod*\".", "Filter", false, "true (ByValue)", "*", "" ], [ "UserName", "Filters cached connections by the username in the stored credentials. Supports wildcards for pattern matching.\r\nUse this to find connections using specific service accounts or domain credentials. Will not match connections using integrated Windows authentication.", "", false, "false", "*", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "ComputerManagement", "CIM" ], "CommandName": "Get-DbaCmObject", "Name": "Get-DbaCmObject", "Author": "Friedrich Weinmann (@FredWeinmann)", "Syntax": "Get-DbaCmObject [-ClassName] \u003cString\u003e [-ComputerName \u003cDbaCmConnectionParameter[]\u003e] [-Credential \u003cPSCredential\u003e] [-Namespace \u003cString\u003e] [-DoNotUse {None | CimRM | CimDCOM | Wmi | PowerShellRemoting}] [-Force] [-SilentlyContinue] [-EnableException] [\u003cCommonParameters\u003e]\nGet-DbaCmObject -Query \u003cString\u003e [-ComputerName \u003cDbaCmConnectionParameter[]\u003e] [-Credential \u003cPSCredential\u003e] [-Namespace \u003cString\u003e] [-DoNotUse {None | CimRM | CimDCOM | Wmi | PowerShellRemoting}] [-Force] [-SilentlyContinue] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.Management.ManagementObject or Microsoft.Management.Infrastructure.CimInstance\nReturns WMI or CIM objects matching the specified class or query. The exact type and properties depend on the WMI/CIM class being queried (e.g., Win32_OperatingSystem, Win32_ComputerSystem, \r\nWin32_Service, etc.).\nThe function automatically uses the most efficient connection method available on the target system (CIM over WinRM, CIM over DCOM, WMI, or PowerShell Remoting with WMI fallback) and returns the \r\nnative WMI/CIM object with all properties exposed by that class.\nCommon examples of returned object properties (varies by class):\r\n- For Win32_OperatingSystem: Name, Caption, Version, BuildNumber, OSArchitecture, FreePhysicalMemory, TotalVisibleMemorySize, SystemDrive, WindowsDirectory\r\n- For Win32_ComputerSystem: Name, DNSHostName, Domain, Manufacturer, Model, SystemType, NumberOfProcessors, NumberOfLogicalProcessors, TotalPhysicalMemory\r\n- For Win32_Service: Name, DisplayName, State, StartMode, Status, PathName, StartName, Description\r\n- For Win32_LogicalDisk: Name, FileSystem, FreeSpace, Size, Description, VolumeSerialNumber\nUse Select-Object * to display all available properties for the queried class. Properties available on the returned object depend on what the target WMI/CIM class exposes.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaCmObject win32_OperatingSystem\nRetrieves the common operating system information from the local computer.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaCmObject -Computername \"sql2014\" -ClassName Win32_OperatingSystem -Credential $cred -DoNotUse CimRM\nRetrieves the common operating system information from the server sql2014.\r\nIt will use the Credentials stored in $cred to connect, unless they are known to not work, in which case they will default to windows credentials (unless another default has been set).", "Description": "Queries Windows Management Instrumentation (WMI) or Common Information Model (CIM) classes on SQL Server hosts to gather system-level information like hardware specs, operating system details, services, and performance counters. This function automatically tries multiple connection protocols in order of preference (CIM over WinRM, CIM over DCOM, WMI, then WMI over PowerShell Remoting) and remembers which methods work for each server to optimize future connections.\n\nEssential for collecting host-level information that complements SQL Server monitoring, such as checking available memory, CPU utilization, disk space, or Windows service status across your SQL Server infrastructure. The intelligent credential and connection caching prevents repeated authentication failures and speeds up bulk operations across multiple servers.\n\nMuch of its behavior can be configured using Test-DbaCmConnection to pre-test and configure optimal connection methods for your environment.", "Links": "https://dbatools.io/Get-DbaCmObject", "Synopsis": "Retrieves Windows system information from SQL Server hosts using WMI/CIM with intelligent connection fallback.", "Availability": "Windows only", "Params": [ [ "ClassName", "Specifies the WMI or CIM class name to query from the target servers. Common classes include Win32_OperatingSystem for OS details, Win32_ComputerSystem for hardware info, or Win32_Service for Windows \r\nservices.\r\nUse this when you need to retrieve all instances and properties of a specific Windows management class across your SQL Server infrastructure.", "Class", true, "false", "", "" ], [ "Query", "Specifies a custom WQL (WMI Query Language) query to execute against the target servers. Allows for complex filtering and specific property selection beyond simple class retrieval.\r\nUse this when you need advanced filtering like \"SELECT Name, State FROM Win32_Service WHERE StartMode=\u0027Auto\u0027\" to get specific data rather than entire class instances.", "", true, "false", "", "" ], [ "ComputerName", "Specifies the target computer names or SQL Server host names to query for Windows management information. Accepts multiple values and pipeline input.\r\nDefaults to the local machine when not specified, but typically used to gather system-level data from remote SQL Server hosts for infrastructure monitoring.", "", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Credentials to use. Invalid credentials will be stored in a credentials cache and not be reused.", "", false, "false", "", "" ], [ "Namespace", "Specifies the WMI namespace path where the target class or query should be executed. The default \"root\\cimv2\" contains most Windows system classes.\r\nChange this when querying specialized namespaces like \"root\\SQLSERVER\" for SQL Server-specific WMI classes or \"root\\MSCluster\" for cluster information.", "", false, "false", "root\\cimv2", "" ], [ "DoNotUse", "Excludes specific connection protocols from the automatic fallback sequence. Valid values are CimRM, CimDCOM, Wmi, and PowerShellRemoting.\r\nUse this when certain protocols are blocked by network policies or cause issues in your environment, forcing the function to skip problematic connection methods.", "", false, "false", "None", "" ], [ "Force", "Bypasses timeout protections on connections that have previously failed, allowing retry attempts on servers marked as problematic.\r\nUse this when you suspect connection issues have been resolved or when you need to override cached failure states during troubleshooting.", "", false, "false", "False", "" ], [ "SilentlyContinue", "Converts terminating connection failures into non-terminating errors when used with EnableException, allowing processing to continue with remaining servers.\r\nUse this when querying multiple servers where some may be unavailable, and you want to collect data from accessible servers rather than stopping on the first failure.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Certificate", "Security" ], "CommandName": "Get-DbaComputerCertificate", "Name": "Get-DbaComputerCertificate", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaComputerCertificate [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-Store] \u003cString[]\u003e] [[-Folder] \u003cString[]\u003e] [[-Type] \u003cString\u003e] [[-Path] \u003cString\u003e] [[-Thumbprint] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.Security.Cryptography.X509Certificates.X509Certificate2\nReturns one X509Certificate2 object per certificate found in the specified store and folder.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The name of the computer where the certificate is stored\r\n- Store: The certificate store location (CurrentUser or LocalMachine)\r\n- Folder: The certificate folder/container name (My, Root, AddressBook, etc.)\r\n- Name: The friendly name of the certificate (added via Add-Member)\r\n- DnsNameList: Collection of DNS names associated with the certificate\r\n- Thumbprint: The SHA-1 hash fingerprint uniquely identifying the certificate\r\n- NotBefore: DateTime when the certificate becomes valid\r\n- NotAfter: DateTime when the certificate expires\r\n- Subject: The distinguished name of the subject (entity the certificate is issued to)\r\n- Issuer: The distinguished name of the certificate issuer (CA that signed it)\r\n- Algorithm: The signature algorithm used by the certificate (added via Add-Member)\nAdditional properties available from the X509Certificate2 object:\r\n- PublicKey: The public key cryptographic information\r\n- PrivateKey: The private key (when available)\r\n- Version: The X.509 certificate version\r\n- SerialNumber: The serial number assigned by the issuer\r\n- SignatureAlgorithm: Algorithm details for the certificate signature\r\n- Extensions: Collection of certificate extensions\r\n- SignatureAlgorithmOid: Object identifier for the signature algorithm\r\n- IssuerName: X500DistinguishedName of the issuer\r\n- SubjectName: X500DistinguishedName of the subject\r\n- Verify: Method to verify the certificate", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaComputerCertificate\nGets computer certificates on localhost that are candidates for using with SQL Server\u0027s network encryption\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaComputerCertificate -ComputerName sql2016\nGets computer certificates on sql2016 that are candidates for using with SQL Server\u0027s network encryption\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaComputerCertificate -ComputerName sql2016 -Thumbprint 8123472E32AB412ED4288888B83811DB8F504DED, 04BFF8B3679BB01A986E097868D8D494D70A46D6\nGets computer certificates on sql2016 that match thumbprints 8123472E32AB412ED4288888B83811DB8F504DED or 04BFF8B3679BB01A986E097868D8D494D70A46D6", "Description": "Scans Windows certificate stores to find X.509 certificates suitable for enabling SQL Server network encryption. By default, returns only certificates with Server Authentication capability from the LocalMachine\\My store, which are the certificates SQL Server can actually use for TLS connections. This saves you from manually browsing certificate stores and checking enhanced key usage extensions when configuring Force Encryption or setting up secure SQL Server connections.", "Links": "https://dbatools.io/Get-DbaComputerCertificate", "Synopsis": "Retrieves X.509 certificates from Windows certificate stores that can be used for SQL Server TLS encryption", "Availability": "Windows only", "Params": [ [ "ComputerName", "Specifies the target computer(s) to scan for certificates. Defaults to localhost.\r\nUse this when you need to check certificates on remote SQL Server machines or when configuring network encryption across multiple instances.\r\nFor SQL Server clusters, specify each individual cluster node separately since certificates are stored per machine, not per cluster resource.", "", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Allows you to login to $ComputerName using alternative credentials.", "", false, "false", "", "" ], [ "Store", "Specifies which Windows certificate store location to search. Defaults to LocalMachine.\r\nUse LocalMachine for certificates that SQL Server service accounts can access, or CurrentUser for user-specific certificates.\r\nSQL Server typically requires certificates in LocalMachine store for network encryption to work properly.", "", false, "false", "LocalMachine", "" ], [ "Folder", "Specifies which certificate folder within the store to search. Defaults to My (Personal certificates).\r\nUse My for personal certificates with private keys, Root for trusted root certificates, or other folders based on certificate type.\r\nSQL Server network encryption typically uses certificates from the My folder since they contain the required private keys.", "", false, "false", "My", "" ], [ "Type", "Filters certificates by their intended usage. Service returns only certificates with Server Authentication capability, All returns every certificate.\r\nUse Service (default) to find certificates that SQL Server can actually use for network encryption and TLS connections.\r\nService certificates have the required Enhanced Key Usage extension (1.3.6.1.5.5.7.3.1) that enables them for server authentication scenarios.", "", false, "false", "Service", "All,Service" ], [ "Path", "Specifies the file system path to a certificate file (.cer, .crt, .pfx) to load and analyze.\r\nUse this when you need to examine a certificate file before installing it to a certificate store.\r\nThis bypasses the Store and Folder parameters since the certificate is loaded directly from the file system.", "", false, "false", "", "" ], [ "Thumbprint", "Filters results to return only certificates with the specified thumbprint(s). Accepts multiple thumbprints.\r\nUse this when you need to verify specific certificates exist or check their properties before configuring SQL Server network encryption.\r\nThe thumbprint is the unique SHA-1 hash identifier that SQL Server uses in its certificate configuration.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Management", "Computer", "OS" ], "CommandName": "Get-DbaComputerSystem", "Name": "Get-DbaComputerSystem", "Author": "Shawn Melton (@wsmelton), wsmelton.github.io", "Syntax": "Get-DbaComputerSystem [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-IncludeAws] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per computer specified, containing hardware and system information collected from WMI.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The resolved computer name\r\n- Domain: The domain name the computer belongs to\r\n- DomainRole: Role of the computer (Standalone Workstation, Member Workstation, Standalone Server, Member Server, Backup Domain Controller, or Primary Domain Controller)\r\n- Manufacturer: Hardware manufacturer name\r\n- Model: Hardware model name\r\n- SystemFamily: System family classification\r\n- SystemType: System type (e.g., \"x64-based PC\")\r\n- ProcessorName: Processor name from Win32_Processor\r\n- ProcessorCaption: Processor description from Win32_Processor\r\n- ProcessorMaxClockSpeed: Maximum processor speed in MHz\r\n- NumberLogicalProcessors: Number of logical processors (includes hyperthreading virtual cores)\r\n- NumberProcessors: Number of physical processor sockets\r\n- IsHyperThreading: Boolean indicating if hyperthreading is detected (logical processors \u003e physical processors)\r\n- TotalPhysicalMemory: Total physical memory as a DbaSize object (shows human-readable format)\r\n- IsSystemManagedPageFile: Boolean indicating if Windows manages the page file automatically\r\n- PendingReboot: Boolean indicating if the system has a pending reboot, or $null if reboot status could not be determined\nAdditional properties available but not shown by default:\r\n- SystemSkuNumber: System SKU number from hardware\r\n- IsDaylightSavingsTime: Boolean indicating if daylight saving time is enabled on the system\r\n- DaylightInEffect: Boolean indicating if daylight saving time is currently in effect\r\n- DnsHostName: DNS host name of the computer\r\n- AdminPasswordStatus: Administrator password status (Disabled, Enabled, Not Implemented, or Unknown)\nWhen -IncludeAws is specified and the computer is detected as an AWS EC2 instance, the following properties are added:\r\n- AwsAmiId: The AMI (Amazon Machine Image) ID\r\n- AwsIamRoleArn: The IAM instance profile ARN\r\n- AwsEc2InstanceId: The EC2 instance ID\r\n- AwsEc2InstanceType: The EC2 instance type (e.g., t2.large, m5.xlarge)\r\n- AwsAvailabilityZone: The AWS availability zone where the instance is located\r\n- AwsPublicHostName: The public hostname assigned to the EC2 instance", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaComputerSystem\nReturns information about the local computer\u0027s computer system\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaComputerSystem -ComputerName sql2016\nReturns information about the sql2016\u0027s computer system\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaComputerSystem -ComputerName sql2016 -IncludeAws\nReturns information about the sql2016\u0027s computer system and includes additional properties around the EC2 instance.", "Description": "Collects detailed system specifications including processor details, memory configuration, domain membership, and hardware information from target computers. This function is essential for SQL Server capacity planning, pre-installation system verification, and troubleshooting performance issues by providing complete hardware inventory data.\n\nThe function queries WMI classes (Win32_ComputerSystem and Win32_Processor) to gather CPU details, determines hyperthreading status, checks total physical memory, and identifies domain roles. It also detects pending reboots that could affect SQL Server operations and optionally retrieves AWS EC2 metadata for cloud-hosted instances.\n\nUse this command when documenting SQL Server environments, verifying system requirements before installations or upgrades, or investigating hardware-related performance bottlenecks.", "Links": "https://dbatools.io/Get-DbaComputerSystem", "Synopsis": "Retrieves comprehensive hardware and system information from Windows computers hosting SQL Server instances.", "Availability": "Windows only", "Params": [ [ "ComputerName", "Specifies the target computer(s) to collect system information from. Defaults to the local computer when not specified.\r\nUse this to inventory multiple SQL Server hosts at once or to gather system details from remote servers for capacity planning and troubleshooting.", "cn,host,Server", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Alternate credential object to use for accessing the target computer(s).", "", false, "false", "", "" ], [ "IncludeAws", "Retrieves additional AWS EC2 metadata when the target computer is hosted on Amazon Web Services. Adds properties like AMI ID, instance type, availability zone, and IAM role information.\r\nUse this switch when documenting cloud-hosted SQL Server environments or when you need AWS-specific details for compliance or cost management purposes.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": "Connection", "CommandName": "Get-DbaConnectedInstance", "Name": "Get-DbaConnectedInstance", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaConnectedInstance [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per cached connection in the dbatools connection pool, containing details about each active or recently used SQL Server connection.\nDefault display properties (via Select-DefaultView):\r\n- SqlInstance: The SQL Server instance identifier (computer\\instance or server name)\r\n- ConnectionType: The .NET type of the connection object (e.g., Microsoft.SqlServer.Management.Smo.Server or System.Data.SqlClient.SqlConnection)\r\n- ConnectionObject: The actual connection object used internally by dbatools\r\n- Pooled: Boolean indicating whether connection pooling is enabled for this connection\nAdditional properties available:\r\n- ConnectionString: The connection string used to establish the connection (with credentials redacted for security)\nUse Select-Object * to view all properties including the full ConnectionString.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaConnectedInstance\nGets all connected SQL Server instances\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaConnectedInstance | Select *\nGets all connected SQL Server instances and shows the associated connectionstrings as well", "Description": "Shows all SQL Server connections that are currently active or cached in your PowerShell session. When you connect to instances using dbatools commands like Connect-DbaInstance, those connections are stored in an internal cache for reuse. This command reveals what\u0027s in that cache, including connection details like whether pooling is enabled and the connection type (SMO server objects vs raw SqlConnection objects). Use this to track active connections before cleaning them up with Disconnect-DbaInstance or to troubleshoot connection-related issues in long-running scripts.", "Links": "https://dbatools.io/Get-DbaConnectedInstance", "Synopsis": "Returns SQL Server instances currently cached in the dbatools connection pool", "Availability": "Windows, Linux, macOS", "Params": [ ] }, { "Tags": "Connection", "CommandName": "Get-DbaConnection", "Name": "Get-DbaConnection", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaConnection [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per connection on each SQL Server instance. Each object contains detailed information about the connection and its statistics.\nProperties:\r\n- ComputerName: The name of the computer where SQL Server is running\r\n- InstanceName: The SQL Server instance name (MSSQLSERVER for default instance)\r\n- SqlInstance: The full SQL Server instance name (ComputerName\\InstanceName format)\r\n- SessionId: The session ID of the connection (integer)\r\n- MostRecentSessionId: The most recent session ID associated with this connection (integer)\r\n- ConnectTime: DateTime when the connection was established\r\n- Transport: The network transport protocol used (e.g., \"Named pipes\", \"TCP/IP\", \"Shared memory\")\r\n- ProtocolType: The protocol type used for the connection (e.g., \"TSQL\")\r\n- ProtocolVersion: The version of the protocol being used (integer)\r\n- EndpointId: The ID of the database mirroring endpoint (integer)\r\n- EncryptOption: Encryption status of the connection (e.g., \"ENCRYPT_ON\", \"ENCRYPT_OFF\")\r\n- AuthScheme: The authentication scheme used (e.g., \"WINDOWS\", \"SQL\")\r\n- NodeAffinity: The node affinity of the connection for non-uniform memory access (NUMA) systems (integer)\r\n- Reads: The number of read operations performed on this connection (integer)\r\n- Writes: The number of write operations performed on this connection (integer)\r\n- LastRead: DateTime of the most recent read operation on this connection\r\n- LastWrite: DateTime of the most recent write operation on this connection\r\n- PacketSize: The network packet size in bytes used for this connection (integer)\r\n- ClientNetworkAddress: The IP address or network address of the client connecting to SQL Server\r\n- ClientTcpPort: The TCP port used by the client to connect to SQL Server (integer)\r\n- ServerNetworkAddress: The IP address or network address of the server\u0027s network interface\r\n- ServerTcpPort: The TCP port on which SQL Server is listening (integer)\r\n- ConnectionId: The unique identifier for this connection (integer, GUID-based)\r\n- ParentConnectionId: The parent connection ID for connections that are part of a hierarchy (integer)\r\n- MostRecentSqlHandle: The SQL handle of the most recently executed statement (binary)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaConnection -SqlInstance sql2016, sql2017\nReturns client connection information from sql2016 and sql2017", "Description": "Returns a bunch of information from dm_exec_connections which, according to Microsoft:\n\"Returns information about the connections established to this instance of SQL Server and the details of each connection. Returns server wide connection information for SQL Server. Returns current database connection information for SQL Database.\"", "Links": "https://dbatools.io/Get-DbaConnection", "Synopsis": "Returns a bunch of information from dm_exec_connections.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. Server(s) must be SQL Server 2005 or higher.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "Credential,Cred", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Diagnostic", "Buffer", "CPU" ], "CommandName": "Get-DbaCpuRingBuffer", "Name": "Get-DbaCpuRingBuffer", "Author": "Patrick Flynn (@sqllensman)", "Syntax": "Get-DbaCpuRingBuffer [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-CollectionMinutes] \u003cInt32\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per minute of CPU ring buffer data retrieved from the SQL Server instance.\nProperties:\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- RecordId: The unique record identifier from the ring buffer entry\r\n- EventTime: DateTime of the CPU sample (in local server time)\r\n- SQLProcessUtilization: Percentage of CPU used by the SQL Server process (0-100)\r\n- SystemIdle: Percentage of CPU that is idle (0-100)\r\n- OtherProcessUtilization: Percentage of CPU used by other processes (0-100), calculated as 100 - SystemIdle - SQLProcessUtilization", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaCpuRingBuffer -SqlInstance sql2008, sqlserver2012\nGets CPU Statistics from sys.dm_os_ring_buffers for servers sql2008 and sqlserver2012 for last 60 minutes.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaCpuRingBuffer -SqlInstance sql2008 -CollectionMinutes 240\nGets CPU Statistics from sys.dm_os_ring_buffers for server sql2008 for last 240 minutes\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$output = Get-DbaCpuRingBuffer -SqlInstance sql2008 -CollectionMinutes 240 | Select-Object * | ConvertTo-DbaDataTable\nGets CPU Statistics from sys.dm_os_ring_buffers for server sql2008 for last 240 minutes into a Data Table.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e\u0027sql2008\u0027,\u0027sql2012\u0027 | Get-DbaCpuRingBuffer\nGets CPU Statistics from sys.dm_os_ring_buffers for servers sql2008 and sqlserver2012\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Get-DbaCpuRingBuffer -SqlInstance sql2008 -SqlCredential $cred\nConnects using sqladmin credential and returns CPU Statistics from sys.dm_os_ring_buffers from sql2008", "Description": "This command queries sys.dm_os_ring_buffers to extract detailed CPU utilization history for performance troubleshooting and capacity planning. Based on Glen Berry\u0027s diagnostic query, it provides minute-by-minute CPU usage breakdowns that help identify performance patterns and resource contention.\n\nThe ring buffer stores CPU utilization data in one-minute increments for up to 256 minutes, tracking three key metrics: SQL Server process utilization, other processes utilization, and system idle time. This historical data is invaluable when investigating performance issues, establishing baselines, or determining if high CPU usage originates from SQL Server or other system processes.\n\nUse this function to analyze CPU trends during specific time periods, correlate CPU spikes with application events, or gather evidence for capacity planning decisions without requiring external monitoring tools.\n\nReference: https://www.sqlskills.com/blogs/glenn/sql-server-diagnostic-information-queries-detailed-day-16//", "Links": "https://dbatools.io/Get-DbaCpuRingBuffer", "Synopsis": "Retrieves historical CPU utilization data from SQL Server\u0027s internal ring buffer for performance analysis", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "Allows you to specify a comma separated list of servers to query.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance. To use:\r\n$cred = Get-Credential, this pass this $cred to the param.\nWindows Authentication will be used if DestinationSqlCredential is not specified. To connect as a different Windows user, run PowerShell as that user.", "", false, "false", "", "" ], [ "CollectionMinutes", "Specifies how many minutes of historical CPU data to retrieve from the ring buffer. Defaults to 60 minutes.\r\nUse this to extend the analysis window when investigating longer-term CPU trends or to focus on recent activity with shorter periods. Maximum available history is typically 256 minutes depending on \r\nsystem activity.", "", false, "false", "60", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Diagnostic", "Performance", "CPU" ], "CommandName": "Get-DbaCpuUsage", "Name": "Get-DbaCpuUsage", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaCpuUsage [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [[-Threshold] \u003cInt32\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Win32_PerfFormattedData_PerfProc_Thread (with added properties)\nReturns one object per Windows thread of SQL Server processes with CPU usage at or above the specified threshold.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Name: The thread identifier in format \u0027ProcessName_ProcessID_ThreadID\u0027\r\n- ContextSwitchesPersec: Number of context switches per second for this thread\r\n- ElapsedTime: Time in seconds since the thread was created\r\n- IDProcess: Windows process ID (PID) of the SQL Server process\r\n- Spid: SQL Server session ID (SPID) associated with this thread\r\n- PercentPrivilegedTime: Percentage of time thread spent in privileged mode\r\n- PercentProcessorTime: Percentage of total processor time consumed by this thread\r\n- PercentUserTime: Percentage of time thread spent in user mode\r\n- PriorityBase: The base priority of the thread\r\n- PriorityCurrent: The current priority of the thread\r\n- StartAddress: Memory address where the thread code begins execution\r\n- ThreadStateValue: Human-readable description of the thread state (e.g., \u0027Running\u0027, \u0027Waiting\u0027)\r\n- ThreadWaitReasonValue: Human-readable description of the wait reason if thread is waiting\r\n- Process: Associated SQL Server process object from Get-DbaProcess\r\n- Query: The last T-SQL query executed by the process\nAdditional properties available (from Win32_PerfFormattedData_PerfProc_Thread):\r\n- IDThread: Windows thread ID\r\n- ThreadState: Numeric value representing thread state (0=Initialized, 1=Ready, 2=Running, 3=Standby, 4=Terminated, 5=Waiting, 6=Transition, 7=Unknown)\r\n- ThreadWaitReason: Numeric value representing the reason the thread is waiting\nAll properties from the Win32_PerfFormattedData_PerfProc_Thread WMI class are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaCpuUsage -SqlInstance sql2017\nLogs into the SQL Server instance \"sql2017\" and also the Computer itself (via WMI) to gather information\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$usage = Get-DbaCpuUsage -SqlInstance sql2017\nPS C:\\\u003e $usage.Process\nExplores the processes (from Get-DbaProcess) associated with the usage results\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaCpuUsage -SqlInstance sql2017 -SqlCredential sqladmin -Credential ad\\sqldba\nLogs into the SQL instance using the SQL Login \u0027sqladmin\u0027 and then Windows instance as \u0027ad\\sqldba\u0027", "Description": "When CPU usage is high on your SQL Server, it can be difficult to pinpoint which specific SQL queries or processes are responsible using standard SQL Server tools alone. This function bridges that gap by correlating SQL Server process IDs (SPIDs) with Windows kernel process IDs (KPIDs) through system DMVs and Windows performance counters.\n\nThe function queries both SQL Server\u0027s process information and Windows thread performance data, then matches them together to show you exactly which SQL queries are consuming CPU at the operating system level. This is particularly valuable during performance troubleshooting when you need to identify the root cause of high CPU usage.\n\nResults include detailed thread information such as processor time percentages, thread states, wait reasons, and the actual SQL queries being executed. You can also set a CPU threshold to focus only on processes exceeding a specific percentage.\n\nReferences: https://www.mssqltips.com/sqlservertip/2454/how-to-find-out-how-much-cpu-a-sql-server-process-is-really-using/\n\nNote: This command returns results from all SQL instances on the destination server but the process\ncolumn is specific to -SqlInstance passed.", "Links": "https://dbatools.io/Get-DbaCpuUsage", "Synopsis": "Correlates SQL Server processes with Windows threads to identify which queries are consuming CPU resources", "Availability": "Windows only", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Credential", "Allows you to login to the Windows Server using alternative credentials.", "", false, "false", "", "" ], [ "Threshold", "Filters results to only show SQL Server threads with CPU usage at or above this percentage.\r\nUse this to focus on high-CPU consuming processes and ignore idle or low-activity threads during performance troubleshooting.", "", false, "false", "0", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Security", "Credential" ], "CommandName": "Get-DbaCredential", "Name": "Get-DbaCredential", "Author": "Garry Bargsley (@gbargsley), blog.garrybargsley.com", "Syntax": "Get-DbaCredential [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cString[]\u003e] [[-ExcludeCredential] \u003cString[]\u003e] [[-Identity] \u003cString[]\u003e] [[-ExcludeIdentity] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Credential\nReturns one Credential object per credential found on the target SQL Server instance(s). This object represents SQL Server credentials stored in the database that are used for external resource \r\naccess and authentication.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- ID: Unique identifier for the credential within SQL Server\r\n- Name: The name of the SQL Server credential\r\n- Identity: The Windows identity, login, or external identity the credential uses (e.g., domain\\account or Azure URI)\r\n- MappedClassType: The credential class type (None or CryptographicProvider for EKM)\r\n- ProviderName: The name of the cryptographic provider (if MappedClassType is CryptographicProvider)\nAdditional properties available (from SMO Credential object):\r\n- CreateDate: DateTime when the credential was created\r\n- DateLastModified: DateTime when the credential was last modified\r\n- Parent: The Server object containing this credential\r\n- Properties: Collection of extended properties assigned to the credential\r\n- Urn: Uniform Resource Name identifier for the credential\r\n- State: The current state of the SMO object\nAll properties from the base SMO Credential object are accessible even though only default properties are displayed without using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaCredential -SqlInstance localhost\nReturns all SQL Credentials on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaCredential -SqlInstance localhost, sql2016 -Name \u0027PowerShell Proxy\u0027\nReturns the SQL Credentials named \u0027PowerShell Proxy\u0027 for the local and sql2016 SQL Server instances\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaCredential -SqlInstance localhost, sql2016 -Identity ad\\powershell\nReturns the SQL Credentials for the account \u0027ad\\powershell\u0027 on the local and sql2016 SQL Server instances", "Description": "Retrieves SQL Server Credentials that are stored securely on the server and used by SQL Server services to authenticate to external resources like file shares, web services, or other SQL Server instances. These credentials are essential for operations like backups to network locations, accessing external data sources, or running SQL Agent jobs that interact with external systems. The function returns detailed information about each credential including its name, associated identity, and provider configuration.", "Links": "https://dbatools.io/Get-DbaCredential", "Synopsis": "Retrieves SQL Server Credentials configured for external authentication and resource access.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function\r\nto be executed against multiple SQL Server instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Credential", "Filters results to only include SQL Server credentials with specific names. Accepts multiple credential names and supports wildcards.\r\nUse this when you need to check configuration for specific credentials like backup service accounts or external data source connections.\r\nEnclose names with spaces in quotes, such as \"My Backup Credential\".", "Name", false, "false", "", "" ], [ "ExcludeCredential", "Excludes SQL Server credentials with specified names from the results. Accepts multiple credential names to filter out.\r\nUseful when auditing all credentials except system or known service credentials that don\u0027t require review.", "ExcludeName", false, "false", "", "" ], [ "Identity", "Filters results to only include credentials that use specific Windows identities or SQL logins. Accepts multiple identity names.\r\nUse this to find all credentials associated with a particular service account or user across different credential objects.\r\nEnclose identities with spaces in quotes, such as \"DOMAIN\\Service Account\".", "CredentialIdentity", false, "false", "", "" ], [ "ExcludeIdentity", "Excludes credentials that use specified Windows identities or SQL logins from the results. Accepts multiple identity names.\r\nHelpful when auditing credentials but excluding known system accounts or service identities from the output.", "ExcludeCredentialIdentity", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "General", "Error" ], "CommandName": "Get-DbaCustomError", "Name": "Get-DbaCustomError", "Author": "Garry Bargsley (@gbargsley), blog.garrybargsley.com", "Syntax": "Get-DbaCustomError [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.UserDefinedMessage\nReturns one UserDefinedMessage object per custom error message found in sys.messages on the target SQL Server instance(s). When multiple instances are specified, all custom errors from all instances \r\nare returned.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server host\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- ID: The custom error message ID (50001-2147483647)\r\n- Text: The text of the custom error message (max 255 characters)\r\n- LanguageID: The language ID (numeric identifier from sys.syslanguages)\r\n- Language: The language name (e.g., \"English\", \"French\", \"Deutsch\")\nAdditional properties available (from SMO UserDefinedMessage object):\r\n- Severity: The severity level of the error (1-25 integer)\r\n- IsLogged: Boolean indicating if the error is logged to the Windows Application and SQL Server error logs\r\n- Parent: Reference to the parent SMO Server object\nAll properties from the base SMO object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaCustomError -SqlInstance localhost\nReturns all Custom Error Message(s) on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaCustomError -SqlInstance localhost, sql2016\nReturns all Custom Error Message(s) for the local and sql2016 SQL Server instances", "Description": "Retrieves all custom error messages that have been added to SQL Server using sp_addmessage or through SQL Server Management Studio. These user-defined error messages are stored in the sys.messages system catalog and are commonly used by applications for business logic validation and custom error handling. This function helps DBAs inventory custom errors across multiple instances during migrations, troubleshooting, or compliance audits.", "Links": "https://dbatools.io/Get-DbaCustomError", "Synopsis": "Retrieves user-defined error messages from SQL Server instances for auditing and documentation.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function\r\nto be executed against multiple SQL Server instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": "Database", "CommandName": "Get-DbaDatabase", "Name": "Get-DbaDatabase", "Author": "Garry Bargsley (@gbargsley), blog.garrybargsley.com | Klaas Vandenberghe (@PowerDbaKlaas) | Simone Bizzotto (@niphlod)", "Syntax": "Get-DbaDatabase [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-ExcludeDatabase] \u003cString[]\u003e] [[-Pattern] \u003cString[]\u003e] [-ExcludeUser] [-ExcludeSystem] [[-Owner] \u003cString[]\u003e] [-Encrypted] [[-Status] \u003cString[]\u003e] [[-Access] \u003cString\u003e] [[-RecoveryModel] \u003cString[]\u003e] [-NoFullBackup] [[-NoFullBackupSince] \u003cDateTime\u003e] [-NoLogBackup] [[-NoLogBackupSince] \u003cDateTime\u003e] [-EnableException] [-IncludeLastUsed] [-OnlyAccessible] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Database\nReturns one SMO Database object for each database on the specified instances matching the filter criteria.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Name: Database name\r\n- Status: Current database status (EmergencyMode, Normal, Offline, Recovering, RecoveryPending, Restoring, Standby, Suspect)\r\n- IsAccessible: Boolean indicating if the database is currently accessible\r\n- RecoveryModel: Database recovery model (Full, Simple, BulkLogged)\r\n- LogReuseWaitStatus: Status of transaction log reuse (LogSwitch, ChkptBkup, ActiveBkup, ActiveTran, etc.)\r\n- Size: Database size in megabytes (MB)\r\n- Compatibility: Database compatibility level (numeric value representing SQL Server version)\r\n- Collation: Database collation setting\r\n- Owner: Database owner login name\r\n- Encrypted: Boolean indicating if Transparent Data Encryption (TDE) is enabled\r\n- LastFullBackup: DateTime of the most recent full backup\r\n- LastDiffBackup: DateTime of the most recent differential backup\r\n- LastLogBackup: DateTime of the most recent transaction log backup\nWhen -NoFullBackup or -NoFullBackupSince is specified, an additional property is included:\r\n- BackupStatus: String indicating backup state (e.g., \"Only CopyOnly backups\", $null for normal backups)\nWhen -IncludeLastUsed is specified, additional properties are included:\r\n- LastIndexRead: DateTime of last read operation from sys.dm_db_index_usage_stats\r\n- LastIndexWrite: DateTime of last write operation from sys.dm_db_index_usage_stats\nAdditional properties available (from SMO Database object):\r\n- IsCdcEnabled: Boolean indicating if Change Data Capture is enabled (SQL Server 2008+)\r\n- And all other standard SMO Database properties (use Select-Object * to see all)\nAll properties from the base SMO Database object are accessible via Select-Object even though only default properties are displayed without using the -Property parameter.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance localhost\nReturns all databases on the local default SQL Server instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance localhost -ExcludeUser\nReturns only the system databases on the local default SQL Server instance.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance localhost -ExcludeSystem\nReturns only the user databases on the local default SQL Server instance.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e\u0027localhost\u0027,\u0027sql2016\u0027 | Get-DbaDatabase\nReturns databases on multiple instances piped into the function.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance SQL1\\SQLExpress -RecoveryModel full,Simple\nReturns only the user databases in Full or Simple recovery model from SQL Server instance SQL1\\SQLExpress.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance SQL1\\SQLExpress -Status Normal\nReturns only the user databases with status \u0027normal\u0027 from SQL Server instance SQL1\\SQLExpress.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance SQL1\\SQLExpress -IncludeLastUsed\nReturns the databases from SQL Server instance SQL1\\SQLExpress and includes the last used information\r\nfrom the sys.dm_db_index_usage_stats DMV.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance SQL1\\SQLExpress,SQL2 -ExcludeDatabase model,master\nReturns all databases except master and model from SQL Server instances SQL1\\SQLExpress and SQL2.\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance SQL1\\SQLExpress,SQL2 -Encrypted\nReturns only databases using TDE from SQL Server instances SQL1\\SQLExpress and SQL2.\n-------------------------- EXAMPLE 10 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance SQL1\\SQLExpress,SQL2 -Access ReadOnly\nReturns only read only databases from SQL Server instances SQL1\\SQLExpress and SQL2.\n-------------------------- EXAMPLE 11 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance SQL2,SQL3 -Database OneDB,OtherDB\nReturns databases \u0027OneDb\u0027 and \u0027OtherDB\u0027 from SQL Server instances SQL2 and SQL3 if databases by those names exist on those instances.\n-------------------------- EXAMPLE 12 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance SQL2,SQL3 -Pattern \"^dbatools_\"\nReturns all databases that match the regex pattern \"^dbatools_\" (e.g., dbatools_example1, dbatools_example2) from SQL Server instances SQL2 and SQL3.", "Description": "Retrieves detailed database information from one or more SQL Server instances, returning rich database objects instead of basic metadata queries.\nThis command provides comprehensive filtering options for database status, access type, recovery model, backup history, and encryption status, making it essential for database inventory, compliance auditing, and maintenance planning.\nUnlike querying sys.databases directly, this returns full SMO database objects with calculated properties for backup status, usage statistics from DMVs, and consistent formatting across SQL Server versions.\nSupports both on-premises SQL Server (2000+) and Azure SQL Database with automatic compatibility handling.", "Links": "https://dbatools.io/Get-DbaDatabase", "Synopsis": "Retrieves database objects and metadata from SQL Server instances with advanced filtering and usage analytics.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies one or more databases to include in the results using exact name matching.\r\nUse this when you need to retrieve specific databases instead of all databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies one or more databases to exclude from the results using exact name matching.\r\nUse this to filter out specific databases like test or staging environments from your inventory.", "", false, "false", "", "" ], [ "Pattern", "Specifies a pattern for filtering databases using regular expressions.\r\nUse this when you need to match databases by pattern, such as \"^dbatools_\" or \".*_prod$\".\r\nThis parameter supports standard .NET regular expression syntax.", "", false, "false", "", "" ], [ "ExcludeUser", "Returns only system databases (master, model, msdb, tempdb).\r\nUse this when you need to focus on system database maintenance tasks or validation.\r\nThis parameter cannot be used with -ExcludeSystem.", "SystemDbOnly,NoUserDb,ExcludeAllUserDb", false, "false", "False", "" ], [ "ExcludeSystem", "Returns only user databases, excluding system databases (master, model, msdb, tempdb).\r\nUse this when you need to focus on application databases for maintenance, backup, or compliance reporting.\r\nThis parameter cannot be used with -ExcludeUser.", "UserDbOnly,NoSystemDb,ExcludeAllSystemDb", false, "false", "False", "" ], [ "Owner", "Filters databases by their database owner (the principal listed as the database owner).\r\nUse this to find databases owned by specific accounts for security auditing or ownership cleanup.\r\nAccepts login names like \u0027sa\u0027, \u0027DOMAIN\\user\u0027, or service account names.", "", false, "false", "", "" ], [ "Encrypted", "Returns only databases with Transparent Data Encryption (TDE) enabled.\r\nUse this for compliance reporting or to verify which databases have encryption configured for data protection.", "", false, "false", "False", "" ], [ "Status", "Filters databases by their current operational status. Returns only databases matching the specified status values.\r\nUse this to identify databases requiring attention (Suspect, Offline) or in specific states for maintenance planning.\r\nValid options: EmergencyMode, Normal, Offline, Recovering, RecoveryPending, Restoring, Standby, Suspect.", "", false, "false", "@(\u0027EmergencyMode\u0027, \u0027Normal\u0027, \u0027Offline\u0027, \u0027Recovering\u0027, \u0027RecoveryPending\u0027, \u0027Restoring\u0027, \u0027Standby\u0027, \u0027Suspect\u0027)", "EmergencyMode,Normal,Offline,Recovering,RecoveryPending,Restoring,Standby,Suspect" ], [ "Access", "Filters databases by their read/write access mode. Returns only databases set to the specified access type.\r\nUse ReadOnly to find reporting databases or those temporarily set to read-only for maintenance.\r\nValid options: ReadOnly, ReadWrite.", "", false, "false", "", "ReadOnly,ReadWrite" ], [ "RecoveryModel", "Filters databases by their recovery model setting, which controls transaction log behavior and backup capabilities.\r\nUse this to verify recovery model consistency or find databases needing model changes for backup strategy compliance.\r\nValid options: Full (point-in-time recovery), Simple (no log backups), BulkLogged (minimal logging for bulk operations).", "", false, "false", "@(\u0027Full\u0027, \u0027Simple\u0027, \u0027BulkLogged\u0027)", "Full,Simple,BulkLogged" ], [ "NoFullBackup", "Returns only databases that have never had a full backup or only have CopyOnly full backups recorded in msdb.\r\nUse this to identify databases at risk due to missing backup coverage for disaster recovery planning.", "", false, "false", "False", "" ], [ "NoFullBackupSince", "Returns databases that haven\u0027t had a full backup since the specified date and time.\r\nUse this to identify databases with stale backups that may violate your backup policy or RTO requirements.", "", false, "false", "", "" ], [ "NoLogBackup", "Returns databases in Full or BulkLogged recovery model that have never had a transaction log backup.\r\nUse this to identify databases where transaction logs may be growing unchecked due to missing log backup strategy.", "", false, "false", "False", "" ], [ "NoLogBackupSince", "Returns databases that haven\u0027t had a transaction log backup since the specified date and time.\r\nUse this to find databases with overdue log backups that may cause transaction log growth or RPO violations.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "IncludeLastUsed", "Adds LastRead and LastWrite columns showing when databases were last accessed based on index usage statistics.\r\nUse this to identify unused or rarely accessed databases for decommissioning or archival decisions.\r\nData is retrieved from sys.dm_db_index_usage_stats and resets when SQL Server restarts.", "", false, "false", "False", "" ], [ "OnlyAccessible", "Returns only databases that are currently accessible, excluding offline or inaccessible databases.\r\nUse this to improve performance when you only need databases that can be queried, providing significant speedup for SMO enumeration.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Assembly", "Database" ], "CommandName": "Get-DbaDbAssembly", "Name": "Get-DbaDbAssembly", "Author": "Garry Bargsley (@gbargsley), blog.garrybargsley.com", "Syntax": "Get-DbaDbAssembly [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-Name] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Assembly\nReturns one Assembly object for each CLR assembly found in the specified or accessible databases.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: The database name containing the assembly\r\n- ID: Unique identifier for the assembly\r\n- Name: Name of the assembly\r\n- Owner: The principal that owns the assembly\r\n- SecurityLevel: Assembly security level (Safe, ExternalAccess, or Unsafe)\r\n- CreateDate: DateTime when the assembly was created\r\n- IsSystemObject: Boolean indicating if the assembly is a system object\r\n- Version: Version information of the assembly\nAdditional properties available (from SMO Assembly object):\r\n- DatabaseId: Unique identifier for the database containing the assembly\r\n- FilePath: File path associated with the assembly\r\n- AssemblySecurityLevel: Same as SecurityLevel property\nAll properties from the base SMO Assembly object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbAssembly -SqlInstance localhost\nReturns all Database Assembly on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbAssembly -SqlInstance localhost, sql2016\nReturns all Database Assembly for the local and sql2016 SQL Server instances\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbAssembly -SqlInstance Server1 -Database MyDb -Name MyTechCo.Houids.SQLCLR\nWill fetch details for the MyTechCo.Houids.SQLCLR assembly in the MyDb Database on the Server1 instance", "Description": "Retrieves detailed information about Common Language Runtime (CLR) assemblies that have been registered in SQL Server databases. This function helps DBAs audit custom .NET assemblies for security compliance, track assembly versions, and identify potentially unsafe or unauthorized code deployed to their SQL Server instances. Returns key properties including assembly security level, owner, creation date, and version information across all accessible databases.", "Links": "https://dbatools.io/Get-DbaDbAssembly", "Synopsis": "Retrieves CLR assemblies registered in SQL Server databases for security auditing and inventory management.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function\r\nto be executed against multiple SQL Server instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to scan for CLR assemblies. Accepts wildcards for pattern matching.\r\nUse this when auditing assemblies in specific databases rather than scanning the entire instance.", "", false, "false", "", "" ], [ "Name", "Filters results to assemblies with matching names. Supports exact assembly name matching only.\r\nUse this when investigating specific assemblies during security audits or troubleshooting CLR-related issues.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Certificate", "Security" ], "CommandName": "Get-DbaDbAsymmetricKey", "Name": "Get-DbaDbAsymmetricKey", "Author": "Stuart Moore (@napalmgram), stuart-moore.com", "Syntax": "Get-DbaDbAsymmetricKey [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-ExcludeDatabase] \u003cString[]\u003e] [[-Name] \u003cString[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.AsymmetricKey\nReturns one AsymmetricKey object per asymmetric key found in the specified databases. Each object represents a single asymmetric key stored in the database\u0027s encryption hierarchy.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: The database name containing the asymmetric key\r\n- Name: The name of the asymmetric key\r\n- Owner: The principal that owns the asymmetric key\r\n- KeyEncryptionAlgorithm: The encryption algorithm used for the key (RSA_512, RSA_1024, RSA_2048, RSA_3072, RSA_4096)\r\n- KeyLength: The length of the key in bits (512, 1024, 2048, 3072, or 4096)\r\n- PrivateKeyEncryptionType: How the private key is encrypted (NoEncryption, EncryptedByMasterKey, EncryptedByPassword)\r\n- Thumbprint: The thumbprint (fingerprint) of the asymmetric key for verification and identification\nAdditional properties available (from SMO AsymmetricKey object):\r\n- DatabaseId: Unique identifier of the database containing the key\r\n- And all other standard SMO AsymmetricKey properties (use Select-Object * to see all)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbAsymmetricKey -SqlInstance sql2016\nGets all Asymmetric Keys\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbAsymmetricKey -SqlInstance Server1 -Database db1\nGets the Asymmetric Keys for the db1 database\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbAsymmetricKey -SqlInstance Server1 -Database db1 -Name key1\nGets the key1 Asymmetric Key within the db1 database", "Description": "Retrieves asymmetric keys stored in SQL Server databases, including their encryption algorithms, key lengths, owners, and thumbprints.\nThis function is essential for security audits and encryption key management, allowing DBAs to inventory all asymmetric keys across databases without manually querying system catalogs.\nAsymmetric keys are used for encryption, digital signatures, and certificate creation in SQL Server\u0027s transparent data encryption and column-level encryption features.\nReturns detailed key properties to help with compliance reporting and security assessments.", "Links": "https://dbatools.io/Get-DbaDbAsymmetricKey", "Synopsis": "Retrieves asymmetric keys from SQL Server databases for encryption management and security auditing", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to scan for asymmetric keys. Accepts wildcards for pattern matching.\r\nUse this when you need to audit encryption keys in specific databases instead of scanning all databases on the instance.\r\nEssential for targeted security assessments or compliance audits of particular applications.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific databases from the asymmetric key scan. Accepts wildcards for pattern matching.\r\nUse this to skip system databases, test databases, or databases known to not contain encryption keys.\r\nHelps focus audits on production databases and reduces noise in security assessments.", "", false, "false", "", "" ], [ "Name", "Filters results to asymmetric keys with specific names. Accepts wildcards and multiple key names.\r\nUse this when tracking specific keys during key rotation, compliance audits, or troubleshooting encryption issues.\r\nCommon when validating that required encryption keys exist across multiple databases.", "", false, "false", "", "" ], [ "InputObject", "Accepts database objects from the pipeline, typically from Get-DbaDatabase.\r\nUse this to chain database filtering with key retrieval, such as getting keys from databases with specific properties.\r\nEnables advanced filtering scenarios like scanning only databases created after a certain date or with particular owners.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "DisasterRecovery", "Backup" ], "CommandName": "Get-DbaDbBackupHistory", "Name": "Get-DbaDbBackupHistory", "Author": "Chrissy LeMaire (@cl) | Stuart Moore (@napalmgram)", "Syntax": "Get-DbaDbBackupHistory -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-IncludeCopyOnly] [-Since \u003cPSObject\u003e] [-RecoveryFork \u003cString\u003e] [-Last] [-LastFull] [-LastDiff] [-LastLog] [-DeviceType \u003cString[]\u003e] [-Raw] [-LastLsn \u003cBigInteger\u003e] [-IncludeMirror] [-Type \u003cString[]\u003e] [-AgCheck] [-IgnoreDiffBackup] [-LsnSort \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]\nGet-DbaDbBackupHistory -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-IncludeCopyOnly] [-Force] [-Since \u003cPSObject\u003e] [-RecoveryFork \u003cString\u003e] [-Last] [-LastFull] [-LastDiff] [-LastLog] [-DeviceType \u003cString[]\u003e] [-Raw] [-LastLsn \u003cBigInteger\u003e] [-IncludeMirror] [-Type \u003cString[]\u003e] [-AgCheck] [-IgnoreDiffBackup] [-LsnSort \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.Data.DataRow (when -Raw is specified)\nReturns one DataRow per backup file from the MSDB backup tables, preserving the raw SQL Server structure. This is useful when you need to analyze individual backup files in a striped backup set or \r\nrequire access to all MSDB backup columns without object wrapping.\nAdditional property added to raw output:\r\n- FullName: Copy of the Path property for consistency with grouped output\nDataplat.Dbatools.Database.BackupHistory (default)\nReturns one BackupHistory object per backup set, with striped backups automatically grouped into a single object. The standard output is more practical for restore planning and backup analysis.\nDefault display properties (via table format):\r\n- SqlInstance: The SQL Server instance name\r\n- Database: Database name\r\n- Type: Backup type (Full, Log, Differential, File, Differential File, Partial Full, or Partial Differential)\r\n- TotalSize: Total uncompressed backup size in bytes\r\n- DeviceType: Storage device type (Disk, Tape, URL, Virtual Device, etc.)\r\n- Start: Backup start date and time\r\n- Duration: Duration of the backup operation\r\n- End: Backup completion date and time\nAll available properties on BackupHistory objects:\r\n- ComputerName: Computer name where SQL Server instance resides\r\n- InstanceName: SQL Server instance name\r\n- SqlInstance: Full SQL Server instance name (ComputerName\\InstanceName)\r\n- AvailabilityGroupName: Availability group name (if applicable)\r\n- Database: Database name\r\n- DatabaseId: SQL Server database ID\r\n- UserName: Windows or SQL login that performed the backup\r\n- Start: Backup start DateTime\r\n- End: Backup completion DateTime\r\n- Duration: TimeSpan duration of the backup\r\n- Path: Array of file paths for the backup files\r\n- TotalSize: Total uncompressed backup size in bytes\r\n- CompressedBackupSize: Compressed backup size in bytes (NULL for SQL 2005)\r\n- CompressionRatio: Ratio of total size to compressed size (1.0 for uncompressed)\r\n- Type: Backup type string\r\n- BackupSetId: Unique backup set identifier from MSDB\r\n- DeviceType: Backup device type (Disk, Tape, Pipe, Virtual Device, URL, etc.)\r\n- Software: Software that created the backup (e.g., \"Microsoft SQL Server\")\r\n- FullName: Array of backup file paths (same as Path)\r\n- FileList: Array of file objects with FileType, LogicalName, and PhysicalName properties\r\n- Position: Position of this backup in the media set\r\n- FirstLsn: First Log Sequence Number in the backup (string representation of binary(10))\r\n- DatabaseBackupLsn: LSN of the last database backup referenced by this backup\r\n- CheckpointLsn: LSN of the checkpoint at the time the backup was created\r\n- LastLsn: Last Log Sequence Number in the backup\r\n- SoftwareVersionMajor: Major version number of SQL Server that created the backup\r\n- IsCopyOnly: Boolean indicating if this is a copy-only backup\r\n- LastRecoveryForkGUID: Unique identifier of the last recovery fork\r\n- RecoveryModel: Database recovery model (Simple, Full, or Bulk-logged)\r\n- EncryptorThumbprint: Thumbprint of the certificate used for backup encryption (SQL 2014+)\r\n- EncryptorType: Encryption algorithm used (SQL 2014+)\r\n- KeyAlgorithm: Key algorithm used for encryption (SQL 2014+)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbBackupHistory -SqlInstance SqlInstance2014a\nReturns server name, database, username, backup type, date for all database backups still in msdb history on SqlInstance2014a. This may return many rows; consider using filters that are included in \r\nother examples.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nGet-DbaDbBackupHistory -SqlInstance SqlInstance2014a -SqlCredential $cred\nDoes the same as above but connect to SqlInstance2014a as SQL user \"sqladmin\"\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbBackupHistory -SqlInstance SqlInstance2014a -Database db1, db2 -Since ([DateTime]\u00272016-07-01 10:47:00\u0027)\nReturns backup information only for databases db1 and db2 on SqlInstance2014a since July 1, 2016 at 10:47 AM.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbBackupHistory -SqlInstance sql2014 -Database AdventureWorks2014, pubs -Force | Format-Table\nReturns information only for AdventureWorks2014 and pubs and formats the results as a table.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaDbBackupHistory -SqlInstance sql2014 -Database AdventureWorks2014 -Last\nReturns information about the most recent full, differential and log backups for AdventureWorks2014 on sql2014.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaDbBackupHistory -SqlInstance sql2014 -Database AdventureWorks2014 -Last -DeviceType Disk\nReturns information about the most recent full, differential and log backups for AdventureWorks2014 on sql2014, but only for backups to disk.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eGet-DbaDbBackupHistory -SqlInstance sql2014 -Database AdventureWorks2014 -Last -DeviceType 148,107\nReturns information about the most recent full, differential and log backups for AdventureWorks2014 on sql2014, but only for backups with device_type 148 and 107.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eGet-DbaDbBackupHistory -SqlInstance sql2014 -Database AdventureWorks2014 -LastFull\nReturns information about the most recent full backup for AdventureWorks2014 on sql2014.\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003eGet-DbaDbBackupHistory -SqlInstance sql2014 -Database AdventureWorks2014 -Type Full\nReturns information about all Full backups for AdventureWorks2014 on sql2014.\n-------------------------- EXAMPLE 10 --------------------------\nPS C:\\\u003eGet-DbaRegServer -SqlInstance sql2016 | Get-DbaDbBackupHistory\nReturns database backup information for every database on every server listed in the Central Management Server on sql2016.\n-------------------------- EXAMPLE 11 --------------------------\nPS C:\\\u003eGet-DbaDbBackupHistory -SqlInstance SqlInstance2014a, sql2016 -Force\nReturns detailed backup history for all databases on SqlInstance2014a and sql2016.\n-------------------------- EXAMPLE 12 --------------------------\nPS C:\\\u003eGet-DbaDbBackupHistory -SqlInstance sql2016 -Database db1 -RecoveryFork 38e5e84a-3557-4643-a5d5-eed607bef9c6 -Last\nIf db1 has multiple recovery forks, specifying the RecoveryFork GUID will restrict the search to that fork.", "Description": "Queries the MSDB database backup tables to extract detailed backup history information including file paths, sizes, compression ratios, and LSN sequences. Essential for compliance auditing, disaster recovery planning, and troubleshooting backup issues without having to manually query system tables. The function automatically groups striped backup sets into single objects and excludes copy-only backups by default, making the output more practical for restoration scenarios. You can filter results by database name, backup type, date range, or retrieve only the most recent backup chains needed for point-in-time recovery.\n\nReference: http://www.sqlhub.com/2011/07/find-your-backup-history-in-sql-server.html", "Links": "https://dbatools.io/Get-DbaDbBackupHistory", "Synopsis": "Retrieves backup history records from MSDB for analysis and compliance reporting.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Credential object used to connect to the SQL Server instance as a different user. This can be a Windows or SQL Server account. Windows users are determined by the existence of a backslash, so if you \r\nare intending to use an alternative Windows connection instead of a SQL login, ensure it contains a backslash.", "", false, "false", "", "" ], [ "Database", "Specifies one or more databases to include in the backup history search. Accepts wildcards for pattern matching.\r\nUse this when you need backup history for specific databases rather than all databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies one or more databases to exclude from the backup history search.\r\nUseful when you want history for most databases but need to skip system databases or specific user databases.", "", false, "false", "", "" ], [ "IncludeCopyOnly", "Includes copy-only backups in the results, which are normally excluded by default.\r\nCopy-only backups don\u0027t break the backup chain and are commonly used for ad-hoc backups or moving databases to other environments.", "", false, "false", "False", "" ], [ "Force", "Returns all columns from the MSDB backup tables instead of the filtered standard output.\r\nUse this when you need access to additional backup metadata fields for detailed analysis or troubleshooting.", "", false, "false", "False", "" ], [ "Since", "Filters backup history to only include backups taken after the specified date and time.\r\nAccepts DateTime objects or TimeSpan objects (which get added to the current time). Times are compared using the SQL Server instance\u0027s timezone.\r\nEssential for limiting results when dealing with databases that have extensive backup history.", "", false, "false", "([DateTime]::ParseExact(\"1970-01-01\", \"yyyy-MM-dd\", [System.Globalization.CultureInfo]::InvariantCulture))", "" ], [ "RecoveryFork", "Filters results to a specific recovery fork GUID when a database has multiple recovery paths.\r\nUse this when a database has been restored from different backup chains or has experienced recovery fork scenarios, ensuring you get the correct backup sequence.", "", false, "false", "", "" ], [ "Last", "Returns the most recent complete backup chain (full, differential, and log backups) needed for point-in-time recovery.\r\nThis provides the exact backup sequence you\u0027d need to restore a database to its most current state.", "", false, "false", "False", "" ], [ "LastFull", "Returns only the most recent full backup for each database.\r\nUse this to quickly identify the base backup needed for restore operations or to verify when the last full backup was taken.", "", false, "false", "False", "" ], [ "LastDiff", "Returns only the most recent differential backup for each database.\r\nUseful for verifying differential backup schedules or identifying the latest differential backup in a restore scenario.", "", false, "false", "False", "" ], [ "LastLog", "Returns only the most recent transaction log backup for each database.\r\nCritical for monitoring log backup frequency and identifying the latest point-in-time recovery option available.", "", false, "false", "False", "" ], [ "DeviceType", "Filters backups by device type such as \u0027Disk\u0027, \u0027Tape\u0027, \u0027URL\u0027, or \u0027Virtual Device\u0027.\r\nUse this to find backups stored on specific media types, particularly useful when backups go to different destinations like local disk vs cloud storage.", "", false, "false", "", "" ], [ "Raw", "Returns one object per backup file instead of grouping striped backup sets into single objects.\r\nUse this when you need to see individual backup file details for striped backups or need to analyze backup file distribution.", "", false, "false", "False", "" ], [ "LastLsn", "Filters to only include backups with LSNs greater than the specified value, improving query performance on large backup histories.\r\nUse this when you know the LSN range you\u0027re interested in, typically when building restore sequences or analyzing backup chains.", "", false, "false", "", "" ], [ "IncludeMirror", "Includes mirror backup copies in the results, which are excluded by default.\r\nUse this when you need to see all backup copies created through backup mirroring, useful for verifying mirror backup configurations.", "", false, "false", "False", "" ], [ "Type", "Filters results to specific backup types: \u0027Full\u0027, \u0027Log\u0027, \u0027Differential\u0027, \u0027File\u0027, \u0027Differential File\u0027, \u0027Partial Full\u0027, or \u0027Partial Differential\u0027.\r\nUse this to focus on particular backup types when analyzing backup strategies or troubleshooting specific backup issues.", "", false, "false", "", "Full,Log,Differential,File,Differential File,Partial Full,Partial Differential" ], [ "AgCheck", "Deprecated parameter. Use Get-DbaAgBackupHistory instead to retrieve backup history from all replicas in an Availability Group.\r\nThis parameter is maintained for backward compatibility but no longer functions.", "", false, "false", "False", "" ], [ "IgnoreDiffBackup", "Excludes differential backups from the results, showing only full and log backups.\r\nUseful when analyzing backup chains that don\u0027t use differential backups or when you want to focus on full and log backup patterns.", "", false, "false", "False", "" ], [ "LsnSort", "Determines which LSN column to use for sorting results: \u0027FirstLsn\u0027, \u0027DatabaseBackupLsn\u0027, or \u0027LastLsn\u0027 (default).\r\nUse this to control backup ordering when working with complex backup scenarios or when you need results sorted by specific LSN checkpoints.", "", false, "false", "LastLsn", "FirstLsn,DatabaseBackupLsn,LastLsn" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": "DBCC", "CommandName": "Get-DbaDbccHelp", "Name": "Get-DbaDbccHelp", "Author": "Patrick Flynn (@sqllensman)", "Syntax": "Get-DbaDbccHelp [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Statement] \u003cString\u003e] [-IncludeUndocumented] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance containing the DBCC help information.\nProperties:\r\n- Operation: The DBCC command name specified in the Statement parameter (e.g., \"CHECKDB\", \"SHRINKFILE\")\r\n- Cmd: The complete DBCC command executed against SQL Server (e.g., \"DBCC HELP(CHECKDB)\")\r\n- Output: The raw output from the DBCC HELP command, containing the syntax help and parameter information. This is typically a DataTable or collection of results rows with parameter details.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbccHelp -SqlInstance SQLInstance -Statement FREESYSTEMCACHE -Verbose | Format-List\nRuns the command DBCC HELP(FREESYSTEMCACHE) WITH NO_INFOMSGS against the SQLInstance SQL Server instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbccHelp -SqlInstance SQLInstance -Statement WritePage -IncludeUndocumented | Format-List\nSets Trace Flag 2588 on for the session and then runs the command DBCC HELP(WritePage) WITH NO_INFOMSGS against the SQLInstance SQL Server instance.", "Description": "Executes DBCC HELP against SQL Server to display syntax, parameters, and usage information for Database Console Commands. This saves you from having to look up DBCC command syntax in documentation, especially for complex commands like CHECKDB, CHECKTABLE, or SHRINKFILE. Supports both documented and undocumented DBCC commands when used with the IncludeUndocumented parameter.\n\nRead more:\n - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-help-transact-sql", "Links": "https://dbatools.io/Get-DbaDbccHelp", "Synopsis": "Retrieves syntax help and parameter information for DBCC commands", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Statement", "Specifies the DBCC command name to get syntax help for. Provide only the command portion after \"DBCC\" (e.g., CHECKDB, CHECKTABLE, SHRINKFILE).\r\nUse this when you need to verify command syntax before running maintenance operations or troubleshooting database issues.\r\nCommon commands include CHECKDB for database integrity, SHRINKFILE for file management, or FREEPROCCACHE for memory management.", "", false, "false", "", "" ], [ "IncludeUndocumented", "Enables access to help for undocumented DBCC commands by setting trace flag 2588 for the session.\r\nUse this when troubleshooting advanced scenarios that require undocumented commands like WRITEPAGE or PAGE.\r\nOnly works on SQL Server 2005 and higher, and should be used with caution as undocumented commands can affect system stability.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "DBCC", "Memory" ], "CommandName": "Get-DbaDbccMemoryStatus", "Name": "Get-DbaDbccMemoryStatus", "Author": "Patrick Flynn (@sqllensman)", "Syntax": "Get-DbaDbccMemoryStatus [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per memory metric returned by DBCC MEMORYSTATUS. Each metric is parsed into a structured object containing the metric name, value, and classification.\nProperties:\r\n- ComputerName: The name of the computer hosting the SQL Server instance\r\n- InstanceName: The name of the SQL Server instance\r\n- SqlInstance: The full SQL Server instance name (ComputerName\\InstanceName)\r\n- RecordSet: The recordset number from the DBCC MEMORYSTATUS output (identifies which section the metric belongs to)\r\n- RowId: The sequential row ID across all recordsets\r\n- RecordSetId: The row ID within the current recordset\r\n- Type: The memory category/type from DBCC MEMORYSTATUS (e.g., Memory Manager, Buffer Manager, Resource Pool, etc.)\r\n- Name: The name of the memory metric\r\n- Value: The value of the memory metric (typically in KB)\r\n- ValueType: The column name from DBCC MEMORYSTATUS output indicating the metric classification", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbccMemoryStatus -SqlInstance sqlcluster, sqlserver2012\nGet output of DBCC MEMORYSTATUS for instances \"sqlcluster\" and \"sqlserver2012\". Returns results in a single recordset.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaRegServer -SqlInstance sqlcluster | Get-DbaDbccMemoryStatus\nGet output of DBCC MEMORYSTATUS for all servers in Server Central Management Server", "Description": "Runs DBCC MEMORYSTATUS against SQL Server instances and parses the output into a structured PowerShell object for analysis. This replaces the need to manually execute DBCC MEMORYSTATUS and interpret its raw text output, making memory troubleshooting and monitoring much easier. The function organizes memory statistics by type (like Memory Manager, Buffer Manager, Resource Pool, etc.) and provides both the metric names and values in a consistent format across multiple instances. Useful for diagnosing memory pressure, understanding memory allocation patterns, and comparing memory usage across environments.\n\nReference:\n - https://blogs.msdn.microsoft.com/timchapman/2012/08/16/how-to-parse-dbcc-memorystatus-via-powershell/\n - https://support.microsoft.com/en-us/help/907877/how-to-use-the-dbcc-memorystatus-command-to-monitor-memory-usage-on-sq", "Links": "https://dbatools.io/Get-DbaDbccMemoryStatus", "Synopsis": "Executes DBCC MEMORYSTATUS and returns memory usage details in a structured format", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": "DBCC", "CommandName": "Get-DbaDbccProcCache", "Name": "Get-DbaDbccProcCache", "Author": "Patrick Flynn (@sqllensman)", "Syntax": "Get-DbaDbccProcCache [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per result row from DBCC PROCCACHE with the following properties:\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name (service name)\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Count: Number of plan cache entries in use\r\n- Used: Memory allocated for plan cache (in pages)\r\n- Active: Number of active plan cache entries\r\n- CacheSize: Total plan cache size (in pages)\r\n- CacheUsed: Amount of plan cache currently used (in pages)\r\n- CacheActive: Number of active cache entries (may differ from Active)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbccProcCache -SqlInstance Server1\nGet results of DBCC PROCCACHE for Instance Server1\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Get-DbaDbccProcCache\nGet results of DBCC PROCCACHE for Instances Sql1 and Sql2/sqlexpress\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Get-DbaDbccProcCache -SqlInstance Server1 -SqlCredential $cred\nConnects using sqladmin credential and gets results of DBCC PROCCACHE for Instance Server1", "Description": "Executes DBCC PROCCACHE against SQL Server instances and returns structured information about plan cache memory utilization. This command reveals how much memory is allocated for storing compiled execution plans, how much is currently being used, and how many plan entries are active. Essential for diagnosing memory pressure issues, understanding plan cache efficiency, and monitoring whether the plan cache is consuming excessive memory or experiencing frequent evictions that could impact query performance.\n\nRead more:\n - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-proccache-transact-sql", "Links": "https://dbatools.io/Get-DbaDbccProcCache", "Synopsis": "Retrieves plan cache memory usage statistics from SQL Server instances", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": "DBCC", "CommandName": "Get-DbaDbccSessionBuffer", "Name": "Get-DbaDbccSessionBuffer", "Author": "Patrick Flynn (@sqllensman)", "Syntax": "Get-DbaDbccSessionBuffer [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Operation] \u003cString\u003e] [[-SessionId] \u003cInt32[]\u003e] [[-RequestId] \u003cInt32\u003e] [-All] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per row of DBCC buffer output. The exact properties depend on the -Operation parameter value.\nWhen Operation is InputBuffer:\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The fully qualified SQL Server instance name (computer\\instance)\r\n- SessionId: The session ID being examined (integer)\r\n- EventType: The event type of the SQL statement (string)\r\n- Parameters: Parameters associated with the SQL statement (string)\r\n- EventInfo: Additional event information or the SQL statement itself (string)\nWhen Operation is OutputBuffer:\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The fully qualified SQL Server instance name (computer\\instance)\r\n- SessionId: The session ID being examined (integer)\r\n- Buffer: The output buffer contents in ASCII format with non-printable characters removed (string)\r\n- HexBuffer: The raw hexadecimal representation of the output buffer data (string, available but not displayed by default)\nThe default display via Select-DefaultView shows only ComputerName, InstanceName, SqlInstance, SessionId, and Buffer (or EventType/Parameters/EventInfo for InputBuffer) to maintain readability. Use \r\nSelect-Object * to view all properties including HexBuffer.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbccSessionBuffer -SqlInstance Server1 -Operation InputBuffer -SessionId 51\nGet results of DBCC INPUTBUFFER(51) for Instance Server1\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbccSessionBuffer -SqlInstance Server1 -Operation OutputBuffer -SessionId 51, 52\nGet results of DBCC OUTPUTBUFFER for SessionId\u0027s 51 and 52 for Instance Server1\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbccSessionBuffer -SqlInstance Server1 -Operation InputBuffer -SessionId 51 -RequestId 0\nGet results of DBCC INPUTBUFFER(51,0) for Instance Server1\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbccSessionBuffer -SqlInstance Server1 -Operation OutputBuffer -SessionId 51 -RequestId 0\nGet results of DBCC OUTPUTBUFFER(51,0) for Instance Server1\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Get-DbaDbccSessionBuffer -Operation InputBuffer -All\nGet results of DBCC INPUTBUFFER for all user sessions for the instances Sql1 and Sql2/sqlexpress\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Get-DbaDbccSessionBuffer -Operation OutputBuffer -All\nGet results of DBCC OUTPUTBUFFER for all user sessions for the instances Sql1 and Sql2/sqlexpress\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Get-DbaDbccSessionBuffer -SqlInstance Server1 -SqlCredential $cred -Operation InputBuffer -SessionId 51 -RequestId 0\nConnects using sqladmin credential and gets results of DBCC INPUTBUFFER(51,0) for Instance Server1\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Get-DbaDbccSessionBuffer -SqlInstance Server1 -SqlCredential $cred -Operation OutputBuffer -SessionId 51 -RequestId 0\nConnects using sqladmin credential and gets results of DBCC OUTPUTBUFFER(51,0) for Instance Server1", "Description": "Executes DBCC INPUTBUFFER or DBCC OUTPUTBUFFER to examine what SQL statements a session is executing or what data is being returned to a client. InputBuffer shows the last SQL batch sent by a client session, which is essential for troubleshooting blocking, investigating suspicious activity, or understanding what commands are causing performance issues. OutputBuffer reveals the actual data being transmitted back to the client, useful for debugging connectivity problems or examining result sets. This replaces the need to manually run DBCC commands and parse their output, especially when investigating multiple sessions simultaneously.\n\nRead more:\n - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-inputbuffer-transact-sql\n - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-outputbuffer-transact-sql", "Links": "https://dbatools.io/Get-DbaDbccSessionBuffer", "Synopsis": "Retrieves session input or output buffer contents using DBCC INPUTBUFFER or DBCC OUTPUTBUFFER", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Operation", "Specifies which DBCC operation to execute: InputBuffer shows the last SQL statement sent by a client, while OutputBuffer shows data being returned to the client.\r\nUse InputBuffer when troubleshooting blocking sessions, investigating suspicious activity, or identifying problematic queries.\r\nUse OutputBuffer when debugging client connectivity issues or examining what data is being transmitted to applications.", "", false, "false", "InputBuffer", "InputBuffer,OutputBuffer" ], [ "SessionId", "Specifies one or more session IDs to examine for buffer contents. Session IDs can be found in sys.dm_exec_sessions or sys.dm_exec_requests.\r\nUse this when you need to investigate specific sessions that are causing blocking, consuming resources, or exhibiting unusual behavior.\r\nCannot be used together with the -All parameter.", "", false, "false", "", "" ], [ "RequestId", "Specifies the exact request (batch) to examine within a session when multiple requests are active. Optional parameter that defaults to the current request.\r\nUse this when a session has multiple concurrent requests and you need to examine a specific batch rather than the most recent one.\r\nFind request IDs by querying sys.dm_exec_requests for the target session_id.", "", false, "false", "0", "" ], [ "All", "Retrieves buffer information for all active user sessions instead of specific session IDs. Excludes system sessions to focus on user activity.\r\nUse this when performing broad troubleshooting to identify which sessions are running problematic queries or consuming resources.\r\nThis parameter overrides any SessionId or RequestId values and may return large result sets on busy servers.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "DBCC", "Statistics" ], "CommandName": "Get-DbaDbccStatistic", "Name": "Get-DbaDbccStatistic", "Author": "Patrick Flynn (@sqllensman)", "Syntax": "Get-DbaDbccStatistic [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-Object] \u003cString\u003e] [[-Target] \u003cString\u003e] [[-Option] \u003cString\u003e] [-NoInformationalMessages] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per row returned from the DBCC SHOW_STATISTICS command. The properties included vary based on the Option parameter.\nCommon properties (all outputs):\r\n- ComputerName: The name of the SQL Server instance\u0027s computer\r\n- InstanceName: The name of the SQL Server instance\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: The name of the database containing the statistics\r\n- Object: The schema-qualified name of the table or indexed view (e.g., \u0027dbo.Orders\u0027)\r\n- Target: The name of the statistics object, index, or column being analyzed\r\n- Cmd: The full DBCC SHOW_STATISTICS command that was executed\nWhen Option is \u0027StatHeader\u0027 (default):\r\n- Name: The name of the statistics object\r\n- Updated: DateTime when statistics were last updated\r\n- Rows: Total number of rows in the table or indexed view\r\n- RowsSampled: Number of rows sampled when statistics were created\r\n- Steps: Number of steps in the histogram\r\n- Density: Overall density value for the statistics\r\n- AverageKeyLength: Average length of the index key in bytes\r\n- StringIndex: Indicates if the statistics are on a string column (Yes/No)\r\n- FilterExpression: Filter expression if statistics are filtered\r\n- UnfilteredRows: Number of rows if different from Rows due to filtering\r\n- PersistedSamplePercent: Sample percent used when creating statistics\nWhen Option is \u0027DensityVector\u0027:\r\n- AllDensity: String representation of density value for all leading columns\r\n- AverageLength: Average length of the column in bytes\r\n- Columns: Names of the columns included in the density vector\nWhen Option is \u0027Histogram\u0027:\r\n- RangeHiKey: Upper boundary value of the histogram step\r\n- RangeRows: Number of rows with values within the histogram step range\r\n- EqualRows: Number of rows with values equal to RangeHiKey\r\n- DistinctRangeRows: Number of distinct values within the histogram step\r\n- AverageRangeRows: Average number of rows per distinct value\nWhen Option is \u0027StatsStream\u0027:\r\n- StatsStream: Raw binary statistics data as a binary object (for advanced analysis)\r\n- Rows: Total number of rows in the table\r\n- DataPages: Number of data pages used by the table", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbccStatistic -SqlInstance SQLServer2017\nWill run the statement SHOW_STATISTICS WITH STAT_HEADER against all Statistics on all User Tables or views for every accessible database on instance SQLServer2017. Connects using Windows \r\nAuthentication.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbccStatistic -SqlInstance SQLServer2017 -Database MyDb -Option DensityVector\nWill run the statement SHOW_STATISTICS WITH DENSITY_VECTOR against all Statistics on all User Tables or views for database MyDb on instance SQLServer2017. Connects using Windows Authentication.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Get-DbaDbccStatistic -SqlInstance SQLServer2017 -SqlCredential $cred -Database MyDb -Object UserTable -Option Histogram\nWill run the statement SHOW_STATISTICS WITH HISTOGRAM against all Statistics on table UserTable for database MyDb on instance SQLServer2017. Connects using sqladmin credential.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Get-DbaDbccStatistic -SqlInstance SQLServer2017 -Database MyDb -Object \u0027dbo.UserTable\u0027 -Target MyStatistic -Option StatsStream\nRuns the statement SHOW_STATISTICS(\u0027dbo.UserTable\u0027, \u0027MyStatistic\u0027) WITH STATS_STREAM against database MyDb on instances Sql1 and Sql2/sqlexpress. Connects using Windows Authentication.", "Description": "Executes DBCC SHOW_STATISTICS to extract detailed information about statistics objects, including distribution histograms, density vectors, and header information. This helps DBAs diagnose query performance issues when the optimizer makes poor execution plan choices due to outdated or skewed statistics. You can analyze specific statistics objects or scan all statistics across databases to identify when UPDATE STATISTICS should be run. Returns different data sets based on the selected option: StatHeader shows when statistics were last updated and row counts, DensityVector reveals data uniqueness patterns, Histogram displays value distribution across column ranges, and StatsStream provides the raw binary statistics data.", "Links": "https://dbatools.io/Get-DbaDbccStatistic", "Synopsis": "Retrieves statistics information from tables and indexed views for query performance analysis", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to analyze for statistics information. Accepts multiple database names as an array.\r\nWhen omitted, the function processes all accessible databases on the instance, which is useful for instance-wide statistics analysis.", "", false, "false", "", "" ], [ "Object", "Specifies the table or indexed view to analyze for statistics information. Use this to focus on a specific object rather than all tables in the database.\r\nFormat two-part names as \u0027Schema.ObjectName\u0027 (e.g., \u0027dbo.Orders\u0027). When specified without Target, all statistics on the object are analyzed.", "", false, "false", "", "" ], [ "Target", "Specifies the exact statistics object, index, or column name to analyze. Use this when you need to examine a specific statistic rather than all statistics on an object.\r\nAccepts statistics names (like \u0027_WA_Sys_CustomerID\u0027), index names (like \u0027IX_Orders_CustomerID\u0027), or column names. Can be enclosed in brackets, quotes, or left unquoted.", "", false, "false", "", "" ], [ "Option", "Controls which type of statistics data to return from DBCC SHOW_STATISTICS. Defaults to \u0027StatHeader\u0027 which shows when statistics were last updated and row counts.\r\nUse \u0027Histogram\u0027 to analyze data distribution patterns, \u0027DensityVector\u0027 to examine column uniqueness, or \u0027StatsStream\u0027 to get raw binary statistics data for advanced analysis.", "", false, "false", "StatHeader", "StatHeader,DensityVector,Histogram,StatsStream" ], [ "NoInformationalMessages", "Suppresses informational messages from DBCC SHOW_STATISTICS output, providing cleaner results focused only on the statistics data.\r\nUse this when running automated scripts or when you only need the statistics data without additional DBCC messaging.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": "DBCC", "CommandName": "Get-DbaDbccUserOption", "Name": "Get-DbaDbccUserOption", "Author": "Patrick Flynn (@sqllensman)", "Syntax": "Get-DbaDbccUserOption [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Option] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per session option returned by DBCC USEROPTIONS. If the -Option parameter is specified, only matching options are returned.\nProperties:\r\n- ComputerName: The name of the computer hosting the SQL Server instance\r\n- InstanceName: The SQL Server instance name (service name)\r\n- SqlInstance: The full SQL Server instance name in the format ComputerName\\InstanceName or just the computer name for the default instance\r\n- Option: The name of the session option (e.g., ansi_nulls, dateformat, isolation level)\r\n- Value: The current value or setting of the option", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbccUserOption -SqlInstance Server1\nGet results of DBCC USEROPTIONS for Instance Server1\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Get-DbaDbccUserOption\nGet results of DBCC USEROPTIONS for Instances Sql1 and Sql2/sqlexpress\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Get-DbaDbccUserOption -SqlInstance Server1 -SqlCredential $cred\nConnects using sqladmin credential and gets results of DBCC USEROPTIONS for Instance Server1\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbccUserOption -SqlInstance Server1 -Option ansi_nulls, ansi_warnings, datefirst\nGets results of DBCC USEROPTIONS for Instance Server1. Only display results for the options ansi_nulls, ansi_warnings, datefirst", "Description": "Executes DBCC USEROPTIONS against SQL Server instances to display current session settings including ANSI options, isolation levels, date formats, language, and timeout values. This is particularly useful when troubleshooting application connection issues or verifying that session-level defaults match across environments. You can filter results to specific options or retrieve all current settings to compare against expected configurations during deployments or performance investigations.\n\nRead more:\n - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-useroptions-transact-sql", "Links": "https://dbatools.io/Get-DbaDbccUserOption", "Synopsis": "Retrieves current session-level SET options and connection settings from SQL Server instances", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Option", "Filters results to show only specific session options instead of all DBCC USEROPTIONS output. Use this when troubleshooting specific connection settings like ANSI options, date formats, or isolation \r\nlevels without seeing the full list of 13 available options.\r\nAccepts any values in set \u0027ansi_null_dflt_on\u0027, \u0027ansi_nulls\u0027, \u0027ansi_padding\u0027, \u0027ansi_warnings\u0027, \u0027arithabort\u0027, \u0027concat_null_yields_null\u0027, \u0027datefirst\u0027, \u0027dateformat\u0027, \u0027isolation level\u0027, \u0027language\u0027, \r\n\u0027lock_timeout\u0027, \u0027quoted_identifier\u0027, \u0027textsize\u0027", "", false, "false", "", "ansi_null_dflt_on,ansi_nulls,ansi_padding,ansi_warnings,arithabort,concat_null_yields_null,datefirst,dateformat,isolation level,language,lock_timeout,quoted_identifier,textsize" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Certificate", "Security" ], "CommandName": "Get-DbaDbCertificate", "Name": "Get-DbaDbCertificate", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaDbCertificate [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-ExcludeDatabase] \u003cString[]\u003e] [[-Certificate] \u003cObject[]\u003e] [[-Subject] \u003cString[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Certificate\nReturns one Certificate object per certificate found in the specified databases. Each certificate object is augmented with additional context properties to identify the containing database and SQL \r\nServer instance.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The name of the computer hosting the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: The name of the database containing the certificate\r\n- Name: The name of the certificate\r\n- Subject: The subject field of the certificate for identification\r\n- StartDate: The date and time when the certificate becomes valid\r\n- ActiveForServiceBrokerDialog: Boolean indicating if the certificate is active for Service Broker dialog security\r\n- ExpirationDate: The date and time when the certificate expires\r\n- Issuer: The issuer of the certificate\r\n- LastBackupDate: The date and time of the most recent backup of the certificate\r\n- Owner: The owner or principal that owns the certificate\r\n- PrivateKeyEncryptionType: The encryption type used for the private key (None, Password, MasterKey)\r\n- Serial: The serial number of the certificate\nAdditional properties available from the SMO Certificate object:\r\n- DatabaseId: The unique identifier of the database containing the certificate\r\n- Thumbprint: The SHA-1 hash of the certificate\r\n- CreateDate: The date and time when the certificate was created\r\n- SignedByCertificate: Name of the certificate that signed this certificate (if applicable)\r\n- PrivateKeyExists: Boolean indicating if the certificate has a private key\nAll properties from the base SMO Certificate object are accessible via Select-Object * even though only default properties are displayed without explicit selection.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbCertificate -SqlInstance sql2016\nGets all certificates\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbCertificate -SqlInstance Server1 -Database db1\nGets the certificate for the db1 database\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbCertificate -SqlInstance Server1 -Database db1 -Certificate cert1\nGets the cert1 certificate within the db1 database\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbCertificate -SqlInstance Server1 -Database db1 -Subject \u0027Availability Group Cert\u0027\nGets the certificate within the db1 database that has the subject \u0027Availability Group Cert\u0027", "Description": "Retrieves all certificates stored within SQL Server databases, providing detailed information about each certificate including expiration dates, issuers, and encryption properties. This function is essential for DBAs managing Transparent Data Encryption (TDE), Service Broker security, or other database-level encryption features. Use this to audit certificate inventory across your environment, monitor approaching expiration dates for proactive renewal planning, and ensure compliance with security policies that require certificate tracking and rotation.", "Links": "https://dbatools.io/Get-DbaDbCertificate", "Synopsis": "Retrieves database-level certificates from SQL Server databases for security auditing and certificate management", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to search for certificates. Accepts one or more database names as strings.\r\nUse this when you need to audit certificates in specific databases rather than all databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies which databases to skip when retrieving certificates. Accepts one or more database names as strings.\r\nUseful when you want to audit most databases but exclude system databases or specific databases that don\u0027t contain certificates of interest.", "", false, "false", "", "" ], [ "Certificate", "Filters results to specific certificates by their name property. Accepts one or more certificate names as strings.\r\nUse this when you need to check the status of known certificates across multiple databases, such as tracking TDE certificates or Service Broker certificates.", "", false, "false", "", "" ], [ "Subject", "Filters results to certificates with specific subject names. Accepts one or more subject strings for exact matching.\r\nHelpful when searching for certificates based on their distinguished name or common name, particularly when certificate names aren\u0027t descriptive but subjects are standardized.", "", false, "false", "", "" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase through the PowerShell pipeline.\r\nThis allows you to chain commands like Get-DbaDatabase | Get-DbaDbCertificate for more complex filtering scenarios.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": "Database", "CommandName": "Get-DbaDbCheckConstraint", "Name": "Get-DbaDbCheckConstraint", "Author": "Claudio Silva (@ClaudioESSilva), claudioessilva.eu", "Syntax": "Get-DbaDbCheckConstraint [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-ExcludeSystemTable] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Check\nReturns one Check object per check constraint found in the specified databases. Each object represents a single check constraint defined on a database table.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: The database name containing the check constraint\r\n- Parent: The table object that contains this check constraint\r\n- ID: Unique identifier of the check constraint\r\n- CreateDate: DateTime when the check constraint was created\r\n- DateLastModified: DateTime when the check constraint was last modified\r\n- Name: The name of the check constraint\r\n- IsEnabled: Boolean indicating if the check constraint is currently enabled\r\n- IsChecked: Boolean indicating if the constraint is checked during INSERT/UPDATE operations\r\n- NotForReplication: Boolean indicating if the constraint applies to replication operations\r\n- Text: The actual check constraint definition/expression (the logic that validates the data)\r\n- State: SMO object state (Existing, Creating, Dropping, etc.)\nAdditional properties available (from SMO Check object):\r\n- DatabaseEngineEdition: The SQL Server edition where the check constraint exists\r\n- DatabaseEngineType: The type of database engine\r\n- Urn: Unique Resource Name for the constraint\r\n- ExtendedProperties: Extended properties attached to the constraint\nAll properties from the base SMO Check object are accessible even though only default properties are displayed without using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbCheckConstraint -SqlInstance sql2016\nGets all database check constraints.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbCheckConstraint -SqlInstance Server1 -Database db1\nGets the check constraints for the db1 database.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbCheckConstraint -SqlInstance Server1 -ExcludeDatabase db1\nGets the check constraints for all databases except db1.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbCheckConstraint -SqlInstance Server1 -ExcludeSystemTable\nGets the check constraints for all databases that are not system objects.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Get-DbaDbCheckConstraint\nGets the check constraints for the databases on Sql1 and Sql2/sqlexpress.", "Description": "Gets database Checks constraints.", "Links": "https://dbatools.io/Get-DbaDbCheckConstraint", "Synopsis": "Gets database Check constraints.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to search for check constraints. Accepts wildcards and multiple database names.\r\nUse this when you need to examine constraints on specific databases rather than all accessible databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific databases from the check constraint search. Accepts multiple database names.\r\nUseful when you want to scan most databases but skip certain ones like development or temporary databases.", "", false, "false", "", "" ], [ "ExcludeSystemTable", "Excludes check constraints from system tables when searching through databases.\r\nUse this to focus only on user-created tables and avoid system table constraints that are typically not relevant for DBA reviews.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Compatibility", "Database" ], "CommandName": "Get-DbaDbCompatibility", "Name": "Get-DbaDbCompatibility", "Author": "Garry Bargsley, blog.garrybargsley.com", "Syntax": "Get-DbaDbCompatibility [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database checked. Each object contains the following properties:\n- ComputerName: The name of the computer hosting the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (ComputerName\\InstanceName)\r\n- Database: The name of the database\r\n- DatabaseId: The internal ID of the database\r\n- Compatibility: The compatibility level of the database (numeric value corresponding to SQL Server version, e.g., 150 for SQL Server 2019, 160 for SQL Server 2022)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbCompatibility -SqlInstance localhost\\sql2017\nDisplays database compatibility level for all user databases on server localhost\\sql2017\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbCompatibility -SqlInstance localhost\\sql2017 -Database Test\nDisplays database compatibility level for database Test on server localhost\\sql2017", "Description": "Returns the current compatibility level setting for each database, which determines what SQL Server language features and behaviors are available to that database. This is essential when planning SQL Server upgrades, as databases often retain older compatibility levels even after the instance is upgraded. The function helps identify which databases may need compatibility level updates to take advantage of newer SQL Server features or to maintain vendor application support requirements.", "Links": "https://dbatools.io/Get-DbaDbCompatibility", "Synopsis": "Retrieves database compatibility levels from SQL Server instances for upgrade planning and compliance auditing.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", false, "false", "", "" ], [ "SqlCredential", "SqlLogin to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance..", "", false, "false", "", "" ], [ "Database", "Specifies which databases to check for compatibility levels. Accepts wildcards for pattern matching.\r\nUse this when you need to focus on specific databases rather than reviewing all databases on the instance.", "", false, "false", "", "" ], [ "InputObject", "Accepts database objects from the pipeline to check their compatibility levels directly.\r\nUse this when you already have database objects from Get-DbaDatabase or other dbatools commands and want to avoid additional server queries.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Compression", "Table", "Database" ], "CommandName": "Get-DbaDbCompression", "Name": "Get-DbaDbCompression", "Author": "Jess Pomfret (@jpomfret), jesspomfret.com", "Syntax": "Get-DbaDbCompression [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-ExcludeDatabase] \u003cString[]\u003e] [[-Table] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per partition for each table and index analyzed, providing compression details for heaps, clustered indexes, and non-clustered indexes.\nProperties:\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: Name of the database containing the table\r\n- DatabaseId: Unique identifier (ID) of the database\r\n- Schema: Name of the schema containing the table\r\n- TableName: Name of the table\r\n- IndexName: Name of the index (null for heap partitions)\r\n- Partition: The partition number within the partition scheme\r\n- IndexID: Index ID number (0 for heaps, \u003e0 for indexes)\r\n- IndexType: Type of index structure (Heap, ClusteredIndex, NonClusteredIndex, or other types)\r\n- DataCompression: Current compression type (None, Row, Page, or ColumnStore)\r\n- SizeCurrent: Current size of the partition in bytes (dbasize object supporting multiple units: B, KB, MB, GB)\r\n- RowCount: Number of rows in the partition", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbCompression -SqlInstance localhost\nReturns objects size and current compression level for all user databases.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbCompression -SqlInstance localhost -Database TestDatabase\nReturns objects size and current compression level for objects within the TestDatabase database.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbCompression -SqlInstance localhost -ExcludeDatabase TestDatabases\nReturns objects size and current compression level for objects in all databases except the TestDatabase database.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbCompression -SqlInstance localhost -ExcludeDatabase TestDatabases -Table table1, table2\nReturns objects size and current compression level for table1 and table2 in all databases except the TestDatabase database.", "Description": "This function analyzes data compression usage across your SQL Server databases by examining tables, indexes, and their physical partitions. It returns detailed information including current compression type (None, Row, Page, Columnstore), space usage, and row counts for each object. This is essential for compression optimization analysis, identifying candidates for compression to save storage space, and generating compliance reports on compression usage across your database environment.", "Links": "https://dbatools.io/Get-DbaDbCompression", "Synopsis": "Retrieves compression settings, sizes, and row counts for tables and indexes across SQL Server databases.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to analyze for compression information. Accepts multiple database names as an array.\r\nUse this when you want to focus compression analysis on specific databases rather than scanning all user databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies which databases to skip during compression analysis. Accepts multiple database names as an array.\r\nUse this to exclude system databases, maintenance databases, or other databases you don\u0027t want included in compression reporting.", "", false, "false", "", "" ], [ "Table", "Specifies which tables to analyze for compression information. Accepts multiple table names as an array.\r\nUse this when you need compression details for specific tables rather than all tables in the target databases, particularly useful for large databases where you want to focus on specific objects.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "DataClassification", "Classification", "Compliance", "Security" ], "CommandName": "Get-DbaDbDataClassification", "Name": "Get-DbaDbDataClassification", "Author": "the dbatools team + Claude", "Syntax": "Get-DbaDbDataClassification [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-Schema] \u003cString[]\u003e] [[-Table] \u003cString[]\u003e] [[-Column] \u003cString[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per classified column with the following properties:\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name\r\n- Database: The database name\r\n- Schema: The schema name of the table\r\n- Table: The table name\r\n- Column: The column name\r\n- InformationTypeId: GUID identifying the information type\r\n- InformationType: Human-readable information type name\r\n- SensitivityLabelId: GUID identifying the sensitivity label\r\n- SensitivityLabel: Human-readable sensitivity label name", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbDataClassification -SqlInstance sql2019\nReturns all data classifications across all databases on sql2019.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbDataClassification -SqlInstance sql2019 -Database AdventureWorks\nReturns all data classifications in the AdventureWorks database.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbDataClassification -SqlInstance sql2019 -Database AdventureWorks -Table Customer\nReturns data classifications for columns in the Customer table.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2019 -Database AdventureWorks | Get-DbaDbDataClassification\nReturns all data classifications in AdventureWorks by piping the database object.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaDbDataClassification -SqlInstance sql2019 -Database AdventureWorks | Where-Object SensitivityLabel -eq \"Highly Confidential\"\nReturns only columns classified as Highly Confidential in AdventureWorks.", "Description": "Retrieves data classification labels stored as extended properties on table columns. Data classification\nis used to tag sensitive data columns with information type and sensitivity labels, which helps with\ncompliance, data governance, and security auditing.\n\nClassification metadata is stored as four extended properties on each classified column:\n- sys_information_type_id: GUID identifying the information type\n- sys_information_type_name: Human-readable information type name (e.g., \"Financial\", \"Health\", \"Credentials\")\n- sys_sensitivity_label_id: GUID identifying the sensitivity label\n- sys_sensitivity_label_name: Human-readable sensitivity label (e.g., \"Public\", \"General\", \"Confidential\")\n\nThese properties are compatible with Microsoft Information Protection (MIP) labels used by SQL Server\nData Discovery \u0026 Classification in SSMS and Azure SQL Database.\n\nRequires SQL Server 2005 or later due to use of sys.extended_properties.", "Links": "https://dbatools.io/Get-DbaDbDataClassification", "Synopsis": "Retrieves data classification information for columns in SQL Server databases", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory -\r\nIntegrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to search for data classifications. Only applies when connecting directly via SqlInstance.", "", false, "false", "", "" ], [ "Schema", "Filters results to columns in the specified schema(s).", "", false, "false", "", "" ], [ "Table", "Filters results to columns in the specified table(s).", "", false, "false", "", "" ], [ "Column", "Filters results to the specified column name(s).", "", false, "false", "", "" ], [ "InputObject", "Accepts database objects piped from Get-DbaDatabase.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": "DBCC", "CommandName": "Get-DbaDbDbccOpenTran", "Name": "Get-DbaDbDbccOpenTran", "Author": "Patrick Flynn (@sqllensman)", "Syntax": "Get-DbaDbDbccOpenTran [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per active transaction found, or one object per database when no active transactions exist.\nProperties:\r\n- ComputerName: The name of the server where the SQL Server instance is running\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (ComputerName\\InstanceName)\r\n- Database: The database name that was scanned\r\n- DatabaseId: The unique identifier of the database\r\n- Cmd: The DBCC OPENTRAN command executed (for reference/debugging)\r\n- Output: Human-readable summary of the result (\"Oldest active transaction\" or \"No active open transactions.\")\r\n- Field: The property name from DBCC OPENTRAN output (e.g., \"Transaction ID\", \"OldestOpenTrxn\", \"SPID\", \"StartTime\", \"Program Name\", \"Host Name\"), or $null if no active transactions\r\n- Data: The corresponding value for the Field (e.g., transaction ID number, SPID number, timestamp, program name), or $null if no active transactions\nWhen no open transactions are found, all rows return the same database-level information with Output set to \"No active open transactions.\" and Field/Data set to $null.\r\nWhen open transactions are found, Field and Data contain the result columns from DBCC OPENTRAN output, providing detailed transaction details.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbDbccOpenTran -SqlInstance SQLServer2017\nConnects to instance SqlServer2017 using Windows Authentication and runs the command DBCC OPENTRAN WITH TABLERESULTS, NO_INFOMSGS against each database.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbDbccOpenTran -SqlInstance SQLServer2017 -Database CurrentDB\nConnects to instance SqlServer2017 using Windows Authentication and runs the command DBCC OPENTRAN(CurrentDB) WITH TABLERESULTS, NO_INFOMSGS against the CurrentDB database.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e \u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Get-DbaDbDbccOpenTran -SqlCredential $cred\nConnects to instances Sql1 and Sql2/sqlexpress using sqladmin credential and runs the command DBCC OPENTRAN WITH TABLERESULTS, NO_INFOMSGS against each database.", "Description": "Executes DBCC OPENTRAN against specified databases to identify long-running or problematic transactions that may be causing blocking, transaction log growth, or replication delays.\n\nThis function helps DBAs troubleshoot performance issues by revealing the oldest active transaction and any distributed or replicated transactions within each database\u0027s transaction log. When transactions remain open for extended periods, they prevent log truncation and can cause cascading blocking issues throughout your SQL Server instance.\n\nThe output includes detailed transaction information in structured PowerShell objects, making it easy to identify which transactions need attention. If no active transactions are found, the function clearly indicates this status for each database checked.\n\nThis is particularly valuable when investigating sudden transaction log growth, diagnosing blocking chains, or troubleshooting replication latency issues where old transactions may be preventing log reader processes from advancing.\n\nRead more:\n - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-opentran-transact-sql", "Links": "https://dbatools.io/Get-DbaDbDbccOpenTran", "Synopsis": "Identifies the oldest active transactions in database transaction logs using DBCC OPENTRAN", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to check for open transactions. Accepts database names or database IDs.\r\nUse this when investigating transaction issues in specific databases rather than scanning all databases on the instance.\r\nIf omitted, DBCC OPENTRAN runs against all accessible databases, which may take longer on instances with many databases.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Database", "Detach" ], "CommandName": "Get-DbaDbDetachedFileInfo", "Name": "Get-DbaDbDetachedFileInfo", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaDbDetachedFileInfo [-SqlInstance] \u003cDbaInstanceParameter\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Path] \u003cString[]\u003e [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per detached MDF file analyzed.\nProperties:\r\n- ComputerName: The computer name of the SQL Server instance used to read the file\r\n- InstanceName: The SQL Server instance name used to read the file\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Name: The original database name stored in the detached MDF file\r\n- Version: Human-readable SQL Server version name (e.g., \"SQL Server 2019\", \"SQL Server 2016\")\r\n- ExactVersion: The raw internal version number from the MDF file header\r\n- Collation: The database collation name, or the collation ID if the name cannot be resolved\r\n- DataFiles: System.Collections.Specialized.StringCollection containing the paths of all data files that belonged to this database\r\n- LogFiles: System.Collections.Specialized.StringCollection containing the paths of all transaction log files that belonged to this database", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbDetachedFileInfo -SqlInstance sql2016 -Path M:\\Archive\\mydb.mdf\nReturns information about the detached database file M:\\Archive\\mydb.mdf using the SQL Server instance sql2016. The M drive is relative to the SQL Server instance.", "Description": "Analyzes detached MDF files to retrieve essential database metadata including name, SQL Server version, collation, and complete file structure. This lets you examine database files sitting in storage or archives without the risk of attaching them to a live instance.\n\nPerfect for migration planning when you need to verify compatibility before moving databases between SQL Server versions. Also invaluable for troubleshooting scenarios where you have detached database files and need to understand their structure or requirements before reattachment.\n\nThe function reads the MDF file header using SQL Server\u0027s built-in methods, so it requires an online SQL Server instance to interpret the binary data. All file paths must be accessible to the specified SQL Server service account.\n\nReturns comprehensive details including the original database name, exact SQL Server version (mapped from internal version numbers), collation settings, and complete lists of associated data and log files as they existed when detached.", "Links": "https://dbatools.io/Get-DbaDbDetachedFileInfo", "Synopsis": "Reads detached SQL Server database files to extract metadata and file structure without attaching them.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "Source SQL Server. This instance must be online and is required to parse the information contained with in the detached database file.\nThis function will not attach the database file, it will only use SQL Server to read its contents.", "", true, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Path", "Specifies the full file path to one or more detached MDF database files to analyze. The SQL Server service account must have read access to these file locations.\r\nUse this when you need to examine database files in archives, backups, or migration staging areas before deciding whether to attach them.\r\nSupports multiple file paths and accepts wildcards, but each MDF file must be accessible from the specified SQL Server instance.", "Mdf,FilePath,FullName", true, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": "Encryption", "CommandName": "Get-DbaDbEncryption", "Name": "Get-DbaDbEncryption", "Author": "Stephen Bennett, sqlnotesfromtheunderground.wordpress.com", "Syntax": "Get-DbaDbEncryption [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-IncludeSystemDBs] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per encryption object found. The function searches for four types of encryption objects within each database: TDE encryption, certificates, asymmetric keys, and symmetric keys. \r\nProperties vary depending on the type of encryption object found.\nCommon properties in all output objects:\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: The database name containing the encryption object\r\n- Encryption: The type of encryption object (EncryptionEnabled (TDE), Certificate, Asymmetric key, or Symmetric key)\r\n- Name: The name of the encryption object\r\n- Owner: The owner of the encryption object\r\n- Object: The underlying SMO object (Certificate, AsymmetricKey, SymmetricKey, or DatabaseEncryptionKey)\nAdditional properties specific to encryption type:\r\n- LastBackup: DateTime of the last certificate backup (populated for TDE and Certificate types only)\r\n- PrivateKeyEncryptionType: How the private key is encrypted (populated for TDE, Certificate, Asymmetric key, and Symmetric key types)\r\n- EncryptionAlgorithm: The encryption algorithm used (populated for TDE and Asymmetric key types)\r\n- KeyLength: The key length in bits (populated for Asymmetric key and Symmetric key types)\r\n- ExpirationDate: DateTime when the certificate expires (populated for TDE and Certificate types only)\nNote: When TDE encryption is enabled on a database, the returned object includes details of the server certificate protecting the database encryption key.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbEncryption -SqlInstance DEV01\nList all encryption found on the instance by database\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbEncryption -SqlInstance DEV01 -Database MyDB\nList all encryption found for the MyDB database.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbEncryption -SqlInstance DEV01 -ExcludeDatabase MyDB\nList all encryption found for all databases except MyDB.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbEncryption -SqlInstance DEV01 -IncludeSystemDBs\nList all encryption found for all databases including the system databases.", "Description": "Audits database-level encryption across SQL Server instances by examining TDE encryption status, certificates, asymmetric keys, and symmetric keys within each database. Returns detailed information including key algorithms, lengths, owners, backup dates, and expiration dates for compliance reporting and security assessments. Particularly useful for encryption audits, certificate lifecycle management, and ensuring regulatory compliance across your SQL Server environment.", "Links": "https://dbatools.io/Get-DbaDbEncryption", "Synopsis": "Retrieves comprehensive encryption inventory from SQL Server databases including TDE status, certificates, and keys.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to examine for encryption objects including TDE, certificates, and keys. Accepts database names as strings or arrays.\r\nUse this to focus encryption audits on specific databases rather than scanning all user databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific databases from the encryption inventory scan. Useful when you need to audit most databases but skip certain ones.\r\nCommonly used to exclude databases with known encryption issues or maintenance databases that don\u0027t require encryption compliance checks.", "", false, "false", "", "" ], [ "IncludeSystemDBs", "Includes system databases (master, model, msdb, tempdb) in the encryption inventory. By default, only user databases are scanned.\r\nUse this when conducting comprehensive security audits that require visibility into system database encryption objects and TDE configurations.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Certificate", "Security" ], "CommandName": "Get-DbaDbEncryptionKey", "Name": "Get-DbaDbEncryptionKey", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaDbEncryptionKey [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-ExcludeDatabase] \u003cString[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.DatabaseEncryptionKey\nReturns one DatabaseEncryptionKey object per database that has Transparent Data Encryption (TDE) enabled. If a database has no encryption key, no object is returned for that database.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: The database name containing the encryption key\r\n- CreateDate: DateTime when the encryption key was created\r\n- EncryptionAlgorithm: The encryption algorithm used (Aes128, Aes192, Aes256, or TripleDes)\r\n- EncryptionState: Current encryption state (Encrypted, EncryptionInProgress, DecryptionInProgress, or EncryptionUnsupported)\r\n- EncryptionType: Type of encryptor used (ServerCertificate or ServerAsymmetricKey)\r\n- EncryptorName: Name of the certificate or asymmetric key protecting this encryption key\r\n- ModifyDate: DateTime when the encryption key was last modified\r\n- OpenedDate: DateTime when the encryption key was last opened\r\n- RegenerateDate: DateTime when the encryption key was last regenerated\r\n- SetDate: DateTime when the encryption key was last set\r\n- Thumbprint: Thumbprint hash of the certificate protecting this encryption key\nAll properties from the base SMO DatabaseEncryptionKey object are accessible even though only default properties are displayed without using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbEncryptionKey -SqlInstance sql2016\nGets all encryption keys from sql2016\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbEncryptionKey -SqlInstance sql01 -Database db1\nGets the encryption key for the db1 database on the sql01 instance\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbEncryptionKey -SqlInstance sql01 -Database db1 -Certificate cert1\nGets the cert1 encryption key within the db1 database\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbEncryptionKey -SqlInstance sql01 -Database db1 -Subject \u0027Availability Group Cert\u0027\nGets the encryption key within the db1 database that has the subject \u0027Availability Group Cert\u0027 on sql01", "Description": "Retrieves detailed information about Transparent Data Encryption (TDE) database encryption keys including encryption state, algorithm, and certificate details. This function helps DBAs audit encrypted databases, verify TDE configuration, and gather key information for compliance reporting or troubleshooting encryption issues. Returns comprehensive key properties like thumbprint, encryption type, and important dates for certificate rotation planning.", "Links": "https://dbatools.io/Get-DbaDbEncryptionKey", "Synopsis": "Retrieves Transparent Data Encryption (TDE) database encryption keys from SQL Server databases", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to retrieve TDE encryption keys from. Accepts wildcards for pattern matching.\r\nUse this when you need to check encryption status for specific databases instead of all databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific databases from the encryption key retrieval operation. Useful when scanning all databases except certain ones like system databases or test databases.\r\nCommonly used to skip tempdb or databases that are known to be unencrypted.", "", false, "false", "", "" ], [ "InputObject", "Accepts database objects piped from Get-DbaDatabase or other dbatools commands. This allows you to filter databases using Get-DbaDatabase\u0027s extensive filtering options before checking encryption keys.\r\nParticularly useful for complex database selection scenarios or when working with specific database collections.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Backup", "Database" ], "CommandName": "Get-DbaDbExtentDiff", "Name": "Get-DbaDbExtentDiff", "Author": "Viorel Ciucu, cviorel.com", "Syntax": "Get-DbaDbExtentDiff [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database analyzed, containing the extent change analysis since the last full backup.\nProperties:\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- DatabaseName: Name of the database analyzed\r\n- ExtentsTotal: Total number of extents in the database\r\n- ExtentsChanged: Number of extents that have been modified since the last full backup\r\n- ChangedPerc: Percentage of the database that has changed since the last full backup (rounded to 2 decimal places)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbExtentDiff -SqlInstance SQL2016 -Database DBA\nGet the changes for the DBA database.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$Cred = Get-Credential sqladmin\nPS C:\\\u003e Get-DbaDbExtentDiff -SqlInstance SQL2017N1, SQL2017N2, SQL2016 -Database DB01 -SqlCredential $Cred\nGet the changes for the DB01 database on multiple servers.", "Description": "Analyzes database extents to determine how much data has changed since the last full backup, helping DBAs decide between differential and full backup strategies. The function examines extent-level modifications (groups of 8 pages) to provide accurate change percentages, which is essential for optimizing backup schedules and storage requirements.\n\nFor SQL Server 2016 SP2 and later, uses the sys.dm_db_file_space_usage DMV for efficient analysis. For older versions, falls back to DBCC PAGE commands to examine differential bitmap pages directly.\n\nBased on the original script by Paul S. Randal: https://www.sqlskills.com/blogs/paul/new-script-how-much-of-the-database-has-changed-since-the-last-full-backup/", "Links": "https://dbatools.io/Get-DbaDbExtentDiff", "Synopsis": "Calculates the percentage of database extents modified since the last full backup", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to analyze for extent changes since the last full backup. Accepts multiple database names and supports wildcards.\r\nUse this when you need to check specific databases rather than analyzing all databases on the instance, which is helpful for large environments or when focusing on particular applications.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies databases to skip during the extent change analysis. Accepts multiple database names and supports wildcards.\r\nUse this to exclude system databases, read-only databases, or databases where you don\u0027t need backup planning analysis, reducing execution time and focusing on relevant databases.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": "Deprecated", "CommandName": "Get-DbaDbFeatureUsage", "Name": "Get-DbaDbFeatureUsage", "Author": "Brandon Abshire, netnerds.net", "Syntax": "Get-DbaDbFeatureUsage [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-ExcludeDatabase] \u003cString[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per Enterprise-edition feature found in the queried database(s).\nProperties:\r\n- ComputerName: The name of the computer hosting the SQL Server instance\r\n- InstanceName: The name of the SQL Server instance (MSSQLSERVER for default instance)\r\n- SqlInstance: The full SQL Server instance name (computer\\instance or just computer for default)\r\n- Id: The feature ID from sys.dm_db_persisted_sku_features\r\n- Feature: The name of the Enterprise-edition feature that is currently in use\r\n- Database: The database where this Enterprise feature was detected\nNo properties are returned if no Enterprise features are found in the queried database(s).", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2008 -Database testdb, db2 | Get-DbaDbFeatureUsage\nShows features that are enabled in the testdb and db2 databases but\r\nnot supported on the all the editions of SQL Server.", "Description": "Queries the sys.dm_db_persisted_sku_features dynamic management view to identify SQL Server Enterprise features that are actively used in your databases. This is essential when planning to downgrade from Enterprise to Standard edition or migrating databases to environments with lower SQL Server editions.\n\nEnterprise features like columnstore indexes, table partitioning, or transparent data encryption must be removed or disabled before a database can be successfully migrated to Standard edition. This function helps you inventory these blocking features across one or more databases so you can plan the necessary remediation steps.\n\nReturns feature ID, feature name, and database information for each Enterprise feature found, making it easy to identify which databases need attention before edition changes.", "Links": "https://dbatools.io/Get-DbaDbFeatureUsage", "Synopsis": "Identifies Enterprise-edition features currently used in databases that prevent downgrading to Standard edition", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to scan for Enterprise edition features. Accepts wildcards for pattern matching.\r\nUse this when you need to check specific databases instead of scanning all databases on the instance.\r\nHelpful when planning edition downgrades for particular databases or troubleshooting feature usage in development environments.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific databases from the Enterprise feature scan. Accepts wildcards for pattern matching.\r\nUse this to skip system databases, read-only databases, or databases you know don\u0027t need to be downgraded.\r\nCommonly used to exclude tempdb, model, or archived databases from bulk scanning operations.", "", false, "false", "", "" ], [ "InputObject", "Accepts database objects directly from the pipeline, typically from Get-DbaDatabase output.\r\nUse this for advanced filtering scenarios or when you\u0027ve already retrieved specific database objects.\r\nAllows you to chain database selection commands with feature usage checking in a single pipeline operation.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Storage", "Data", "File", "Log" ], "CommandName": "Get-DbaDbFile", "Name": "Get-DbaDbFile", "Author": "Stuart Moore (@napalmgram), stuart-moore.com", "Syntax": "Get-DbaDbFile [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-FileGroup] \u003cObject[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database file on the SQL Server instance(s).\nProperties:\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: Name of the database containing the file\r\n- DatabaseID: Internal ID of the database\r\n- FileGroupName: Name of the filegroup containing this file (NULL for log files)\r\n- ID: File ID within the database\r\n- Type: Type of file - 0 for data file, 1 for log file (Integer)\r\n- TypeDescription: Human-readable file type (ROWS or LOG)\r\n- LogicalName: Logical name of the file within SQL Server\r\n- PhysicalName: Operating system file path\r\n- State: Current state of the file (ONLINE, OFFLINE, etc.)\r\n- MaxSize: Maximum size the file can grow to - displays as dbasize object (KB, MB, GB, etc.)\r\n- Growth: Growth increment - value depends on GrowthType\r\n- GrowthType: How the file grows (Percent or KB)\r\n- NextGrowthEventSize: Size added during next autogrow event - displays as dbasize object\r\n- Size: Current size of the file - displays as dbasize object\r\n- UsedSpace: Space currently used within the file - displays as dbasize object\r\n- AvailableSpace: Free space within the file (Size - UsedSpace) - displays as dbasize object\r\n- IsOffline: Boolean indicating if the file is offline\r\n- IsReadOnly: Boolean indicating if the file is read-only\r\n- IsReadOnlyMedia: Boolean indicating if the underlying storage media is read-only\r\n- IsSparse: Boolean indicating if the file is sparse (snapshots)\r\n- NumberOfDiskWrites: Count of write operations to the file since instance startup\r\n- NumberOfDiskReads: Count of read operations from the file since instance startup\r\n- ReadFromDisk: Total bytes read from the file since instance startup - displays as dbasize object\r\n- WrittenToDisk: Total bytes written to the file since instance startup - displays as dbasize object\r\n- VolumeFreeSpace: Free space available on the volume containing this file - displays as dbasize object\r\n- FileGroupDataSpaceId: Internal ID of the filegroup data space\r\n- FileGroupType: Type of filegroup (NULL for log files, or name for data filegroups)\r\n- FileGroupTypeDescription: Description of filegroup type\r\n- FileGroupDefault: Boolean indicating if this is the default filegroup\r\n- FileGroupReadOnly: Boolean indicating if the filegroup is read-only\nNote: Size-related properties (Size, UsedSpace, MaxSize, etc.) are returned as dbasize objects which automatically format as human-readable units (KB, MB, GB, TB) when displayed.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbFile -SqlInstance sql2016\nWill return an object containing all file groups and their contained files for every database on the sql2016 SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbFile -SqlInstance sql2016 -Database Impromptu\nWill return an object containing all file groups and their contained files for the Impromptu Database on the sql2016 SQL Server instance\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbFile -SqlInstance sql2016 -Database Impromptu, Trading\nWill return an object containing all file groups and their contained files for the Impromptu and Trading databases on the sql2016 SQL Server instance\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2016 -Database Impromptu, Trading | Get-DbaDbFile\nWill accept piped input from Get-DbaDatabase and return an object containing all file groups and their contained files for the Impromptu and Trading databases on the sql2016 SQL Server instance\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaDbFile -SqlInstance sql2016 -Database AdventureWorks2017 -FileGroup Index\nReturn any files that are in the Index filegroup of the AdventureWorks2017 database.", "Description": "Retrieves detailed information about database files (data and log files) from SQL Server instances using direct T-SQL queries for optimal performance. This function provides comprehensive file metadata including current size, used space, growth settings, I/O statistics, and volume free space information that DBAs need for capacity planning, performance analysis, and storage management. Unlike SMO-based approaches, this command avoids costly enumeration operations and provides faster results when analyzing file configurations across multiple databases.", "Links": "https://dbatools.io/Get-DbaDbFile", "Synopsis": "Retrieves comprehensive database file information including size, growth, I/O statistics, and storage details.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances", "", false, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to analyze for file information. Accepts wildcards for pattern matching.\r\nUse this when you need to focus on specific databases rather than scanning all databases on the instance.\r\nParticularly useful for capacity planning or troubleshooting file growth issues on targeted databases.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific databases from the file analysis. Accepts wildcards for pattern matching.\r\nUse this to skip system databases, test databases, or databases you don\u0027t need to analyze.\r\nHelpful when performing routine file space reviews while avoiding databases that don\u0027t require monitoring.", "", false, "false", "", "" ], [ "FileGroup", "Filters results to show only files within the specified filegroup name.\r\nUse this when analyzing specific filegroups for space utilization, I/O patterns, or growth planning.\r\nParticularly valuable when troubleshooting performance issues or planning filegroup-specific storage migrations.", "", false, "false", "", "" ], [ "InputObject", "Accepts database objects piped from other dbatools commands like Get-DbaDatabase.\r\nUse this for advanced filtering scenarios or when chaining multiple dbatools commands together.\r\nAllows you to pre-filter databases using complex criteria before analyzing their file information.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Storage", "File", "Data" ], "CommandName": "Get-DbaDbFileGroup", "Name": "Get-DbaDbFileGroup", "Author": "Patrick Flynn (@sqllensman)", "Syntax": "Get-DbaDbFileGroup [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [[-FileGroup] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.FileGroup\nReturns one FileGroup object per filegroup in the selected databases. For example, querying a database with PRIMARY, SECONDARY, and FILESTREAM filegroups returns three objects.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name (service name)\r\n- SqlInstance: The full SQL Server instance name (domain\\instance or instance)\r\n- Parent: The parent Database object name\r\n- FileGroupType: Type of filegroup (RowsFileGroup, FileStreamFileGroup, or MemoryOptimizedFileGroup)\r\n- Name: Name of the filegroup (e.g., PRIMARY, SECONDARY, FILESTREAM)\r\n- Size: Total size of the filegroup in kilobytes\nAdditional properties available (from SMO FileGroup object):\r\n- AbsolutePhysicalName: Absolute physical name of the filegroup\r\n- DefaultFileGroup: Boolean indicating if this is the default filegroup\r\n- Files: Collection of DataFile objects in the filegroup\r\n- IsDefault: Boolean indicating if this is the default filegroup\r\n- State: State of the filegroup (Normal, Offline, Defunct)\nAll properties from the base SMO FileGroup object are accessible even though only default properties are displayed without using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbFileGroup -SqlInstance sql2016\nReturn all FileGroups for all databases on instance sql2016\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbFileGroup -SqlInstance sql2016 -Database MyDB\nReturn all FileGroups for database MyDB on instance sql2016\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbFileGroup -SqlInstance sql2016 -FileGroup Primary\nReturns information on filegroup called Primary if it exists in any database on the server sql2016\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e\u0027localhost\u0027,\u0027localhost\\namedinstance\u0027 | Get-DbaDbFileGroup\nReturns information on all FileGroups for all databases on instances \u0027localhost\u0027,\u0027localhost\\namedinstance\u0027\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e\u0027localhost\u0027,\u0027localhost\\namedinstance\u0027 | Get-DbaDbFileGroup\nReturns information on all FileGroups for all databases on instances \u0027localhost\u0027,\u0027localhost\\namedinstance\u0027\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance SQL1\\SQLExpress,SQL2 -ExcludeDatabase model,master | Get-DbaDbFileGroup\nReturns information on all FileGroups for all databases except model and master on instances SQL1\\SQLExpress,SQL2", "Description": "Retrieves detailed filegroup information from one or more databases, including filegroup type, size, and configuration details. This function helps DBAs analyze database storage organization, plan storage capacity, and document database structure for compliance or migration planning. Returns filegroup objects that can be filtered by database or specific filegroup names, making it useful for targeted storage analysis and troubleshooting performance issues related to data distribution.", "Links": "https://dbatools.io/Get-DbaDbFileGroup", "Synopsis": "Retrieves filegroup configuration and storage details from SQL Server databases", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input.", "", false, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to analyze for filegroup information. Accepts wildcards and multiple database names.\r\nUse this when you need to focus on specific databases instead of scanning all databases on the instance, which is helpful for large environments or targeted storage analysis.", "", false, "false", "", "" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase pipeline input for processing filegroups.\r\nUse this when you want to chain database filtering with filegroup analysis, such as excluding system databases or filtering by database properties before examining storage structure.", "", false, "true (ByValue)", "", "" ], [ "FileGroup", "Filters results to specific filegroups by name, such as \u0027PRIMARY\u0027 or custom filegroups.\r\nUse this when troubleshooting storage issues with particular filegroups or when you need to verify configuration of specific data placement strategies.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Storage", "Data", "File", "Log" ], "CommandName": "Get-DbaDbFileGrowth", "Name": "Get-DbaDbFileGrowth", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaDbFileGrowth [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database file across all specified databases.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: Name of the database containing the file\r\n- MaxSize: Maximum size the file can grow to - displays as dbasize object (KB, MB, GB, etc.)\r\n- GrowthType: How the file grows - either \"Percent\" or \"kb\"\r\n- Growth: Growth increment value - interpretation depends on GrowthType (percentage or KB)\r\n- File: Logical name of the file within SQL Server (aliased from LogicalName)\r\n- FileName: Operating system file path (aliased from PhysicalName)\r\n- State: Current state of the file (ONLINE, OFFLINE, etc.)\nAdditional properties available (from Get-DbaDbFile object):\r\n- DatabaseID: Internal ID of the database\r\n- FileGroupName: Name of the filegroup containing this file (NULL for log files)\r\n- ID: File ID within the database\r\n- Type: Type of file - 0 for data file, 1 for log file (Integer)\r\n- TypeDescription: Human-readable file type (ROWS or LOG)\r\n- LogicalName: Logical name of the file within SQL Server\r\n- PhysicalName: Operating system file path\r\n- NextGrowthEventSize: Size that will be added during the next autogrow event - displays as dbasize object\r\n- Size: Current size of the file - displays as dbasize object\r\n- UsedSpace: Space currently used within the file - displays as dbasize object\r\n- AvailableSpace: Free space within the file (Size - UsedSpace) - displays as dbasize object\r\n- IsOffline: Boolean indicating if the file is offline\r\n- IsReadOnly: Boolean indicating if the file is read-only\r\n- IsReadOnlyMedia: Boolean indicating if the underlying storage media is read-only\r\n- IsSparse: Boolean indicating if the file is sparse (snapshots)\r\n- NumberOfDiskWrites: Count of write operations to the file since instance startup\r\n- NumberOfDiskReads: Count of read operations from the file since instance startup\r\n- ReadFromDisk: Total bytes read from the file since instance startup - displays as dbasize object\r\n- WrittenToDisk: Total bytes written to the file since instance startup - displays as dbasize object\r\n- VolumeFreeSpace: Free space available on the volume containing this file - displays as dbasize object\r\n- FileGroupDataSpaceId: Internal ID of the filegroup data space\r\n- FileGroupType: Type of filegroup (NULL for log files, or name for data filegroups)\r\n- FileGroupTypeDescription: Description of filegroup type\r\n- FileGroupDefault: Boolean indicating if this is the default filegroup\r\n- FileGroupReadOnly: Boolean indicating if the filegroup is read-only\nAll properties from the base object are accessible even though only default properties are displayed without using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbFileGrowth -SqlInstance sql2017, sql2016, sql2012\nGets all database file growths on sql2017, sql2016, sql2012\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbFileGrowth -SqlInstance sql2017, sql2016, sql2012 -Database pubs\nGets the database file growth info for pubs on sql2017, sql2016, sql2012\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2016 -Database test | Get-DbaDbFileGrowth\nGets the test database file growth information on sql2016", "Description": "Retrieves auto-growth configuration for data and log files across SQL Server databases, including growth type (percentage or fixed MB), growth increment values, and maximum size limits. This function helps DBAs quickly identify databases with problematic growth settings like percentage-based growth on large files, unlimited growth configurations, or insufficient growth increments that could cause performance issues during auto-growth events.", "Links": "https://dbatools.io/Get-DbaDbFileGrowth", "Synopsis": "Retrieves database file auto-growth settings and maximum size limits", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to analyze for file growth settings. Accepts wildcards for pattern matching.\r\nUse this when you need to check growth configuration for specific databases instead of all databases on the instance.", "", false, "false", "", "" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase via pipeline input.\r\nUse this when you want to analyze file growth settings for databases already retrieved by another dbatools command.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Storage", "File", "Data", "Log", "Backup" ], "CommandName": "Get-DbaDbFileMapping", "Name": "Get-DbaDbFileMapping", "Author": "Chrissy LeMaire (@cl), netnerds.net | Andreas Jordan (@JordanOrdix), ordix.de", "Syntax": "Get-DbaDbFileMapping [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per accessible database provided as input. Each object contains the file mapping information needed for restore operations.\nProperties:\r\n- ComputerName: The name of the computer where the SQL Server instance is running\r\n- InstanceName: The instance name of the SQL Server (e.g., \"MSSQLSERVER\" or \"SQLEXPRESS\")\r\n- SqlInstance: The full SQL Server instance name (computer\\instance format)\r\n- Database: The name of the database from which file mappings were extracted\r\n- FileMapping: A hashtable mapping logical file names (keys) to their physical file paths (values), compatible with Restore-DbaDatabase", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$filemap = Get-DbaDbFileMapping -SqlInstance sql2016 -Database test\nPS C:\\\u003e Get-ChildItem \\\\nas\\db\\backups\\test | Restore-DbaDatabase -SqlInstance sql2019 -Database test -FileMapping $filemap.FileMapping\nRestores test to sql2019 using the file structure built from the existing database on sql2016", "Description": "Extracts the logical-to-physical file name mappings from an existing database and returns them in a hashtable format compatible with Restore-DbaDatabase. This eliminates the need to manually specify file paths when restoring databases to different servers or locations. The function reads both data files and log files from the database\u0027s file groups and creates a complete mapping that preserves the original file structure during restore operations.", "Links": "https://dbatools.io/Get-DbaDbFileMapping", "Synopsis": "Creates file mapping hashtable from existing database for use in restore operations", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input.", "", false, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to extract file mappings from. Accepts wildcards for pattern matching.\r\nUse this when you need file mappings for specific databases instead of all databases on the instance.", "", false, "false", "", "" ], [ "InputObject", "Accepts database objects directly from Get-DbaDatabase or other dbatools database functions via pipeline.\r\nUse this when you want to chain database operations or work with pre-filtered database collections.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Database", "ForeignKey", "Table" ], "CommandName": "Get-DbaDbForeignKey", "Name": "Get-DbaDbForeignKey", "Author": "Claudio Silva (@ClaudioESSilva), claudioessilva.eu", "Syntax": "Get-DbaDbForeignKey [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-ExcludeSystemTable] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.ForeignKey\nReturns one ForeignKey object per foreign key constraint found in the specified databases. Each object represents a single foreign key relationship between tables.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: The database name containing the foreign key\r\n- Schema: The schema name containing the table with the foreign key\r\n- Table: The table name that contains the foreign key (referencing table)\r\n- ID: Unique identifier of the foreign key constraint\r\n- CreateDate: DateTime when the foreign key constraint was created\r\n- DateLastModified: DateTime when the foreign key constraint was last modified\r\n- Name: The name of the foreign key constraint\r\n- IsEnabled: Boolean indicating if the foreign key constraint is currently enabled\r\n- IsChecked: Boolean indicating if the constraint is enforced during INSERT/UPDATE operations\r\n- NotForReplication: Boolean indicating if the constraint applies to replication operations\r\n- ReferencedKey: The primary key or unique key being referenced by this foreign key\r\n- ReferencedTable: The name of the table being referenced (referenced table)\r\n- ReferencedTableSchema: The schema name of the referenced table\nAdditional properties available (from SMO ForeignKey object):\r\n- Columns: Collection of columns that make up the foreign key\r\n- DeleteAction: Action to take when the referenced row is deleted (NoAction, Cascade, SetNull, SetDefault)\r\n- UpdateAction: Action to take when the referenced key is updated (NoAction, Cascade, SetNull, SetDefault)\r\n- DatabaseEngineEdition: The SQL Server edition where the foreign key exists\r\n- DatabaseEngineType: The type of database engine\r\n- IsMemoryOptimized: Boolean indicating if the parent table is memory-optimized\r\n- IsSystemNamed: Boolean indicating if the constraint was system-generated (auto-named)\r\n- State: SMO object state (Existing, Creating, Dropping, etc.)\r\n- Urn: Unique Resource Name for the constraint\r\n- ExtendedProperties: Extended properties attached to the constraint\nAll properties from the base SMO ForeignKey object are accessible even though only default properties are displayed without using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbForeignKey -SqlInstance sql2016\nGets all database Foreign Keys.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbForeignKey -SqlInstance Server1 -Database db1\nGets the Foreign Keys for the db1 database.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbForeignKey -SqlInstance Server1 -ExcludeDatabase db1\nGets the Foreign Keys for all databases except db1.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbForeignKey -SqlInstance Server1 -ExcludeSystemTable\nGets the Foreign Keys from all tables that are not system objects from all databases.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Get-DbaDbForeignKey\nGets the Foreign Keys for the databases on Sql1 and Sql2/sqlexpress.", "Description": "Retrieves all foreign key constraint definitions from tables across one or more SQL Server databases.\nEssential for documenting referential integrity relationships, analyzing table dependencies before migrations, and troubleshooting cascade operations.\nReturns detailed foreign key properties including referenced tables, schema information, and constraint status (enabled/disabled, checked/unchecked).\nSupports filtering by database and excluding system tables to focus on user-defined constraints.", "Links": "https://dbatools.io/Get-DbaDbForeignKey", "Synopsis": "Retrieves foreign key constraints from SQL Server database tables", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to scan for foreign key constraints. Accepts database names, wildcards, or arrays.\r\nUse this when you need to focus on specific databases rather than scanning all accessible databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific databases from the foreign key scan. Useful for skipping large databases, test environments, or databases known to have no relevant constraints.\r\nCommonly used to exclude system databases like master, model, msdb, and tempdb when focusing on user databases.", "", false, "false", "", "" ], [ "ExcludeSystemTable", "Excludes system tables from the foreign key analysis, focusing only on user-created tables.\r\nUse this switch when documenting application schemas or analyzing business logic relationships, as system table foreign keys are typically not relevant for most DBA tasks.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": "DBCC", "CommandName": "Get-DbaDbIdentity", "Name": "Get-DbaDbIdentity", "Author": "Patrick Flynn (@sqllensman)", "Syntax": "Get-DbaDbIdentity [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-Table] \u003cString[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per table checked. Each object contains the current identity seed value and the actual highest value in the identity column.\nProperties:\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name (service name)\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: The name of the database containing the table\r\n- Table: The name of the table that was checked (schema-qualified)\r\n- Cmd: The T-SQL DBCC CHECKIDENT command that was executed\r\n- IdentityValue: The current seed value of the identity column (integer or null if unable to determine)\r\n- ColumnValue: The highest value currently in the identity column (integer or null if unable to determine)\r\n- Output: The raw DBCC output message from SQL Server", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbIdentity -SqlInstance SQLServer2017 -Database AdventureWorks2014 -Table \u0027Production.ScrapReason\u0027\nConnects to AdventureWorks2014 on instance SqlServer2017 using Windows Authentication and runs the command DBCC CHECKIDENT(\u0027Production.ScrapReason\u0027, NORESEED) to return the current identity value.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e \u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Get-DbaDbIdentity -SqlCredential $cred -Database AdventureWorks2014 -Table \u0027Production.ScrapReason\u0027\nConnects to AdventureWorks2014 on instances Sql1 and Sql2/sqlexpress using sqladmin credential and runs the command DBCC CHECKIDENT(\u0027Production.ScrapReason\u0027, NORESEED) to return the current identity \r\nvalue.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$query = \"SELECT QUOTENAME(SCHEMA_NAME(t.schema_id)) + \u0027.\u0027 + QUOTENAME(t.name) AS TableName FROM sys.columns c INNER JOIN sys.tables t ON t.object_id = c.object_id WHERE is_identity = 1 AND \r\nis_memory_optimized = 0\"\nPS C:\\\u003e $IdentityTables = Invoke-DbaQuery -SqlInstance SQLServer2017 -Database AdventureWorks2014 -Query $query -As SingleValue\r\nPS C:\\\u003e Get-DbaDbIdentity -SqlInstance SQLServer2017 -Database AdventureWorks2014 -Table $IdentityTables\nChecks the current identity value for all non memory optimized tables with an Identity in the AdventureWorks2014 database on the SQLServer2017 instance.", "Description": "Executes DBCC CHECKIDENT with the NORESEED option to retrieve current identity seed and column values from specified tables without modifying anything. This provides a safe way to inspect identity column status across multiple tables, databases, and instances simultaneously.\n\nDBAs use this when troubleshooting identity gaps, planning bulk operations, or auditing identity column usage before performing maintenance tasks. Unlike running DBCC CHECKIDENT manually, this command structures the output into readable PowerShell objects that show both the current identity value and the actual highest value in the column.\n\nThe NORESEED option ensures no changes are made to your tables - it\u0027s purely informational. The function parses the DBCC output to extract specific identity metrics, making it ideal for scripted monitoring and reporting workflows.\n\nRead more:\n - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checkident-transact-sql", "Links": "https://dbatools.io/Get-DbaDbIdentity", "Synopsis": "Retrieves current identity values from tables without reseeding using DBCC CHECKIDENT", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to check for identity column values. If not specified, all accessible databases on the instance are processed.\r\nUse this to focus on specific databases when you don\u0027t need identity information from every database on the server.", "", false, "false", "", "" ], [ "Table", "Specifies the table names to check for current identity seed and column values. Accepts schema-qualified names like \u0027Production.ScrapReason\u0027.\r\nThis parameter is required since DBCC CHECKIDENT must target specific tables. Use a query against sys.columns to find all tables with identity columns if needed.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "Shows what would happen if the cmdlet runs. The cmdlet is not run.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before running the cmdlet.", "cf", false, "false", "", "" ] ] }, { "Tags": "LogShipping", "CommandName": "Get-DbaDbLogShipError", "Name": "Get-DbaDbLogShipError", "Author": "Sander Stad (@sqlstad), sqlstad.nl", "Syntax": "Get-DbaDbLogShipError [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-ExcludeDatabase] \u003cString[]\u003e] [[-Action] \u003cString[]\u003e] [[-DateTimeFrom] \u003cDateTime\u003e] [[-DateTimeTo] \u003cDateTime\u003e] [-Primary] [-Secondary] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per log shipping error found. If no errors exist, nothing is returned.\nProperties:\r\n- ComputerName: The name of the computer hosting the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance format)\r\n- Database: Name of the database involved in the log shipping error\r\n- Instance: The role where the error occurred - either \"Primary\" (backup operation) or \"Secondary\" (copy or restore operation)\r\n- Action: The type of log shipping operation that failed - \"Backup\" (primary server), \"Copy\" (between servers), or \"Restore\" (secondary server)\r\n- SessionID: Unique identifier for the log shipping session in which the error occurred\r\n- SequenceNumber: Sequential number of this error within the session for ordering multiple errors\r\n- LogTime: DateTime when the error was recorded in the log shipping monitor tables\r\n- Message: The detailed error message describing what went wrong (e.g., file not found, insufficient disk space, network timeout)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbLogShipError -SqlInstance sql1\nGet all the log shipping errors that occurred\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbLogShipError -SqlInstance sql1 -Action Backup\nGet the errors that have something to do with the backup of the databases\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbLogShipError -SqlInstance sql1 -Secondary\nGet the errors that occurred on the secondary instance.\r\nThis will return the copy of the restore actions because those only occur on the secondary instance\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbLogShipError -SqlInstance sql1 -DateTimeFrom \"01/05/2018\"\nGet the errors that have occurred from \"01/05/2018\". This can also be of format \"yyyy-MM-dd\"\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaDbLogShipError -SqlInstance sql1 -Secondary -DateTimeFrom \"01/05/2018\" -DateTimeTo \"2018-01-07\"\nGet the errors that have occurred between \"01/05/2018\" and \"01/07/2018\".\r\nSee that is doesn\u0027t matter how the date is represented.", "Description": "Queries the log shipping monitor error detail table in msdb to return comprehensive error information when log shipping operations fail.\nIdentifies which specific action failed (backup on primary, copy, or restore on secondary) along with session details and error messages.\nSaves time by consolidating error details from both primary and secondary instances into a single view, so you don\u0027t have to manually query multiple system tables.\nEssential for troubleshooting log shipping failures and determining whether issues occurred during backup, file copy, or database restore phases.", "Links": "https://dbatools.io/Get-DbaDbLogShipError", "Synopsis": "Retrieves log shipping error details from msdb to troubleshoot failed backup, copy, and restore operations", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to include when retrieving log shipping errors. Requires exact database names, not wildcards.\r\nUse this when troubleshooting specific databases rather than reviewing all log shipped databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific databases from the log shipping error results. Requires exact database names, not wildcards.\r\nUseful when you want to see errors for all databases except certain ones, like excluding test databases from production error reviews.", "", false, "false", "", "" ], [ "Action", "Filters errors by log shipping operation type: Backup (primary), Copy (between servers), or Restore (secondary).\r\nUse this to isolate which phase of log shipping is failing when troubleshooting multi-step log shipping workflows.", "", false, "false", "", "Backup,Copy,Restore" ], [ "DateTimeFrom", "Sets the earliest date and time for error records to include in results.\r\nEssential for focusing on recent failures or analyzing errors that occurred after a specific event or change.", "", false, "false", "", "" ], [ "DateTimeTo", "Sets the latest date and time for error records to include in results.\r\nCombined with DateTimeFrom, this creates a specific time window for analyzing log shipping failures during maintenance windows or incidents.", "", false, "false", "", "" ], [ "Primary", "Returns only errors from backup operations that occur on the primary server.\r\nUse this when troubleshooting backup failures or primary-side log shipping issues like insufficient disk space or backup device problems.", "", false, "false", "False", "" ], [ "Secondary", "Returns only errors from copy and restore operations that occur on secondary servers.\r\nUse this when troubleshooting file transfer failures or restore issues on the destination server, such as network connectivity or disk space problems.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Storage", "Space", "Log", "File" ], "CommandName": "Get-DbaDbLogSpace", "Name": "Get-DbaDbLogSpace", "Author": "Jess Pomfret, JessPomfret.com", "Syntax": "Get-DbaDbLogSpace [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-ExcludeDatabase] \u003cString[]\u003e] [-ExcludeSystemDatabase] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database containing transaction log space usage metrics.\nProperties:\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name (service name)\r\n- SqlInstance: The full SQL Server instance name (computer\\instance format)\r\n- Database: The name of the database\r\n- LogSize: The total size of the transaction log file(s) for the database, formatted as a dbasize object (e.g., \"10 MB\", \"1 GB\")\r\n- LogSpaceUsedPercent: The percentage of the transaction log that is currently in use (0-100)\r\n- LogSpaceUsed: The amount of space currently used in the transaction log file(s), formatted as a dbasize object\nThe command uses sys.dm_db_log_space_usage DMV on SQL Server 2012+ or DBCC SQLPERF(logspace) on earlier versions, but returns identical output structure for both.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbLogSpace -SqlInstance Server1\nReturns the transaction log usage information for all databases on Server1\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbLogSpace -SqlInstance Server1 -Database Database1, Database2\nReturns the transaction log usage information for both Database1 and Database 2 on Server1\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbLogSpace -SqlInstance Server1 -ExcludeDatabase Database3\nReturns the transaction log usage information for all databases on Server1, except Database3\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbLogSpace -SqlInstance Server1 -ExcludeSystemDatabase\nReturns the transaction log usage information for all databases on Server1, except the system databases\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaRegisteredServer -SqlInstance cmsServer | Get-DbaDbLogSpace -Database Database1\nReturns the transaction log usage information for Database1 for a group of servers from SQL Server Central Management Server (CMS).", "Description": "Collects detailed transaction log metrics including total size, used space percentage, and used space in bytes for databases across SQL Server instances. Uses the sys.dm_db_log_space_usage DMV on SQL Server 2012+ or DBCC SQLPERF(logspace) on older versions.\n\nEssential for proactive log space monitoring to prevent unexpected transaction log growth, identify databases approaching log capacity limits, and plan log file sizing. Helps DBAs avoid transaction failures caused by full transaction logs and optimize log file allocation strategies.", "Links": "https://dbatools.io/Get-DbaDbLogSpace", "Synopsis": "Retrieves transaction log space usage and capacity information from SQL Server databases.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "SQL Server name or SMO object representing the SQL Server to connect to. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to check for transaction log space usage. Accepts wildcards for pattern matching.\r\nUse this when you need to monitor specific databases instead of checking all databases on the instance, particularly useful for focusing on high-growth or critical databases.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies databases to skip when checking transaction log space usage. Accepts wildcards for pattern matching.\r\nUse this to exclude databases you don\u0027t need to monitor regularly, such as test databases, read-only databases, or databases with known stable log usage patterns.", "", false, "false", "", "" ], [ "ExcludeSystemDatabase", "Excludes system databases (master, model, msdb, tempdb) from the transaction log space report.\r\nUse this when focusing on user databases only, as system database log usage is typically managed differently and may not require the same monitoring attention.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Mail", "DbMail", "Email" ], "CommandName": "Get-DbaDbMail", "Name": "Get-DbaDbMail", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaDbMail [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Mail.SqlMail\nReturns one SqlMail object per SQL Server instance with Database Mail configuration details. Each object includes comprehensive collections of mail profiles, accounts, and configuration settings for \r\nthat instance.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Profiles: Collection of Database Mail profile objects configured on the instance\r\n- Accounts: Collection of Database Mail account objects configured on the instance\r\n- ConfigurationValues: Collection of Database Mail configuration settings (MaxFileSize, ProhibitedExtensions, etc.)\r\n- Properties: Collection of additional mail properties\nAll properties from the base SMO SqlMail object are accessible using Select-Object *. Use Get-DbaDbMailProfile, Get-DbaDbMailAccount, Get-DbaDbMailConfig, and Get-DbaDbMailServer commands to retrieve \r\ndetailed information about specific profiles, accounts, configuration settings, and mail servers from these collections.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbMail -SqlInstance sql01\\sharepoint\nReturns the db mail server object on sql01\\sharepoint\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbMail -SqlInstance sql01\\sharepoint | Select-Object *\nReturns the db mail server object on sql01\\sharepoint then return a bunch more columns\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$servers = \"sql2014\",\"sql2016\", \"sqlcluster\\sharepoint\"\nPS C:\\\u003e $servers | Get-DbaDbMail\nReturns the db mail server object for \"sql2014\",\"sql2016\" and \"sqlcluster\\sharepoint\"", "Description": "Retrieves the complete Database Mail configuration from one or more SQL Server instances, including mail profiles, SMTP accounts, configuration values, and properties. This function provides a quick way to audit your email setup across multiple servers, troubleshoot mail delivery issues, or document your Database Mail configuration for compliance purposes. The output includes server identification details to help when working with multiple instances.", "Links": "https://dbatools.io/Get-DbaDbMail", "Synopsis": "Retrieves Database Mail configuration including profiles, accounts, and settings from SQL Server instances", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Mail", "DbMail", "Email" ], "CommandName": "Get-DbaDbMailAccount", "Name": "Get-DbaDbMailAccount", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaDbMailAccount [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Account] \u003cString[]\u003e] [[-ExcludeAccount] \u003cString[]\u003e] [[-InputObject] \u003cSqlMail[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Mail.SqlMailAccount\nReturns one or more Database Mail account objects from the target SQL Server instance(s). Each account object includes configuration details for sending emails through Database Mail.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- ID: The unique identifier (int) for the Database Mail account within the instance\r\n- Name: The name of the Database Mail account\r\n- DisplayName: The display name used in the \"From\" field of emails sent by this account\r\n- Description: Text description of the account\r\n- EmailAddress: The email address used as the sender (from address) for this account\r\n- ReplyToAddress: The reply-to email address for emails sent from this account\r\n- IsBusyAccount: Boolean indicating if the account is currently busy sending messages\r\n- MailServers: Collection of SMTP servers configured for this account\r\n- MailProfile: Collection of Database Mail profile names associated with this account\nAdditional properties available (from SMO SqlMailAccount object):\r\n- Account: The account owner or associated account information\r\n- AccountType: Type of the account\r\n- CreateDate: DateTime when the account was created\r\n- Urn: The unified resource name (URN) for the object\r\n- Parent: Reference to the parent SqlMail object\r\n- Properties: Collection of property objects for the account\r\n- State: Current state of the account object (Existing, Creating, Deleting)\r\n- Uid: Unique identifier for the account\nUse Select-Object * to access all available properties if needed.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbMailAccount -SqlInstance sql01\\sharepoint\nReturns Database Mail accounts on sql01\\sharepoint.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbMailAccount -SqlInstance sql01\\sharepoint -Account \u0027The DBA Team\u0027\nReturns \u0027The DBA Team\u0027 Database Mail account from sql01\\sharepoint.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbMailAccount -SqlInstance sql01\\sharepoint | Select-Object *\nReturns the Database Mail accounts on sql01\\sharepoint then return a bunch more columns.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$servers = sql2014, sql2016, sqlcluster\\sharepoint\nPS C:\\\u003e $servers | Get-DbaDbMail | Get-DbaDbMailAccount\nReturns the Database Mail accounts for sql2014, sql2016 and sqlcluster\\sharepoint.", "Description": "Retrieves Database Mail account configurations including email addresses, display names, SMTP server settings, and authentication details from SQL Server instances. This function helps DBAs audit email configurations across their environment, troubleshoot mail delivery issues, and document Database Mail settings for compliance or migration purposes. The returned account objects include connection details, server configurations, and account properties that can be used to verify proper Database Mail setup.", "Links": "https://dbatools.io/Get-DbaDbMailAccount", "Synopsis": "Retrieves Database Mail account configurations from SQL Server instances", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Account", "Specifies one or more Database Mail account names to retrieve. Accepts exact account names and supports multiple values.\r\nUse this when you need to check specific mail accounts rather than retrieving all configured accounts on the instance.", "", false, "false", "", "" ], [ "ExcludeAccount", "Specifies one or more Database Mail account names to exclude from results. Accepts exact account names and supports multiple values.\r\nUse this when you want to retrieve most accounts but skip specific ones, such as excluding test or deprecated accounts from auditing reports.", "", false, "false", "", "" ], [ "InputObject", "Accepts SqlMail objects from the pipeline, typically from Get-DbaDbMail. Allows you to chain Database Mail commands together.\r\nUse this when processing multiple instances through Get-DbaDbMail or when working with previously retrieved Database Mail configurations.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Mail", "DbMail", "Email" ], "CommandName": "Get-DbaDbMailConfig", "Name": "Get-DbaDbMailConfig", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaDbMailConfig [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Name] \u003cString[]\u003e] [[-InputObject] \u003cSqlMail[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Mail.ConfigurationValue\nReturns one Database Mail configuration setting per object with added properties from the parent SqlMail object.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Name: The configuration setting name (e.g., MaxFileSize, ProhibitedExtensions, DatabaseMailExeMinLifeTime, LoggingLevel)\r\n- Value: The current value of the configuration setting\r\n- Description: Human-readable description of what the configuration setting controls\nAdditional properties available (from SMO ConfigurationValue object):\r\n- Parent: Reference to the parent SqlMail object\r\n- Urn: The uniform resource name for the configuration value object\r\n- Properties: Collection of SQL Server object properties\r\n- State: The current state of the object (Existing, Creating, Pending, etc.)\nAll properties from the base SMO ConfigurationValue object are accessible using Select-Object * even though only default properties are displayed by default.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbMailConfig -SqlInstance sql01\\sharepoint\nReturns DBMail configs on sql01\\sharepoint\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbMailConfig -SqlInstance sql01\\sharepoint -Name ProhibitedExtensions\nReturns the ProhibitedExtensions configuration on sql01\\sharepoint\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbMailConfig -SqlInstance sql01\\sharepoint | Select-Object *\nReturns the DBMail configs on sql01\\sharepoint then return a bunch more columns\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$servers = \"sql2014\",\"sql2016\", \"sqlcluster\\sharepoint\"\nPS C:\\\u003e $servers | Get-DbaDbMail | Get-DbaDbMailConfig\nReturns the DBMail configs for \"sql2014\",\"sql2016\" and \"sqlcluster\\sharepoint\"", "Description": "Retrieves all Database Mail configuration values from SQL Server, including settings like MaxFileSize, ProhibitedExtensions, DatabaseMailExeMinLifeTime, and LoggingLevel.\nThis function helps DBAs audit current Database Mail configurations, troubleshoot email delivery issues, and verify compliance with organizational email policies.\nYou can retrieve all configuration settings or filter by specific configuration names to focus on particular settings.\nThe output includes the configuration name, current value, and description for each setting across your SQL Server environment.", "Links": "https://dbatools.io/Get-DbaDbMailConfig", "Synopsis": "Retrieves Database Mail configuration settings from SQL Server instances", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Name", "Specifies which Database Mail configuration settings to retrieve by name, such as MaxFileSize, ProhibitedExtensions, or LoggingLevel.\r\nUse this when you need to check specific configuration values instead of retrieving all Database Mail settings.\r\nAccepts multiple configuration names and supports aliases Config and ConfigName.", "Config,ConfigName", false, "false", "", "" ], [ "InputObject", "Accepts Database Mail objects from Get-DbaDbMail for pipeline processing.\r\nUse this when chaining multiple Database Mail functions together or when you already have Database Mail objects loaded.\r\nAllows you to retrieve configurations from multiple SQL Server instances efficiently through the pipeline.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Mail", "DbMail", "Email" ], "CommandName": "Get-DbaDbMailHistory", "Name": "Get-DbaDbMailHistory", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaDbMailHistory [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Since] \u003cDateTime\u003e] [[-Status] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per Database Mail message from the MSDB sysmail_allitems table.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Profile: The Database Mail profile name associated with this message\r\n- Recipients: Email addresses of the primary recipients\r\n- CopyRecipients: Email addresses of the CC recipients\r\n- BlindCopyRecipients: Email addresses of the BCC recipients\r\n- Subject: The subject line of the email message\r\n- Importance: The importance level (Low, Normal, High)\r\n- Sensitivity: The sensitivity level (Normal, Personal, Private, Confidential)\r\n- FileAttachments: File attachments included with the message\r\n- AttachmentEncoding: Character encoding used for attachments\r\n- SendRequestDate: DateTime when the message was requested to be sent\r\n- SendRequestUser: Windows or SQL login that initiated the email\r\n- SentStatus: The delivery status (Unsent, Sent, Failed, Retrying)\r\n- SentDate: DateTime when the message was actually sent (or failed)\nAdditional properties available (via Select-Object *):\r\n- MailItemId: Unique identifier for this mail message in the sysmail_allitems table\r\n- ProfileId: Unique identifier of the Database Mail profile\r\n- Body: The message body text\r\n- BodyFormat: The body format (HTML or TEXT)\r\n- Query: T-SQL query that generated query results attached to the message\r\n- ExecuteQueryDatabase: Database where the query was executed\r\n- AttachQueryResultAsFile: Whether query results were attached as a file\r\n- QueryResultHeader: Whether query result headers were included in the attachment\r\n- QueryResultWidth: Width of the query result output\r\n- QueryResultSeparator: Character used to separate columns in query results\r\n- ExcludeQueryOutput: Whether to exclude the query execution output\r\n- AppendQueryError: Whether to append query errors to the output\r\n- SentAccountId: Account ID used to send the message\r\n- LastModDate: DateTime when this mail item record was last modified\r\n- LastModUser: Login that last modified this mail item record", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbMailHistory -SqlInstance sql01\\sharepoint\nReturns the entire DBMail history on sql01\\sharepoint\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbMailHistory -SqlInstance sql01\\sharepoint | Select-Object *\nReturns the entire DBMail history on sql01\\sharepoint then return a bunch more columns\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$servers = \"sql2014\",\"sql2016\", \"sqlcluster\\sharepoint\"\nPS C:\\\u003e $servers | Get-DbaDbMailHistory\nReturns the all DBMail history for \"sql2014\",\"sql2016\" and \"sqlcluster\\sharepoint\"", "Description": "Retrieves comprehensive Database Mail history from the msdb.dbo.sysmail_allitems table, including delivery status, recipients, subject lines, and timestamps. This function helps DBAs troubleshoot email delivery issues, audit mail activity for compliance reporting, and monitor Database Mail performance. You can filter results by send date or delivery status (Sent, Failed, Unsent, Retrying) to focus on specific timeframes or problem emails.", "Links": "https://dbatools.io/Get-DbaDbMailHistory", "Synopsis": "Retrieves Database Mail history from SQL Server\u0027s msdb database for troubleshooting and compliance", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", false, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Since", "Filters mail history to only include emails sent after the specified date and time.\r\nUse this when troubleshooting recent delivery issues or generating reports for specific time periods.\r\nAccepts standard PowerShell DateTime objects like (Get-Date).AddDays(-7) for the past week.", "", false, "false", "", "" ], [ "Status", "Filters results to only show emails with the specified delivery status.\r\nUse \u0027Failed\u0027 to identify delivery problems, \u0027Unsent\u0027 for queued messages, or \u0027Retrying\u0027 for current retry attempts.\r\nAccepts multiple values: Unsent, Sent, Failed, and Retrying.", "", false, "false", "", "Unsent,Sent,Failed,Retrying" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Mail", "DbMail", "Email" ], "CommandName": "Get-DbaDbMailLog", "Name": "Get-DbaDbMailLog", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaDbMailLog [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Since] \u003cDateTime\u003e] [[-Type] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per log entry in the Database Mail event log.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The name of the computer hosting the SQL Server instance\r\n- InstanceName: The name of the SQL Server instance\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- LogDate: DateTime when the event was logged\r\n- EventType: The type of event (Error, Warning, Success, Information, or Internal)\r\n- Description: Detailed description of the event or error message\r\n- Login: The user who last modified this log entry\nAdditional properties available (accessible via Select-Object *):\r\n- LogId: Unique identifier for the log entry (integer)\r\n- ProcessId: Process ID associated with the event (integer)\r\n- MailItemId: Identifier of the mail item, if applicable (integer)\r\n- AccountId: Identifier of the Database Mail account (integer)\r\n- LastModDate: DateTime when the log entry was last modified\r\n- LastModUser: The user who last modified the log entry\nAll properties are accessible even though only default properties are displayed without using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbMailLog -SqlInstance sql01\\sharepoint\nReturns the entire DBMail log on sql01\\sharepoint\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbMailLog -SqlInstance sql01\\sharepoint | Select-Object *\nReturns the entire DBMail log on sql01\\sharepoint, includes all returned information.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$servers = \"sql2014\",\"sql2016\", \"sqlcluster\\sharepoint\"\nPS C:\\\u003e $servers | Get-DbaDbMailLog -Type Error, Information\nReturns only the Error and Information DBMail log for \"sql2014\",\"sql2016\" and \"sqlcluster\\sharepoint\"", "Description": "Retrieves Database Mail event logs from the msdb.dbo.sysmail_event_log table, providing detailed information about email send attempts, failures, and system events. This function is essential for diagnosing Database Mail problems, monitoring email delivery status, and identifying configuration issues. You can filter results by date range and event type (Error, Warning, Success, Information, Internal) to focus on specific troubleshooting scenarios rather than manually querying the mail log tables.", "Links": "https://dbatools.io/Get-DbaDbMailLog", "Synopsis": "Retrieves Database Mail event logs from msdb for troubleshooting email delivery issues", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", false, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Since", "Filters log entries to only include events that occurred on or after the specified date and time.\r\nUse this when troubleshooting recent mail delivery issues or investigating problems within a specific timeframe.", "", false, "false", "", "" ], [ "Type", "Filters log entries by event type to focus troubleshooting on specific mail system behaviors.\r\nUse \u0027Error\u0027 to identify failed deliveries, \u0027Warning\u0027 for potential issues, \u0027Success\u0027 to verify deliveries, \u0027Information\u0027 for general events, or \u0027Internal\u0027 for system-level Database Mail operations.", "", false, "false", "", "Error,Warning,Success,Information,Internal" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Mail", "DbMail", "Email" ], "CommandName": "Get-DbaDbMailProfile", "Name": "Get-DbaDbMailProfile", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaDbMailProfile [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Profile] \u003cString[]\u003e] [[-ExcludeProfile] \u003cString[]\u003e] [[-InputObject] \u003cSqlMail[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Mail.MailProfile\nReturns one or more Database Mail profile objects from the target SQL Server instance(s). Each profile object includes configuration details for organizing mail accounts used for notifications and \r\nalerts.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- ID: The unique identifier (int) for the Database Mail profile within the instance\r\n- Name: The name of the Database Mail profile\r\n- Description: Text description of the profile\u0027s purpose or intended use\r\n- ForceDeleteForActiveProfiles: Boolean indicating if the profile will be forcefully deleted even if actively used\r\n- IsBusyProfile: Boolean indicating if the profile is currently busy processing mail messages\r\n- MailAccount: Collection of Database Mail account names associated with this profile\nAdditional properties available (from SMO MailProfile object):\r\n- Parent: Reference to the parent SqlMail object\r\n- Properties: Collection of property objects for the profile\r\n- State: Current state of the profile object (Existing, Creating, Deleting)\r\n- Urn: The unified resource name (URN) for the object\r\n- Uid: Unique identifier for the profile\r\n- MailAccountMemberships: Collection of mail accounts associated with this profile\r\n- LastModificationTime: DateTime when the profile was last modified (if available)\nUse Select-Object * to access all available properties if needed.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbMailProfile -SqlInstance sql01\\sharepoint\nReturns DBMail profiles on sql01\\sharepoint\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbMailProfile -SqlInstance sql01\\sharepoint -Profile \u0027The DBA Team\u0027\nReturns The DBA Team DBMail profile from sql01\\sharepoint\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbMailProfile -SqlInstance sql01\\sharepoint | Select-Object *\nReturns the DBMail profiles on sql01\\sharepoint then return a bunch more columns\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$servers = \"sql2014\", \"sql2016\", \"sqlcluster\\sharepoint\"\nPS C:\\\u003e $servers | Get-DbaDbMail | Get-DbaDbMailProfile\nReturns the DBMail profiles for \"sql2014\", \"sql2016\" and \"sqlcluster\\sharepoint\"\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$servers = \"sql2014\", \"sql2016\", \"sqlcluster\\sharepoint\"\nPS C:\\\u003e Get-DbaDbMailProfile -SqlInstance $servers\nReturns the DBMail profiles for \"sql2014\", \"sql2016\" and \"sqlcluster\\sharepoint\"", "Description": "Retrieves Database Mail profiles from one or more SQL Server instances, returning detailed configuration information for each profile including ID, name, description, and status properties. This function is essential for auditing Database Mail configurations across your environment, troubleshooting email notification issues, and documenting mail profile setups for compliance or change management. You can target specific profiles by name or exclude certain profiles from the results, making it useful for both broad configuration reviews and focused troubleshooting scenarios.", "Links": "https://dbatools.io/Get-DbaDbMailProfile", "Synopsis": "Retrieves Database Mail profiles and their configuration details from SQL Server instances", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Profile", "Specifies one or more Database Mail profile names to retrieve. Use this when you need to check configuration details for specific profiles rather than reviewing all profiles.\r\nAccepts exact profile names and is case-sensitive to match SQL Server Database Mail profile naming.", "", false, "false", "", "" ], [ "ExcludeProfile", "Specifies one or more Database Mail profile names to exclude from the results. Useful when auditing multiple profiles but want to skip certain ones like test or deprecated profiles.\r\nHelps focus on production profiles during compliance reviews or troubleshooting scenarios.", "", false, "false", "", "" ], [ "InputObject", "Accepts Database Mail server objects from Get-DbaDbMail cmdlet through the pipeline. This allows you to chain commands when working with multiple SQL instances.\r\nEliminates the need to specify SqlInstance when you already have Database Mail objects from a previous command.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Mail", "DbMail", "Email" ], "CommandName": "Get-DbaDbMailServer", "Name": "Get-DbaDbMailServer", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaDbMailServer [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Server] \u003cString[]\u003e] [[-Account] \u003cString[]\u003e] [[-InputObject] \u003cSqlMail[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Mail.MailServer\nReturns one or more Database Mail server objects from configured Database Mail accounts. Each server object represents an SMTP server configuration associated with a Database Mail account.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Account: The name of the Database Mail account that uses this server\r\n- Name: The name or hostname of the SMTP server\r\n- Port: The SMTP port number used for connections (typically 25, 465, or 587)\r\n- EnableSsl: Boolean indicating whether SSL/TLS encryption is enabled for this server\r\n- ServerType: The type of mail server (typically \"SMTP\")\r\n- UserName: The username used to authenticate with the SMTP server, if required\r\n- UseDefaultCredentials: Boolean indicating whether default Windows credentials are used\r\n- NoCredentialChange: Boolean indicating the credential policy for the server\nAll properties from the SMO MailServer object are accessible via Select-Object * if needed.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbMailServer -SqlInstance sql01\\sharepoint\nReturns all DBMail servers on sql01\\sharepoint\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbMailServer -SqlInstance sql01\\sharepoint -Server DbaTeam\nReturns The DBA Team DBMail server from sql01\\sharepoint\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbMailServer -SqlInstance sql01\\sharepoint | Select-Object *\nReturns the DBMail servers on sql01\\sharepoint then return a bunch more columns\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$servers = \"sql2014\",\"sql2016\", \"sqlcluster\\sharepoint\"\nPS C:\\\u003e $servers | Get-DbaDbMail | Get-DbaDbMailServer\nReturns the DBMail servers for \"sql2014\",\"sql2016\" and \"sqlcluster\\sharepoint\"", "Description": "Retrieves detailed SMTP server configuration information from all Database Mail accounts on SQL Server instances. This function pulls the actual mail server settings including port numbers, SSL configuration, authentication methods, and connection details. Useful for auditing email infrastructure, troubleshooting delivery issues, and documenting Database Mail configurations across your environment.", "Links": "https://dbatools.io/Get-DbaDbMailServer", "Synopsis": "Retrieves SMTP server configurations from SQL Server Database Mail accounts", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Server", "Specifies one or more SMTP server names to retrieve from Database Mail accounts. Use this when you need to check configuration for specific mail servers rather than all configured servers.\r\nAccepts exact server names like \u0027smtp.company.com\u0027 or \u0027mail-relay-01\u0027.", "Name", false, "false", "", "" ], [ "Account", "Restricts results to mail servers associated with specific Database Mail account names. Use this when troubleshooting email issues for particular applications or services.\r\nHelpful for isolating server configurations when you have multiple Database Mail accounts with different SMTP settings.", "", false, "false", "", "" ], [ "InputObject", "Accepts Database Mail objects from Get-DbaDbMail via pipeline. Allows you to chain Database Mail operations together.\r\nUse this when you need to process mail server configurations from a filtered set of SQL instances or specific Database Mail setups.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Certificate", "Security" ], "CommandName": "Get-DbaDbMasterKey", "Name": "Get-DbaDbMasterKey", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaDbMasterKey [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-ExcludeDatabase] \u003cString[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.MasterKey\nReturns one MasterKey object per database that contains a master key. If a database does not have a master key, it is skipped (no output for that database).\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: Name of the database containing the master key\r\n- CreateDate: DateTime when the master key was created\r\n- DateLastModified: DateTime when the master key was last modified\r\n- IsEncryptedByServer: Boolean indicating if the master key is encrypted by the server master key\nAll properties from the base SMO MasterKey object are accessible via Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbMasterKey -SqlInstance sql2016\nGets all master database keys\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbMasterKey -SqlInstance Server1 -Database db1\nGets the master key for the db1 database", "Description": "Retrieves database master key objects and their metadata from one or more SQL Server databases. Database master keys are used to encrypt sensitive data through features like Transparent Data Encryption (TDE), column-level encryption, and certificate-based encryption. This function helps DBAs inventory encryption keys across their environment for security audits, compliance reporting, and encryption management. Returns key details including creation date, last modified date, and server encryption status.", "Links": "https://dbatools.io/Get-DbaDbMasterKey", "Synopsis": "Retrieves database master key information from SQL Server databases", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to check for database master keys. Accepts wildcards for pattern matching.\r\nUse this when you need to audit encryption keys for specific databases instead of scanning all databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies databases to skip when checking for master keys. Accepts wildcards for pattern matching.\r\nUse this to exclude system databases or databases you know don\u0027t use encryption features during security audits.", "", false, "false", "", "" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase through the pipeline for master key analysis.\r\nUse this when you need to check master keys for databases that match specific criteria like compatibility level or size.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Memory", "Database" ], "CommandName": "Get-DbaDbMemoryUsage", "Name": "Get-DbaDbMemoryUsage", "Author": "Shawn Melton (@wsmelton), wsmelton.github.io", "Syntax": "Get-DbaDbMemoryUsage [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-IncludeSystemDb] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per page type per database showing buffer pool memory consumption.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: Name of the database consuming the buffer pool pages\r\n- PageType: Type of page in the buffer (e.g., data pages, index pages, etc.)\r\n- Size: Amount of memory consumed by this database and page type (in MB, as DbaSize object)\r\n- PercentUsed: Percentage of total buffer pool consumed by this database and page type (0-100)\nAdditional properties available:\r\n- PageCount: The number of 8KB pages allocated to this database and page type in the buffer pool\nAll properties are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbMemoryUsage -SqlInstance sqlserver2014a\nReturns the buffer pool consumption for all user databases\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbMemoryUsage -SqlInstance sqlserver2014a -IncludeSystemDb\nReturns the buffer pool consumption for all user databases and system databases\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbMemoryUsage -SqlInstance sql1 -IncludeSystemDb -Database tempdb\nReturns the buffer pool consumption for tempdb database only\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbMemoryUsage -SqlInstance sql2 -IncludeSystemDb -Exclude \u0027master\u0027,\u0027model\u0027,\u0027msdb\u0027,\u0027ResourceDb\u0027\nReturns the buffer pool consumption for all user databases and tempdb database", "Description": "Analyzes SQL Server buffer pool memory usage by querying sys.dm_os_buffer_descriptors to show exactly how much memory each database consumes, broken down by page type (data pages, index pages, etc.). This helps DBAs identify memory-hungry databases that may be impacting instance performance and guides decisions about memory allocation, database optimization, or server capacity planning.\n\nThe results include both raw page counts and percentage of total buffer pool consumed, making it easy to spot databases that are taking disproportionate memory resources. Use this when troubleshooting memory pressure, planning database migrations, or optimizing buffer pool utilization across multiple databases.\n\nThis command is based on query provided by Aaron Bertrand.\nReference: https://www.mssqltips.com/sqlservertip/2393/determine-sql-server-memory-use-by-database-and-object/", "Links": "https://dbatools.io/Get-DbaDbMemoryUsage", "Synopsis": "Retrieves detailed buffer pool memory consumption by database and page type for performance analysis.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance..", "", false, "false", "", "" ], [ "Database", "Restricts analysis to specific databases by name. Accepts multiple database names or wildcard patterns.\r\nUse this when investigating memory usage for particular databases rather than analyzing the entire instance.", "", false, "true (ByPropertyName)", "", "" ], [ "ExcludeDatabase", "Excludes specific databases from the memory analysis by name. Accepts multiple database names.\r\nUseful for filtering out known databases that aren\u0027t relevant to your current investigation or capacity planning.", "", false, "false", "", "" ], [ "IncludeSystemDb", "Includes system databases (master, model, msdb, tempdb, ResourceDb) in the memory consumption analysis.\r\nUse this when troubleshooting overall instance memory pressure or when tempdb memory usage is a concern.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Mirroring", "Mirror", "HA" ], "CommandName": "Get-DbaDbMirror", "Name": "Get-DbaDbMirror", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaDbMirror [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Database\nReturns one Database object for each mirrored database found on the instance. For databases with witness servers, the witness information is added as additional properties.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Name: Database name\r\n- MirroringSafetyLevel: Safety level of the mirroring partnership (OFF, FULL, HIGH)\r\n- MirroringStatus: Current mirroring status (CONNECTED, DISCONNECTED, SUSPENDED, PENDING_FAILOVER)\r\n- MirroringPartner: Server name of the mirroring partner\r\n- MirroringPartnerInstance: Instance name of the mirroring partner\r\n- MirroringFailoverLogSequenceNumber: Log sequence number for failover\r\n- MirroringID: Unique identifier for the mirroring partnership\r\n- MirroringRedoQueueMaxSize: Maximum redo queue size in KB\r\n- MirroringRoleSequence: Current role sequence number\r\n- MirroringSafetySequence: Current safety level sequence number\r\n- MirroringTimeout: Mirroring timeout in seconds\r\n- MirroringWitness: Server name of the witness server (if configured)\r\n- MirroringWitnessStatus: Status of the witness server connection (CONNECTED, DISCONNECTED, UNKNOWN, SUSPENDED)\nFor databases with witness servers, MirroringPartner, MirroringSafetyLevel, and MirroringWitnessStatus may be updated with values from the sys.database_mirroring_witnesses system view.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbMirror -SqlInstance localhost\nGets properties of database mirrors and mirror witnesses on localhost\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbMirror -SqlInstance localhost, sql2016\nGets properties of database mirrors and mirror witnesses on localhost and sql2016 SQL Server instances\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbMirror -SqlInstance localhost, sql2016 -Database mymirror\nGets properties of database mirrors and mirror witnesses on localhost and sql2016 SQL Server instances for databases named mymirror", "Description": "This command collects detailed mirroring information from databases configured with SQL Server Database Mirroring, including partner servers, witness servers, safety levels, and synchronization status. It queries both the database properties and the sys.database_mirroring_witnesses system view to provide complete mirroring topology details. Use this when you need to audit your mirroring setup, troubleshoot mirroring issues, or verify mirroring configuration across multiple instances without manually checking each database\u0027s mirroring properties in SSMS.", "Links": "https://dbatools.io/Get-DbaDbMirror", "Synopsis": "Retrieves database mirroring configuration and status for mirrored databases and their witness servers", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function\r\nto be executed against multiple SQL Server instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to check for mirroring configuration. Accepts multiple database names and supports wildcards.\r\nUse this when you want to examine mirroring status for specific databases instead of checking all databases on the instance.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Mirroring", "Mirror", "HA" ], "CommandName": "Get-DbaDbMirrorMonitor", "Name": "Get-DbaDbMirrorMonitor", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaDbMirrorMonitor [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-Update] [[-LimitResults] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per monitoring record retrieved from the database mirroring monitor table. Multiple records may be returned depending on the -LimitResults parameter value.\nProperties:\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- DatabaseName: Name of the mirrored database\r\n- Role: The role of the server instance - Principal or Mirror\r\n- MirroringState: Current mirroring state (Synchronizing, Synchronized, Suspended, Disconnected, etc.)\r\n- WitnessStatus: Status of the witness server (Connected, Disconnected, Quorum Lost, etc.)\r\n- LogGenerationRate: Rate at which transaction log is being generated on the principal (KB/sec)\r\n- UnsentLog: Amount of log not yet sent to the mirror (KB)\r\n- SendRate: Rate at which log is being sent to the mirror (KB/sec)\r\n- UnrestoredLog: Amount of log not yet restored on the mirror (KB)\r\n- RecoveryRate: Rate at which log is being restored on the mirror (KB/sec)\r\n- TransactionDelay: Delay caused by database mirroring for committed transactions (milliseconds)\r\n- TransactionsPerSecond: Number of transactions per second being processed\r\n- AverageDelay: Average transaction delay (milliseconds)\r\n- TimeRecorded: DateTime when this monitoring record was recorded\r\n- TimeBehind: Amount the mirror lags behind the principal (milliseconds)\r\n- LocalTime: Local time on the server when the record was generated", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbMirrorMonitor -SqlInstance sql2008, sql2012\nReturns last two hours\u0027 worth of status rows for a monitored database from the status table on sql2008 and sql2012.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbMirrorMonitor -SqlInstance sql2005 -LimitResults LastDay -Update\nUpdates monitor stats then returns the last 24 hours worth of status rows for a monitored database from the status table on sql2008 and sql2012.", "Description": "Retrieves detailed database mirroring performance statistics from the msdb monitoring tables, helping you track mirroring health and identify performance bottlenecks. This function executes sp_dbmmonitorresults to pull metrics like log generation rates, send rates, transaction delays, and recovery progress from both principal and mirror databases.\n\nUse this when troubleshooting mirroring performance issues, monitoring replication lag, or generating compliance reports for high availability configurations. You can optionally refresh the monitoring data before retrieval and filter results by time periods or row counts to focus on specific timeframes.\n\nThe function returns comprehensive metrics including unsent log size, recovery rates, average delays, and witness status - all the key indicators DBAs need to assess mirroring health without manually querying system tables.", "Links": "https://dbatools.io/Get-DbaDbMirrorMonitor", "Synopsis": "Retrieves database mirroring performance metrics and monitoring history from SQL Server instances", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which mirrored databases to monitor. Only databases configured for mirroring will return results.\r\nUse this to focus monitoring on specific databases instead of checking all mirrored databases on the instance.", "", false, "false", "", "" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase pipeline input.\r\nUse this when you want to filter databases first before checking their mirroring status.", "", false, "true (ByValue)", "", "" ], [ "Update", "Forces a refresh of mirroring statistics before retrieving results by calling sp_dbmmonitorupdate.\r\nUse this when you need the most current metrics, though SQL Server automatically limits updates to once every 15 seconds and requires sysadmin privileges.", "", false, "false", "False", "" ], [ "LimitResults", "Controls how much historical monitoring data to retrieve from the msdb.dbo.dbm_monitor_data table.\r\nChoose shorter time periods for recent performance analysis or longer periods for trend analysis. Row-based options return the most recent entries regardless of time.\nOptions include:\r\nLastRow\r\nLastTwoHours\r\nLastFourHours\r\nLastEightHours\r\nLastDay\r\nLastTwoDays\r\nLast100Rows\r\nLast500Rows\r\nLast1000Rows\r\nLast1000000Rows", "", false, "false", "LastTwoHours", "LastRow,LastTwoHours,LastFourHours,LastEightHours,LastDay,LastTwoDays,Last100Rows,Last500Rows,Last1000Rows,Last1000000Rows" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Database", "Trigger" ], "CommandName": "Get-DbaDbObjectTrigger", "Name": "Get-DbaDbObjectTrigger", "Author": "Claudio Silva (@claudioessilva), claudioessilva.eu", "Syntax": "Get-DbaDbObjectTrigger [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-Type] \u003cString\u003e] [[-InputObject] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Trigger\nReturns one Trigger object for each DML trigger found on the specified tables and views.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Name: The name of the trigger\r\n- Parent: Reference to the parent table or view object that the trigger is attached to\r\n- IsEnabled: Boolean indicating if the trigger is currently enabled\r\n- DateLastModified: DateTime when the trigger was last modified\nAdditional properties available (from SMO Trigger object):\r\n- ID: The unique identifier for the trigger\r\n- AnsiNullsStatus: Boolean indicating if ANSI_NULLS was set when trigger was created\r\n- AssemblyName: Name of the .NET assembly for CLR triggers\r\n- BodyStartIndex: Index position where trigger body starts in the text\r\n- ClassName: The CLR class name for CLR-based triggers\r\n- CreateDate: DateTime when the trigger was created\r\n- DdlTriggerEvents: List of DDL events that trigger this trigger (if database-level)\r\n- ExecutionContext: Execution context setting for the trigger\r\n- ExecutionContextLogin: Login used for execution context\r\n- ImplementationType: Type of trigger implementation (T-SQL or CLR)\r\n- IsDesignMode: Boolean indicating design mode status\r\n- IsEncrypted: Boolean indicating if trigger definition is encrypted\r\n- IsSystemObject: Boolean indicating if this is a system object\r\n- MethodName: Method name for CLR-based triggers\r\n- QuotedIdentifierStatus: Boolean indicating QUOTED_IDENTIFIER setting\r\n- State: Current state of the trigger object\r\n- TextHeader: Header text of the trigger definition\r\n- TextMode: Text mode setting of the trigger\nAll properties from the SMO Trigger object are accessible via Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbObjectTrigger -SqlInstance sql2017\nReturns all database triggers\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2017 -Database supa | Get-DbaDbObjectTrigger\nReturns all triggers for database supa on sql2017\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbObjectTrigger -SqlInstance sql2017 -Database supa\nReturns all triggers for database supa on sql2017", "Description": "Retrieves all DML triggers that are attached to tables and views within specified databases. This function helps DBAs inventory trigger-based business logic, identify potential performance bottlenecks, and document database dependencies. You can filter results by database, object type (tables vs views), or pipe in specific objects from Get-DbaDbTable and Get-DbaDbView. Returns trigger details including enabled status and last modified date for impact analysis and change management.", "Links": "https://dbatools.io/Get-DbaDbObjectTrigger", "Synopsis": "Retrieves triggers attached to tables and views across SQL Server databases.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", false, "false", "", "" ], [ "SqlCredential", "SqlLogin to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance..", "", false, "false", "", "" ], [ "Database", "Specifies which databases to search for table and view triggers. Accepts wildcards for pattern matching.\r\nUse this when you need to audit triggers in specific databases rather than scanning the entire instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies databases to exclude from trigger enumeration. Accepts wildcards for pattern matching.\r\nUseful when you want to skip system databases or databases known to have no custom triggers.", "", false, "false", "", "" ], [ "Type", "Filters triggers by the type of object they are attached to: Table, View, or All (default).\r\nUse \u0027Table\u0027 or \u0027View\u0027 when you need to focus on triggers for specific object types during auditing or troubleshooting.", "", false, "false", "All", "All,Table,View" ], [ "InputObject", "Accepts specific table or view objects from Get-DbaDbTable and Get-DbaDbView via pipeline input.\r\nUse this when you want to check triggers on particular tables or views rather than scanning entire databases.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Orphan", "Database", "User", "Login" ], "CommandName": "Get-DbaDbOrphanUser", "Name": "Get-DbaDbOrphanUser", "Author": "Claudio Silva (@ClaudioESSilva) | Garry Bargsley (@gbargsley) | Simone Bizzotto (@niphlod)", "Syntax": "Get-DbaDbOrphanUser [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per orphaned user found across the specified databases.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- DatabaseName: Name of the database containing the orphaned user\r\n- User: Name of the orphaned user\nAdditional properties available:\r\n- SmoUser: The underlying Microsoft.SqlServer.Management.Smo.User object with all SMO properties", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbOrphanUser -SqlInstance localhost\\sql2016\nFinds all orphan users without matching Logins in all databases present on server \u0027localhost\\sql2016\u0027.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbOrphanUser -SqlInstance localhost\\sql2016 -SqlCredential $cred\nFinds all orphan users without matching Logins in all databases present on server \u0027localhost\\sql2016\u0027. SQL Server authentication will be used in connecting to the server.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbOrphanUser -SqlInstance localhost\\sql2016 -Database db1\nFinds orphan users without matching Logins in the db1 database present on server \u0027localhost\\sql2016\u0027.", "Description": "An orphan user is defined by a user that does not have their matching login. (Login property = \"\").\n\nNote: Users in contained databases (Partial or Full containment type) are not considered orphaned for SQL logins,\nas these users authenticate directly to the database without requiring a server-level login.\nWindows users are still checked for orphaned status regardless of containment type.", "Links": "https://dbatools.io/Get-DbaDbOrphanUser", "Synopsis": "Get orphaned users.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to check for orphaned users. Accepts database names, wildcards, or arrays.\r\nUse this when you need to focus the orphaned user search on specific databases rather than checking all databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies databases to skip when checking for orphaned users. Useful for excluding system databases or databases under maintenance.\r\nCommonly used to exclude tempdb, distribution, or databases where orphaned users are expected and acceptable.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Database", "Page" ], "CommandName": "Get-DbaDbPageInfo", "Name": "Get-DbaDbPageInfo", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaDbPageInfo [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-Schema] \u003cString[]\u003e] [[-Table] \u003cString[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.Data.DataRow\nReturns one object per page allocation record from the sys.dm_db_database_page_allocations dynamic management view. Each row contains detailed page allocation information for tables in the specified \r\ndatabases.\nProperties:\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name\r\n- Database: The name of the database containing the table\r\n- Schema: The schema name containing the table\r\n- Table: The table name\r\n- PageType: Type of the page (e.g., \u0027DATA_PAGE\u0027, \u0027INDEX_PAGE\u0027, \u0027LOB_DATA_PAGE\u0027)\r\n- PageFreePercent: Percentage of free space available on the page (0-100)\r\n- IsAllocated: String value (\u0027True\u0027 or \u0027False\u0027) indicating if the page is allocated\r\n- IsMixedPage: String value (\u0027True\u0027 or \u0027False\u0027) indicating if this is a mixed page allocation", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbPageInfo -SqlInstance sql2017\nReturns page information for all databases on sql2017\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbPageInfo -SqlInstance sql2017, sql2016 -Database testdb\nReturns page information for the testdb on sql2017 and sql2016\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$servers | Get-DbaDatabase -Database testdb | Get-DbaDbPageInfo\nReturns page information for the testdb on all $servers", "Description": "This function queries the sys.dm_db_database_page_allocations dynamic management view to return detailed information about page allocation, including page type, free space percentage, allocation status, and mixed page allocation indicators.\nUse this when troubleshooting storage issues, analyzing space utilization patterns, or investigating page-level performance problems in your databases.\nResults can be filtered by specific databases, schemas, and tables to focus your analysis on problem areas.\nRequires SQL Server 2012 or higher as it depends on the sys.dm_db_database_page_allocations DMV.", "Links": "https://dbatools.io/Get-DbaDbPageInfo", "Synopsis": "Retrieves detailed page allocation information from SQL Server databases for storage analysis and troubleshooting", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to analyze for page allocation information. Accepts wildcards for pattern matching.\r\nUse this when you need to focus on specific databases rather than scanning all databases on the instance.", "", false, "false", "", "" ], [ "Schema", "Limits the analysis to tables within specific schemas only. Multiple schema names can be provided.\r\nHelpful when troubleshooting page issues in specific application schemas or when you want to exclude system schemas from results.", "", false, "false", "", "" ], [ "Table", "Restricts page information retrieval to specific tables only. Can be combined with Schema parameter for precise targeting.\r\nUse this when investigating page allocation problems for known problematic tables or when performing focused storage analysis.", "", false, "false", "", "" ], [ "InputObject", "Accepts database objects piped from Get-DbaDatabase, allowing you to chain commands together.\r\nThis enables scenarios like getting databases from multiple instances and then analyzing their page information in a single pipeline.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Database", "Partition" ], "CommandName": "Get-DbaDbPartitionFunction", "Name": "Get-DbaDbPartitionFunction", "Author": "Klaas Vandenberghe (@PowerDbaKlaas)", "Syntax": "Get-DbaDbPartitionFunction [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-PartitionFunction] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.PartitionFunction\nReturns one PartitionFunction object for each partition function found in the target databases.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: The name of the database containing the partition function\r\n- CreateDate: DateTime when the partition function was created\r\n- Name: Name of the partition function\r\n- NumberOfPartitions: The number of partitions defined by this function\nAdditional properties available (from SMO PartitionFunction object):\r\n- ParameterType: The data type used as the partitioning column data type\r\n- Urn: Uniform Resource Name identifying the object within the SQL Server hierarchy\r\n- Parent: Reference to the parent Database object\nAll properties from the base SMO object are accessible via Select-Object * even though only default properties are displayed without it.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbPartitionFunction -SqlInstance sql2016\nGets all database partition functions.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbPartitionFunction -SqlInstance Server1 -Database db1\nGets the partition functions for the db1 database.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbPartitionFunction -SqlInstance Server1 -ExcludeDatabase db1\nGets the partition functions for all databases except db1.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Get-DbaDbPartitionFunction\nGets the partition functions for the databases on Sql1 and Sql2/sqlexpress.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaDbPartitionFunction -SqlInstance localhost -Database TestDB -PartitionFunction partFun01\nGets the partition function partFun01 for the TestDB on localhost.", "Description": "Retrieves partition function definitions and their metadata from one or more SQL Server databases. Partition functions define how table or index data is distributed across multiple partitions based on the values of a partitioning column. This function returns details like creation date, function name, and number of partitions, making it useful for documenting partitioning schemes, analyzing partition distribution strategies, and auditing partitioned table configurations before maintenance operations.", "Links": "https://dbatools.io/Get-DbaDbPartitionFunction", "Synopsis": "Retrieves partition function definitions and metadata from SQL Server databases.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to search for partition functions. Accepts multiple database names as an array.\r\nUse this when you need to examine partition functions in specific databases rather than scanning all accessible databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies which databases to skip when searching for partition functions. Accepts multiple database names as an array.\r\nUse this to avoid scanning system databases or databases where you know partition functions don\u0027t exist, improving performance on instances with many databases.", "", false, "false", "", "" ], [ "PartitionFunction", "Specifies which partition functions to retrieve by name. Accepts multiple function names as an array and supports wildcards.\r\nUse this when you need details about specific partition functions rather than retrieving all partition functions from the target databases.", "Name", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Database", "Partition" ], "CommandName": "Get-DbaDbPartitionScheme", "Name": "Get-DbaDbPartitionScheme", "Author": "Klaas Vandenberghe (@PowerDbaKlaas)", "Syntax": "Get-DbaDbPartitionScheme [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-PartitionScheme] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.PartitionScheme\nReturns one PartitionScheme object per partition scheme found in the specified databases. When no filters are applied, all accessible databases are scanned and all partition schemes are returned.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: The database containing this partition scheme\r\n- Name: The name of the partition scheme\r\n- PartitionFunction: The name of the partition function used by this scheme\nAdditional properties available (from SMO PartitionScheme object):\r\n- PartitionFunctionName: The partition function name (same as PartitionFunction)\r\n- Urn: The Uniform Resource Name of the partition scheme object\r\n- State: The current state of the SMO object (Existing, Creating, Pending, Dropping, etc.)\r\n- Parent: The database object that contains this partition scheme\nAll properties from the base SMO PartitionScheme object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbPartitionScheme -SqlInstance sql2016\nGets all database partition schemes.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbPartitionScheme -SqlInstance Server1 -Database db1\nGets the partition schemes for the db1 database.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbPartitionScheme -SqlInstance Server1 -ExcludeDatabase db1\nGets the partition schemes for all databases except db1.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Get-DbaDbPartitionScheme\nGets the partition schemes for the databases on Sql1 and Sql2/sqlexpress.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaDbPartitionScheme -SqlInstance localhost -Database TestDB -PartitionScheme partSch01\nGets the partition scheme partSch01 for the TestDB on localhost.", "Description": "Retrieves partition scheme objects from one or more SQL Server databases, providing details about how partitioned tables and indexes are distributed across filegroups. Partition schemes define the physical storage mapping for partitioned tables by specifying which filegroups contain each partition\u0027s data. This function helps DBAs inventory existing partition schemes when planning table partitioning strategies, troubleshooting performance issues with partitioned tables, or preparing for partition maintenance operations.", "Links": "https://dbatools.io/Get-DbaDbPartitionScheme", "Synopsis": "Retrieves partition schemes from SQL Server databases for table partitioning management.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to scan for partition schemes. Accepts multiple database names.\r\nUse this when you need to check partition schemes in specific databases rather than all accessible databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies databases to skip when scanning for partition schemes. Accepts multiple database names.\r\nUse this to exclude system databases or specific databases you don\u0027t want to check, such as development or staging databases during production audits.", "", false, "false", "", "" ], [ "PartitionScheme", "Specifies which partition schemes to retrieve by name. Accepts multiple scheme names for targeted retrieval.\r\nUse this when you need to examine specific partition schemes rather than all schemes in the database, such as when troubleshooting performance issues with particular partitioned tables.", "Name", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": "QueryStore", "CommandName": "Get-DbaDbQueryStoreOption", "Name": "Get-DbaDbQueryStoreOption", "Author": "Enrico van de Laar (@evdlaar) | Klaas Vandenberghe (@PowerDBAKlaas) | Tracy Boggiano (@TracyBoggiano)", "Syntax": "Get-DbaDbQueryStoreOption [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.QueryStoreOptions\nReturns one object per database with Query Store configuration settings. The base object is the QueryStoreOptions SMO object enhanced with additional properties and adjusted based on the SQL Server \r\nversion.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: Name of the database\r\n- ActualState: Current Query Store state (ReadWrite, ReadOnly, or Off)\r\n- DataFlushIntervalInSeconds: Interval in seconds for flushing data to storage\r\n- StatisticsCollectionIntervalInMinutes: Interval in minutes for statistics collection\r\n- MaxStorageSizeInMB: Maximum storage size allocated for Query Store (in megabytes)\r\n- CurrentStorageSizeInMB: Current storage size being used by Query Store (in megabytes)\r\n- QueryCaptureMode: Query capture mode (All, Auto, None, or Custom)\r\n- SizeBasedCleanupMode: Cleanup mode when max storage is exceeded (Off, Auto)\r\n- StaleQueryThresholdInDays: Number of days after which a query is considered stale for cleanup\nAdditional properties for SQL Server 2017 (v14) and later:\r\n- MaxPlansPerQuery: Maximum number of plans tracked per query\r\n- WaitStatsCaptureMode: Wait statistics capture mode (Off, On)\nAdditional properties for SQL Server 2019 (v15) and later:\r\n- CustomCapturePolicyExecutionCount: Custom capture policy execution count threshold\r\n- CustomCapturePolicyTotalCompileCPUTimeMS: Custom capture policy compile CPU time threshold in milliseconds\r\n- CustomCapturePolicyTotalExecutionCPUTimeMS: Custom capture policy execution CPU time threshold in milliseconds\r\n- CustomCapturePolicyStaleThresholdHours: Custom capture policy stale threshold in hours\nAll properties from the base SMO QueryStoreOptions object are accessible via Select-Object *, even though only default properties are displayed in standard output. The number of properties returned \r\nvaries based on the SQL Server version of the target instance.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbQueryStoreOption -SqlInstance ServerA\\sql\nReturns Query Store configuration settings for every database on the ServerA\\sql instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbQueryStoreOption -SqlInstance ServerA\\sql | Where-Object {$_.ActualState -eq \"ReadWrite\"}\nReturns the Query Store configuration for all databases on ServerA\\sql where the Query Store feature is in Read/Write mode.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbQueryStoreOption -SqlInstance localhost | format-table -AutoSize -Wrap\nReturns Query Store configuration settings for every database on the ServerA\\sql instance inside a table format.", "Description": "Returns the complete Query Store configuration for user databases, including capture modes, storage limits, cleanup policies, and retention settings. This function helps DBAs audit Query Store configurations across their environment, identify databases with suboptimal settings, and ensure consistent Query Store policies. Query Store settings directly impact query performance monitoring, plan regression detection, and storage consumption, so regular configuration reviews are essential for maintaining optimal performance insights.", "Links": "https://dbatools.io/Get-DbaDbQueryStoreOption", "Synopsis": "Retrieves Query Store configuration settings from databases across SQL Server instances.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "SqlLogin to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which user databases to retrieve Query Store configuration from. Accepts database names, wildcards, or arrays for multiple databases.\r\nUse this when you need to audit Query Store settings for specific databases rather than scanning your entire instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific databases from Query Store configuration retrieval. System databases (master, tempdb, model) are automatically excluded.\r\nUseful for skipping databases that you know don\u0027t need Query Store monitoring or have restricted access permissions.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Recovery", "RecoveryModel", "Backup" ], "CommandName": "Get-DbaDbRecoveryModel", "Name": "Get-DbaDbRecoveryModel", "Author": "Viorel Ciucu (@viorelciucu), cviorel.com", "Syntax": "Get-DbaDbRecoveryModel [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-RecoveryModel] \u003cString[]\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Database\nReturns one SMO Database object for each database on the specified instance(s), with the following properties displayed:\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Name: Database name\r\n- Status: Current database status (EmergencyMode, Normal, Offline, Recovering, RecoveryPending, Restoring, Standby, Suspect)\r\n- IsAccessible: Boolean indicating if the database is currently accessible\r\n- RecoveryModel: Database recovery model (Full, Simple, or BulkLogged)\r\n- LastFullBackup: DateTime of the most recent full backup\r\n- LastDiffBackup: DateTime of the most recent differential backup\r\n- LastLogBackup: DateTime of the most recent transaction log backup\nNote: The output is filtered by the Select-DefaultView function to show only the properties listed above. All other properties from the underlying SMO Database object remain accessible via \r\nSelect-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbRecoveryModel -SqlInstance sql2014 -RecoveryModel BulkLogged -Verbose\nGets all databases on SQL Server instance sql2014 having RecoveryModel set to BulkLogged.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbRecoveryModel -SqlInstance sql2014 -Database TestDB\nGets recovery model information for TestDB. If TestDB does not exist on the instance nothing is returned.", "Description": "Retrieves recovery model configuration for databases along with their last backup dates, which is essential for backup strategy planning and compliance auditing. DBAs use this to identify databases with inappropriate recovery models for their business requirements, troubleshoot transaction log growth issues, and ensure backup policies align with recovery model settings. The function shows whether databases are accessible and when their last full, differential, and transaction log backups occurred, making it valuable for both routine maintenance and disaster recovery planning.", "Links": "https://dbatools.io/Get-DbaDbRecoveryModel", "Synopsis": "Retrieves database recovery model settings and backup history information from SQL Server instances.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "RecoveryModel", "Filters results to show only databases using the specified recovery model (Simple, Full, or BulkLogged).\r\nUse this to identify databases with incorrect recovery models for your backup strategy or to audit compliance with recovery model policies.\nDetails about the recovery models can be found here:\r\nhttps://docs.microsoft.com/en-us/sql/relational-databases/backup-restore/recovery-models-sql-server", "", false, "false", "", "Simple,Full,BulkLogged" ], [ "Database", "Specifies which databases to retrieve recovery model information for. Accepts database names, wildcards, or arrays.\r\nUse this when you need to check recovery models for specific databases rather than all databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific databases from the recovery model check. Accepts database names, wildcards, or arrays.\r\nUseful for skipping system databases or databases you don\u0027t manage when reviewing recovery model compliance.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "DisasterRecovery", "Backup", "Restore" ], "CommandName": "Get-DbaDbRestoreHistory", "Name": "Get-DbaDbRestoreHistory", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaDbRestoreHistory [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-Since] \u003cDateTime\u003e] [-Force] [-Last] [[-RestoreType] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.Data.DataRow\nReturns one object per restore operation found in MSDB.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: Name of the database that was restored\r\n- Username: Login name of the user who performed the restore\r\n- RestoreType: Type of restore operation (Database, File, Filegroup, Differential, Log, Verifyonly, or Revert)\r\n- Date: Timestamp when the restore operation completed\r\n- From: Comma-separated list of physical device names where the backup source(s) are located\r\n- To: Comma-separated list of physical file paths where the database files were restored\nAdditional properties available (from MSDB backupset/restorehistory tables):\r\n- first_lsn: First log sequence number in the backup\r\n- last_lsn: Last log sequence number in the backup\r\n- checkpoint_lsn: Checkpoint log sequence number\r\n- database_backup_lsn: Log sequence number of database backup\r\n- BackupStartDate: Timestamp when the backup operation started\r\n- BackupFinishDate: Timestamp when the backup operation completed\r\n- StopAt: The point-in-time stop value specified during the restore operation (NULL if not specified)\r\n- LastRestorePoint: The effective point in time the database was restored to (StopAt if specified, otherwise BackupStartDate)\nAll properties from the underlying DataRow object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbRestoreHistory -SqlInstance sql2016\nReturns server name, database, username, restore type, date for all restored databases on sql2016.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbRestoreHistory -SqlInstance sql2016 -Database db1, db2 -Since \u00272016-07-01 10:47:00\u0027\nReturns restore information only for databases db1 and db2 on sql2016 since July 1, 2016 at 10:47 AM.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbRestoreHistory -SqlInstance sql2014, sql2016 -Exclude db1\nReturns restore information for all databases except db1 on sql2014 and sql2016.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Get-DbaDbRestoreHistory -SqlInstance sql2014 -Database AdventureWorks2014, pubs -SqlCredential $cred | Format-Table\nReturns database restore information for AdventureWorks2014 and pubs database on sql2014, connects using SQL Authentication via sqladmin account. Formats the data as a table.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaRegServer -SqlInstance sql2016 | Get-DbaDbRestoreHistory\nReturns database restore information for every database on every server listed in the Central Management Server on sql2016.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaDbRestoreHistory -SqlInstance sql2016 -RestoreType Log\nReturns log restore information for every database on the sql2016 instance.", "Description": "Queries the MSDB database\u0027s restorehistory and backupset tables to retrieve detailed information about all database restore operations performed on a SQL Server instance. This function returns comprehensive restore details including who performed the restore, when it occurred, what type of restore was performed, and the source and destination file paths.\n\nUse this command to track restore activity for compliance auditing, troubleshoot database issues by determining when databases were last restored, or investigate unexpected changes by identifying recent restore operations. The function supports filtering by database name, restore type (Database, File, Filegroup, Differential, Log, Verifyonly, Revert), date ranges, and can return only the most recent restore for each database.\n\nThis eliminates the need to manually query MSDB system tables or write complex SQL joins to gather restore history information across multiple instances.\n\nThanks to https://www.mssqltips.com/SqlInstancetip/1724/when-was-the-last-time-your-sql-server-database-was-restored/ for the query and https://sqlstudies.com/2016/07/27/when-was-this-database-restored/ for the idea.", "Links": "https://dbatools.io/Get-DbaDbRestoreHistory", "Synopsis": "Retrieves database restore history from MSDB for compliance reporting and recovery analysis.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "Specifies the SQL Server instance(s) to operate on. Requires SQL Server 2005 or higher.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Filters restore history to specific database(s). Accepts wildcards for pattern matching.\r\nUse this when investigating restore activity for particular databases rather than reviewing all restore operations on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific database(s) from the restore history results. Accepts wildcards for pattern matching.\r\nUseful when you need to filter out system databases or other databases that aren\u0027t relevant to your investigation.", "", false, "false", "", "" ], [ "Since", "Filters restore history to operations that occurred on or after the specified date and time.\r\nUse this when investigating recent restore activity or limiting results to a specific time period for compliance reporting.", "", false, "false", "", "" ], [ "Force", "This parameter is deprecated and no longer used.\r\nPreviously controlled whether to return all available columns, but this functionality has been removed.", "", false, "false", "False", "" ], [ "Last", "Returns only the most recent restore operation for each database, filtering out all earlier restore history.\r\nUse this when you need to quickly identify when each database was last restored without seeing the full restore timeline.", "", false, "false", "False", "" ], [ "RestoreType", "Filters results to a specific type of restore operation: Database, File, Filegroup, Differential, Log, Verifyonly, or Revert.\r\nUse this when troubleshooting specific restore scenarios, such as finding all log restores during a point-in-time recovery or identifying differential restores for performance analysis.", "", false, "false", "", "Database,File,Filegroup,Differential,Log,Verifyonly,Revert" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Role", "User" ], "CommandName": "Get-DbaDbRole", "Name": "Get-DbaDbRole", "Author": "Ben Miller (@DBAduck)", "Syntax": "Get-DbaDbRole [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-ExcludeDatabase] \u003cString[]\u003e] [[-Role] \u003cString[]\u003e] [[-ExcludeRole] \u003cString[]\u003e] [-ExcludeFixedRole] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Role\nReturns one Role object per database role found. The output is filtered based on the -Role, -ExcludeRole, and -ExcludeFixedRole parameters.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- Database: The name of the database containing the role\r\n- Name: The name of the database role\r\n- IsFixedRole: Boolean indicating if this is a built-in fixed database role (db_owner, db_datareader, etc.) or a custom user-defined role\nAdditional properties available (from SMO Role object):\r\n- Owner: The principal that owns the role\r\n- CreateDate: DateTime when the role was created\r\n- DateLastModified: DateTime when the role was last modified\r\n- ID: The role\u0027s unique object ID within the database\r\n- Urn: The Urn identifier for the role\nAll properties from the base SMO Role object are accessible via Select-Object * even though only default properties are displayed.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbRole -SqlInstance localhost\nReturns all database roles in all databases on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbRole -SqlInstance localhost, sql2016\nReturns all roles of all database(s) on the local and sql2016 SQL Server instances\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$servers = Get-Content C:\\servers.txt\nPS C:\\\u003e $servers | Get-DbaDbRole\nReturns roles of all database(s) for every server in C:\\servers.txt\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbRole -SqlInstance localhost -Database msdb\nReturns roles of the database msdb on localhost.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaDbRole -SqlInstance localhost -Database msdb -ExcludeFixedRole\nReturns all non-fixed roles in the msdb database on localhost.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaDbRole -SqlInstance localhost -Database msdb -Role \u0027db_owner\u0027\nReturns the db_owner role in the msdb database on localhost.", "Description": "Retrieves all database roles (both fixed and custom) from one or more SQL Server databases, returning detailed role information for security audits and compliance reporting. This function examines the roles collection in each accessible database, allowing you to identify custom roles, exclude built-in fixed roles, or focus on specific roles by name. Essential for documenting role structures across environments, troubleshooting permission issues, and ensuring consistent security configurations during migrations or standardization projects.", "Links": "https://dbatools.io/Get-DbaDbRole", "Synopsis": "Retrieves database roles from SQL Server instances for security auditing and permission analysis.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.", "", false, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to examine for role information. Accepts wildcards for pattern matching.\r\nUse this when you need to audit roles in specific databases rather than scanning all databases on the instance.\r\nParticularly useful for focusing on user databases while skipping system databases, or for compliance audits of specific applications.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specified databases from role enumeration. Accepts wildcards for pattern matching.\r\nUse this to skip databases you don\u0027t need to audit, such as development databases during production security reviews.\r\nCommonly used to exclude system databases or databases with known standard configurations.", "", false, "false", "", "" ], [ "Role", "Specifies which database roles to retrieve by name. Accepts wildcards for pattern matching.\r\nUse this when investigating specific roles across databases, such as checking for custom application roles or finding all instances of a particular role name.\r\nParticularly useful for security audits focusing on elevated permissions like \u0027db_owner\u0027 or custom admin roles.", "", false, "false", "", "" ], [ "ExcludeRole", "Excludes specified roles from the results by name. Accepts wildcards for pattern matching.\r\nUse this to filter out roles you\u0027re not interested in, such as excluding standard fixed roles when focusing on custom application roles.\r\nHelpful for reducing noise in reports when you want to see only non-standard or suspicious role configurations.", "", false, "false", "", "" ], [ "ExcludeFixedRole", "Excludes all built-in fixed database roles from the results, showing only custom user-defined roles.\r\nUse this when auditing custom role implementations or when you need to focus on application-specific security configurations.\r\nFixed roles like db_owner, db_datareader, and db_datawriter are filtered out, along with the public role.", "", false, "false", "False", "" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase through the pipeline for role enumeration.\r\nUse this when you need to chain database selection criteria with role analysis, such as filtering databases by size, compatibility level, or other properties first.\r\nAllows for more complex filtering scenarios than the basic Database parameter provides.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Role", "User" ], "CommandName": "Get-DbaDbRoleMember", "Name": "Get-DbaDbRoleMember", "Author": "Klaas Vandenberghe (@PowerDBAKlaas)", "Syntax": "Get-DbaDbRoleMember [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-ExcludeDatabase] \u003cString[]\u003e] [[-Role] \u003cString[]\u003e] [[-ExcludeRole] \u003cString[]\u003e] [-ExcludeFixedRole] [-IncludeSystemUser] [[-InputObject] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per member (user or nested role) found in each database role.\nProperties:\r\n- ComputerName: The name of the computer where the SQL Server instance is running\r\n- InstanceName: The name of the SQL Server instance\r\n- SqlInstance: The full SQL Server instance name in the format ComputerName\\InstanceName\r\n- Database: The database name containing the role\r\n- Role: The name of the database role\r\n- UserName: The name of the user account (populated when the member is a user; $null when the member is a nested role)\r\n- Login: The SQL Server login associated with the user (populated for user members; $null for nested roles)\r\n- MemberRole: The name of the nested role (populated when the member is another role; $null when the member is a user)\r\n- SmoRole: The SMO DatabaseRole object representing the parent role\r\n- SmoUser: The SMO User object (populated for user members; $null for nested role members)\r\n- SmoMemberRole: The SMO DatabaseRole object for nested role members ($null for user members)\nUse Select-Object to filter properties if you only need specific information, or access SMO objects directly for advanced operations.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbRoleMember -SqlInstance localhost\nReturns all members of all database roles on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbRoleMember -SqlInstance localhost, sql2016\nReturns all members of all database roles on the local and sql2016 SQL Server instances\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$servers = Get-Content C:\\servers.txt\nPS C:\\\u003e $servers | Get-DbaDbRoleMember\nReturns all members of all database roles for every server in C:\\servers.txt\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbRoleMember -SqlInstance localhost -Database msdb\nReturns non-system members of all roles in the msdb database on localhost.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaDbRoleMember -SqlInstance localhost -Database msdb -IncludeSystemUser -ExcludeFixedRole\nReturns all members of non-fixed roles in the msdb database on localhost.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaDbRoleMember -SqlInstance localhost -Database msdb -Role \u0027db_owner\u0027\nReturns all members of the db_owner role in the msdb database on localhost.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003e$roles = Get-DbaDbRole -SqlInstance localhost -Database msdb -Role \u0027db_owner\u0027\nPS C:\\\u003e $roles | Get-DbaDbRoleMember\nReturns all members of the db_owner role in the msdb database on localhost.", "Description": "This function enumerates the membership of database roles, showing which users and nested roles belong to each role. Essential for security audits, permission troubleshooting, and compliance reporting, it reveals the complete role hierarchy within your databases. By default, system users are excluded to focus on business-relevant accounts, but you can include them for comprehensive security reviews. The function works across multiple instances and databases simultaneously, making it perfect for enterprise-wide role membership documentation and access reviews.", "Links": "https://dbatools.io/Get-DbaDbRoleMember", "Synopsis": "Retrieves all users and nested roles that are members of database roles across SQL Server instances", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.", "", false, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to analyze for role membership. Accepts wildcards for pattern matching.\r\nUse this to focus on specific databases rather than scanning all databases on the instance. Helpful when you only need role membership data for particular applications or business units.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific databases from role membership analysis. Supports wildcards for pattern matching.\r\nUse this to skip system databases like tempdb or databases under maintenance when performing enterprise-wide role audits.", "", false, "false", "", "" ], [ "Role", "Limits the analysis to specific database roles by name. Accepts wildcards for pattern matching.\r\nUse this when investigating membership of particular roles like \u0027db_owner\u0027, \u0027db_datareader\u0027, or custom application roles during security reviews or troubleshooting.", "", false, "false", "", "" ], [ "ExcludeRole", "Excludes specific database roles from the membership analysis. Supports wildcards for pattern matching.\r\nUse this to filter out roles you\u0027re not interested in, such as excluding \u0027public\u0027 role or application-specific roles during focused security audits.", "", false, "false", "", "" ], [ "ExcludeFixedRole", "Excludes members of SQL Server\u0027s built-in database roles like db_owner, db_datareader, db_datawriter, etc.\r\nUse this when you want to focus only on custom application roles and their memberships, filtering out the standard SQL Server role assignments.", "", false, "false", "False", "" ], [ "IncludeSystemUser", "Includes SQL Server system users like \u0027dbo\u0027, \u0027guest\u0027, \u0027sys\u0027, and \u0027INFORMATION_SCHEMA\u0027 in the results.\r\nUse this for comprehensive security audits or when troubleshooting system-level permission issues. Normally these accounts are excluded to focus on business user accounts.", "", false, "false", "False", "" ], [ "InputObject", "Accepts piped objects from Get-DbaDbRole, Get-DbaDatabase, or SQL Server instances for processing.\r\nUse this to chain commands together, such as first filtering roles with Get-DbaDbRole then analyzing their membership, or to process multiple database objects efficiently.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Database", "Schema" ], "CommandName": "Get-DbaDbSchema", "Name": "Get-DbaDbSchema", "Author": "Adam Lancaster, github.com/lancasteradam", "Syntax": "Get-DbaDbSchema [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-Schema] \u003cString[]\u003e] [[-SchemaOwner] \u003cString[]\u003e] [-IncludeSystemDatabases] [-IncludeSystemSchemas] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Schema\nReturns one Schema object per database schema found, filtered based on the -Schema, -SchemaOwner, and -IncludeSystemSchemas parameters. Returns multiple objects when querying multiple databases.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Name: The name of the schema\r\n- IsSystemObject: Boolean indicating if this is a built-in system schema (dbo, sys, guest, INFORMATION_SCHEMA) or a custom user-defined schema\nAdditional properties available (from SMO Schema object):\r\n- DatabaseName: The name of the database containing the schema\r\n- DatabaseId: The unique identifier (ID) of the database\r\n- Owner: The principal that owns the schema\r\n- CreateDate: DateTime when the schema was created\r\n- DateLastModified: DateTime when the schema was last modified\r\n- ID: The schema\u0027s unique object ID within the database\r\n- Urn: The Urn identifier for the schema\nAll properties from the base SMO Schema object are accessible via Select-Object * even though only default properties are displayed. The schema object can also be used directly with methods like \r\nAlter() and Drop() as shown in the examples.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbSchema -SqlInstance localhost\nGets all non-system database schemas from all user databases on the localhost instance. Note: the dbo schema is a system schema and won\u0027t be included in the output from this example. To include the \r\ndbo schema specify -IncludeSystemSchemas\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbSchema -SqlInstance localhost -Schema dbo -IncludeSystemSchemas\nReturns the dbo schema from the databases on the localhost instance.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbSchema -SqlInstance localhost -IncludeSystemDatabases -IncludeSystemSchemas\nGets all database schemas from all databases on the localhost instance.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbSchema -SqlInstance localhost -Schema TestSchema\nFinds and returns the TestSchema schema from the localhost instance.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaDbSchema -SqlInstance localhost -SchemaOwner DBUser1\nFinds and returns the schemas owned by DBUser1 from the localhost instance.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaDbSchema -SqlInstance localhost -Database TestDB -SchemaOwner DBUser1\nFinds and returns the schemas owned by DBUser1 in the TestDB database from the localhost instance.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003e$schema = Get-DbaDbSchema -SqlInstance localhost -Database TestDB -Schema TestSchema\nPS C:\\\u003e $schema.Owner = DBUser2\r\nPS C:\\\u003e $schema.Alter()\nFinds the TestSchema in the TestDB on the localhost instance and then changes the schema owner to DBUser2\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003e$schema = Get-DbaDbSchema -SqlInstance localhost -Database TestDB -Schema TestSchema\nPS C:\\\u003e $schema.Drop()\nFinds the TestSchema in the TestDB on the localhost instance and then drops it. Note: to drop a schema all objects must be transferred to another schema or dropped.\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003e$db = Get-DbaDatabase -SqlInstance localhost -Database TestDB\nPS C:\\\u003e $schema = $db | Get-DbaDbSchema -Schema TestSchema\nFinds the TestSchema in the TestDB which is passed via pipeline into the Get-DbaDbSchema command.", "Description": "Returns SQL Server Management Object (SMO) schema objects from one or more databases, allowing you to inspect schema ownership, enumerate database organization, and identify schema-level security configurations. This function is essential for database documentation, security auditing when you need to track who owns which schemas, and migration planning where schema ownership and structure must be preserved. You can filter results by specific schema names, schema owners, or databases, and optionally include system schemas like dbo, sys, and INFORMATION_SCHEMA which are excluded by default.", "Links": "https://dbatools.io/Get-DbaDbSchema", "Synopsis": "Retrieves database schema objects from SQL Server instances for inventory, security auditing, and management tasks", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function\r\nto be executed against multiple SQL Server instances.", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to retrieve schemas from. Accepts wildcards for pattern matching.\r\nUse this when you need to focus on specific databases instead of all databases on the instance.", "", false, "false", "", "" ], [ "Schema", "Filters results to include only schemas with the specified names. Accepts multiple schema names.\r\nUse this when you need to check specific schemas like custom application schemas or verify particular schema configurations.", "", false, "false", "", "" ], [ "SchemaOwner", "Filters results to schemas owned by the specified database users or roles. Accepts multiple owner names.\r\nUse this for security audits to identify all schemas owned by specific users, or when troubleshooting schema ownership issues.", "", false, "false", "", "" ], [ "IncludeSystemDatabases", "Includes system databases (master, model, msdb, tempdb) in the schema retrieval.\r\nUse this when you need to audit or document schema configurations across all databases including system databases.", "", false, "false", "False", "" ], [ "IncludeSystemSchemas", "Includes built-in system schemas like dbo, sys, guest, and INFORMATION_SCHEMA in the results.\r\nUse this when you need complete schema inventory including system schemas, or when specifically working with dbo schema objects.", "", false, "false", "False", "" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase via pipeline input for processing.\r\nUse this to chain database operations or when you already have database objects and want to retrieve their schemas efficiently.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "Shows what would happen if the command were to run. No actions are actually performed.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before executing any changing operations within the command.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Data", "Sequence", "Table" ], "CommandName": "Get-DbaDbSequence", "Name": "Get-DbaDbSequence", "Author": "Adam Lancaster, github.com/lancasteradam", "Syntax": "Get-DbaDbSequence [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-Sequence] \u003cString[]\u003e] [[-Schema] \u003cString[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Sequence\nReturns one or more Sequence objects from the specified database(s) and schema(s). Each object represents a SQL Server sequence definition with its configuration properties.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The name of the computer where the SQL Server instance is running\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance format)\r\n- Database: The name of the database containing the sequence\r\n- Schema: The schema where the sequence is created\r\n- Name: The name of the sequence object\r\n- DataType: The data type of values the sequence will generate (e.g., bigint, int, tinyint, smallint)\r\n- StartValue: The initial value the sequence will return on first use (the current starting point)\r\n- IncrementValue: The amount the sequence will increase (or decrease if negative) with each NEXT VALUE FOR call\nAdditional properties available (from SMO Sequence object):\r\n- CurrentValue: The current value that will be returned by the next NEXT VALUE FOR call\r\n- MinValue: The minimum value the sequence can generate\r\n- MaxValue: The maximum value the sequence can generate\r\n- IsCycleEnabled: Boolean indicating whether the sequence will cycle from MaxValue back to MinValue\r\n- CacheSize: The number of sequence values pre-allocated in memory (0 means no cache)\r\n- SequenceCacheType: The cache behavior setting (DefaultCache, NoCache, or CacheWithSize)\r\n- Parent: Reference to the parent Database SMO object\r\n- Urn: The Uniform Resource Name (URN) identifying the sequence in the SMO object hierarchy\r\n- State: The state of the SMO object (Existing, Creating, Altering, Dropping, etc.)\nAll properties from the base SMO Sequence object are accessible even though only default properties are displayed without using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbSequence -SqlInstance sqldev01 -Database TestDB -Sequence TestSequence\nFinds the sequence TestSequence in the TestDB database on the sqldev01 instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sqldev01 -Database TestDB | Get-DbaDbSequence -Sequence TestSequence -Schema TestSchema\nUsing a pipeline this command finds the sequence named TestSchema.TestSequence in the TestDB database on the sqldev01 instance.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbSequence -SqlInstance localhost\nFinds all the sequences on the localhost instance.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbSequence -SqlInstance localhost -Database db\nFinds all the sequences in the db database on the localhost instance.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaDbSequence -SqlInstance localhost -Sequence seq\nFinds all the sequences named seq on the localhost instance.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaDbSequence -SqlInstance localhost -Schema sch\nFinds all the sequences in the sch schema on the localhost instance.", "Description": "Retrieves sequence objects from SQL Server databases, returning detailed information about each sequence including data type, start value, increment value, and schema location. Sequences provide a flexible alternative to IDENTITY columns for generating sequential numeric values, allowing values to be shared across multiple tables and offering more control over numbering behavior. This function helps DBAs inventory sequences across databases, verify sequence configurations, and identify sequences that may need maintenance or optimization.", "Links": "https://dbatools.io/Get-DbaDbSequence", "Synopsis": "Retrieves SQL Server sequence objects and their configuration details from specified databases.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function\r\nto be executed against multiple SQL Server instances.", "", false, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to search for sequence objects. Accepts wildcards and multiple database names.\r\nUse this when you need to limit the search to specific databases instead of scanning all databases on the instance.", "", false, "false", "", "" ], [ "Sequence", "Filters results to sequences with specific names. Accepts multiple sequence names and supports exact name matching.\r\nUse this when you need to find specific sequences across databases rather than retrieving all sequences.", "Name", false, "false", "", "" ], [ "Schema", "Filters results to sequences within specific schemas. Accepts multiple schema names for searching across different schemas.\r\nUse this when you need to examine sequences in particular schemas, such as application-specific schemas or custom organizational structures.", "", false, "false", "", "" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase pipeline input, allowing you to target specific databases already retrieved.\r\nUse this approach when you need to chain commands or work with databases that meet specific criteria from previous filtering operations.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Database", "ServiceBroker", "Queue" ], "CommandName": "Get-DbaDbServiceBrokerQueue", "Name": "Get-DbaDbServiceBrokerQueue", "Author": "Ant Green (@ant_green)", "Syntax": "Get-DbaDbServiceBrokerQueue [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-ExcludeSystemQueue] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.ServiceBrokerQueue\nReturns one ServiceBrokerQueue object per queue found across the specified databases. System queues are included by default but can be excluded using the -ExcludeSystemQueue parameter.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: The name of the database containing the queue\r\n- Schema: The schema containing the queue\r\n- QueueID: The unique object ID of the queue within the database\r\n- CreateDate: DateTime when the queue was created\r\n- DateLastModified: DateTime when the queue was last modified\r\n- Name: The name of the Service Broker queue\r\n- ProcedureName: Name of the stored procedure that activates the queue (if configured)\r\n- ProcedureSchema: Schema containing the activation procedure\nAdditional properties available (from SMO ServiceBrokerQueue object):\r\n- IsSystemObject: Boolean indicating if this is a system queue created by SQL Server\r\n- IsActivationEnabled: Boolean indicating if queue activation is enabled\r\n- MaxReaders: Maximum number of simultaneous queue readers\r\n- State: Queue state (Available, Unavailable, etc.)\r\n- Owner: The principal that owns the queue\r\n- Urn: The Urn identifier for the queue\nAll properties from the base SMO ServiceBrokerQueue object are accessible via Select-Object * even though only default properties are displayed.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbServiceBrokerQueue -SqlInstance sql2016\nGets all database service broker queues\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbServiceBrokerQueue -SqlInstance Server1 -Database db1\nGets the service broker queues for the db1 database\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbServiceBrokerQueue -SqlInstance Server1 -ExcludeDatabase db1\nGets the service broker queues for all databases except db1\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbServiceBrokerQueue -SqlInstance Server1 -ExcludeSystemQueue\nGets the service broker queues for all databases that are not system objects", "Description": "Gets database Sservice broker queue", "Links": "https://dbatools.io/Get-DbaDbServiceBrokerQueue", "Synopsis": "Gets database service broker queues", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances", "", false, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to retrieve Service Broker queues from. Accepts wildcards for pattern matching.\r\nUse this when you need to focus on specific databases instead of scanning all databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies databases to exclude from the Service Broker queue retrieval. Accepts wildcards for pattern matching.\r\nUseful when you want to scan most databases but skip specific ones like test or development databases.", "", false, "false", "", "" ], [ "ExcludeSystemQueue", "Excludes system-created Service Broker queues from the results, showing only user-created queues.\r\nUse this to focus on application-specific queues and filter out SQL Server\u0027s internal messaging queues.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Service", "ServiceBroker" ], "CommandName": "Get-DbaDbServiceBrokerService", "Name": "Get-DbaDbServiceBrokerService", "Author": "Ant Green (@ant_green)", "Syntax": "Get-DbaDbServiceBrokerService [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-ExcludeSystemService] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.ServiceBrokerService\nReturns one ServiceBrokerService object per Service Broker service found across the specified databases. System services are included by default but can be excluded using the -ExcludeSystemService \r\nparameter.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: The name of the database containing the service\r\n- Owner: The principal that owns the Service Broker service\r\n- ServiceID: The unique object ID of the service within the database\r\n- Name: The name of the Service Broker service\r\n- QueueSchema: The schema containing the associated queue\r\n- QueueName: The name of the queue associated with this service\nAdditional properties available (from SMO ServiceBrokerService object):\r\n- IsSystemObject: Boolean indicating if this is a system service created by SQL Server\r\n- CreateDate: DateTime when the service was created\r\n- DateLastModified: DateTime when the service was last modified\r\n- State: Service state (Existing, Creating, Pending, etc.)\r\n- Urn: The Urn identifier for the service\nAll properties from the base SMO ServiceBrokerService object are accessible via Select-Object * even though only default properties are displayed.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbServiceBrokerService -SqlInstance sql2016\nGets all database service broker queues\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbServiceBrokerService -SqlInstance Server1 -Database db1\nGets the service broker queues for the db1 database\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbServiceBrokerService -SqlInstance Server1 -ExcludeDatabase db1\nGets the service broker queues for all databases except db1\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbServiceBrokerService -SqlInstance Server1 -ExcludeSystemService\nGets the service broker queues for all databases that are not system objects", "Description": "Retrieves detailed information about Service Broker services configured in SQL Server databases, including service names, associated queues, schemas, and ownership details. Service Broker services define the endpoints for reliable messaging between applications and databases. This function helps DBAs audit Service Broker implementations, troubleshoot message-based applications, and document messaging configurations for compliance or migration planning.", "Links": "https://dbatools.io/Get-DbaDbServiceBrokerService", "Synopsis": "Retrieves Service Broker services from SQL Server databases for auditing and troubleshooting messaging configurations", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances", "", false, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to query for Service Broker services. Accepts multiple database names.\r\nUse this when you need to limit the search to specific databases instead of scanning all databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific databases from the Service Broker service search. Accepts multiple database names.\r\nUseful when you want to audit most databases but skip known databases without Service Broker configurations.", "", false, "false", "", "" ], [ "ExcludeSystemService", "Excludes system-created Service Broker services from the results, showing only user-defined services.\r\nUse this to focus on custom messaging implementations and avoid clutter from built-in SQL Server services.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": "SharePoint", "CommandName": "Get-DbaDbSharePoint", "Name": "Get-DbaDbSharePoint", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaDbSharePoint [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-ConfigDatabase] \u003cString[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Database\nReturns one SMO Database object for each SharePoint database found in the SharePoint farm. The number of databases returned depends on the size and configuration of the SharePoint farm, typically \r\nincluding content databases, service application databases, and other associated databases.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Name: Database name\r\n- Status: Current database status (EmergencyMode, Normal, Offline, Recovering, RecoveryPending, Restoring, Standby, Suspect)\r\n- IsAccessible: Boolean indicating if the database is currently accessible\r\n- RecoveryModel: Database recovery model (Full, Simple, BulkLogged)\r\n- LogReuseWaitStatus: Status of transaction log reuse (LogSwitch, ChkptBkup, ActiveBkup, ActiveTran, etc.)\r\n- Size: Database size in megabytes (MB)\r\n- Compatibility: Database compatibility level (numeric value representing SQL Server version)\r\n- Collation: Database collation setting\r\n- Owner: Database owner login name\r\n- Encrypted: Boolean indicating if Transparent Data Encryption (TDE) is enabled\r\n- LastFullBackup: DateTime of the most recent full backup\r\n- LastDiffBackup: DateTime of the most recent differential backup\r\n- LastLogBackup: DateTime of the most recent transaction log backup\nAdditional properties available (from SMO Database object):\r\n- IsCdcEnabled: Boolean indicating if Change Data Capture is enabled (SQL Server 2008+)\r\n- And all other standard SMO Database properties (use Select-Object * to see all)\nAll properties from the base SMO Database object are accessible via Select-Object even though only default properties are displayed without using the -Property parameter.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbSharePoint -SqlInstance sqlcluster\nReturns databases that are part of a SharePoint Farm, as found in SharePoint_Config on sqlcluster\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sqlcluster -Database SharePoint_Config_2016 | Get-DbaDbSharePoint\nReturns databases that are part of a SharePoint Farm, as found in SharePoint_Config_2016 on sqlcluster", "Description": "Discovers and returns database objects for all databases that are part of a SharePoint farm by querying the SharePoint Configuration database\u0027s internal tables and stored procedures. This helps DBAs identify which databases on their SQL Server instance are actively used by SharePoint, eliminating guesswork when planning maintenance, migrations, or troubleshooting SharePoint connectivity issues.\n\nThe function queries the SharePoint Configuration database to find registered SharePoint databases using SharePoint\u0027s internal proc_getObjectsByBaseClass stored procedure and Objects table. By default, this command checks SharePoint_Config. To use an alternate configuration database, use the ConfigDatabase parameter.", "Links": "https://dbatools.io/Get-DbaDbSharePoint", "Synopsis": "Identifies all databases belonging to a SharePoint farm by querying the SharePoint Configuration database.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "ConfigDatabase", "Specifies the name of the SharePoint Configuration database to query for farm database information. Defaults to SharePoint_Config.\r\nUse this when your SharePoint farm uses a non-standard configuration database name, such as SharePoint_Config_2016 or when managing multiple SharePoint versions on the same SQL instance.", "", false, "false", "SharePoint_Config", "" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase to directly analyze specific SharePoint Configuration databases.\r\nUse this when you want to target a specific configuration database without connecting to the SQL instance again, or when working with multiple SharePoint farms across different instances.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": "Snapshot", "CommandName": "Get-DbaDbSnapshot", "Name": "Get-DbaDbSnapshot", "Author": "Simone Bizzotto (@niphlod)", "Syntax": "Get-DbaDbSnapshot [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-Snapshot] \u003cObject[]\u003e] [[-ExcludeSnapshot] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Database\nReturns one SMO Database object for each database snapshot on the specified instances. Database snapshots are read-only views of a database at a specific point in time.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Name: The name of the database snapshot\r\n- SnapshotOf: The name of the base database from which this snapshot was created (alias for DatabaseSnapshotBaseName)\r\n- CreateDate: DateTime when the snapshot was created\r\n- DiskUsage: The amount of disk space consumed by the snapshot (formatted as appropriate unit: KB, MB, GB, etc.)\nAdditional properties available (from SMO Database object):\r\n- DatabaseSnapshotBaseName: The name of the source database\r\n- IsDatabaseSnapshot: Boolean indicating if the database is a snapshot\r\n- SnapshotIsolationState: Snapshot isolation setting\r\n- DatabaseGuid: Unique identifier for the database\r\n- Owner: Database owner login name\r\n- Compatibility: Database compatibility level\nAll properties from the base SMO Database object are accessible via Select-Object * even though only default properties are displayed without using the -Property parameter.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbSnapshot -SqlInstance sqlserver2014a\nReturns a custom object displaying Server, Database, DatabaseCreated, SnapshotOf, SizeMB, DatabaseCreated\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbSnapshot -SqlInstance sqlserver2014a -Database HR, Accounting\nReturns information for database snapshots having HR and Accounting as base dbs\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbSnapshot -SqlInstance sqlserver2014a -Snapshot HR_snapshot, Accounting_snapshot\nReturns information for database snapshots HR_snapshot and Accounting_snapshot", "Description": "Collects information about all database snapshots on a SQL Server instance, showing which database each snapshot was created from, when it was created, and how much disk space it\u0027s consuming. This is useful for snapshot management, cleanup activities, and monitoring storage usage of point-in-time database copies. You can filter results by specific base databases or snapshot names to focus on particular snapshots of interest.", "Links": "https://dbatools.io/Get-DbaDbSnapshot", "Synopsis": "Retrieves database snapshots with their source databases, creation times, and disk usage", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Filters results to snapshots created from specific base databases. Use this when you want to see all snapshots created from particular source databases like \u0027HR\u0027 or \u0027Accounting\u0027.\r\nAccepts multiple database names and is useful for focusing on snapshots from databases you\u0027re actively managing.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes snapshots created from specific base databases from the results. Use this to filter out snapshots from databases you don\u0027t want to see, such as system databases or databases managed by other \r\nteams.\r\nHelpful when you want a comprehensive view but need to omit certain source databases from the output.", "", false, "false", "", "" ], [ "Snapshot", "Returns information for specific database snapshots by their snapshot names. Use this when you need details about particular snapshots like \u0027HR_BeforeUpdate_20240101\u0027 or \u0027Production_Backup_Snapshot\u0027.\r\nAccepts multiple snapshot names and is ideal for checking the status or disk usage of known snapshots.", "", false, "false", "", "" ], [ "ExcludeSnapshot", "Excludes specific database snapshots from the results by their snapshot names. Use this to filter out snapshots you don\u0027t want to see in the output, such as automated system snapshots or snapshots \r\nfrom other environments.\r\nHelpful for focusing on production snapshots while excluding development or test snapshots.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Database", "Space" ], "CommandName": "Get-DbaDbSpace", "Name": "Get-DbaDbSpace", "Author": "Michael Fal (@Mike_Fal), mikefal.net", "Syntax": "Get-DbaDbSpace [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-ExcludeDatabase] \u003cString[]\u003e] [-IncludeSystemDBs] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database file (data and log files).\nProperties:\r\n- ComputerName: The name of the computer hosting the SQL Server instance\r\n- InstanceName: The name of the SQL Server instance\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: The name of the database containing the file\r\n- FileName: The logical name of the database file\r\n- FileGroup: The name of the filegroup the file belongs to (null for log files)\r\n- PhysicalName: The full physical file path on disk\r\n- FileType: The type of file (ROWS for data files, LOG for transaction log files)\r\n- UsedSpace: Amount of space currently in use (dbasize object, convertible to Bytes, KB, MB, GB, TB)\r\n- FreeSpace: Amount of free space available within the file (dbasize object)\r\n- FileSize: Total size of the file (dbasize object)\r\n- PercentUsed: Percentage of the file currently in use (0-100 integer)\r\n- AutoGrowth: The autogrowth increment amount (dbasize object)\r\n- AutoGrowType: Type of autogrowth setting (MB for fixed size, pct for percentage, Unknown if error)\r\n- SpaceUntilMaxSize: Amount of space remaining before reaching max file size limit (dbasize object)\r\n- AutoGrowthPossible: Maximum additional space available through autogrowth (dbasize object)\r\n- UnusableSpace: Space that remains after all possible autogrowth operations (dbasize object)\nNote: All size-related properties use the dbasize object which supports conversion to multiple units\r\n(.Bytes, .Kilobytes, .Megabytes, .Gigabytes, .Terabytes properties are available).", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbSpace -SqlInstance localhost\nReturns all user database files and free space information for the localhost.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbSpace -SqlInstance localhost | Where-Object {$_.PercentUsed -gt 80}\nReturns all user database files and free space information for the local host. Filters the output object by any files that have a percent used of greater than 80%.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e\u0027localhost\u0027,\u0027localhost\\namedinstance\u0027 | Get-DbaDbSpace\nReturns all user database files and free space information for the localhost and localhost\\namedinstance SQL Server instances. Processes data via the pipeline.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbSpace -SqlInstance localhost -Database db1, db2 | Where-Object { $_.SpaceUntilMaxSize.Megabyte -lt 1 }\nReturns database files and free space information for the db1 and db2 on localhost where there is only 1MB left until the space is maxed out\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaDbSpace -SqlInstance localhost -Database db1, db2 | Where-Object { $_.SpaceUntilMaxSize.Gigabyte -lt 1 }\nReturns database files and free space information for the db1 and db2 on localhost where there is only 1GB left until the space is maxed out", "Description": "Queries sys.database_files and FILEPROPERTY to return comprehensive space information for data and log files across databases. Shows current usage, available free space, autogrowth configuration, and space remaining until maximum file size limits are reached. Essential for capacity planning, identifying files approaching size limits, and monitoring database storage consumption patterns.\n\nFile free space script borrowed and modified from Glenn Berry\u0027s DMV scripts (http://www.sqlskills.com/blogs/glenn/category/dmv-queries/)", "Links": "https://dbatools.io/Get-DbaDbSpace", "Synopsis": "Retrieves detailed space usage metrics for all database files including used space, free space, and growth settings.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", false, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Limits space analysis to specific databases by name. Accepts multiple values and supports wildcards.\r\nUse this when monitoring space usage for critical databases or investigating specific capacity issues.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific databases from space analysis by name. Accepts multiple values and supports wildcards.\r\nUseful for skipping test databases, staging environments, or databases with known space issues when doing server-wide capacity reviews.", "", false, "false", "", "" ], [ "IncludeSystemDBs", "This parameter is deprecated and will cause the function to stop with an error message.\r\nTo include system databases in space analysis, pipe results from Get-DbaDatabase with the -IncludeSystem parameter instead.", "", false, "false", "False", "" ], [ "InputObject", "Accepts database objects piped from Get-DbaDatabase for space analysis.\r\nThis allows for advanced filtering scenarios, such as analyzing only databases with specific properties like recovery models or creation dates.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": "Database", "CommandName": "Get-DbaDbState", "Name": "Get-DbaDbState", "Author": "Simone Bizzotto (@niphlod)", "Syntax": "Get-DbaDbState [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database queried. Each object contains the database state information for a specific database on the target instance.\nDefault display properties (via Select-DefaultView):\r\n- SqlInstance: The SQL Server instance name (computer\\instance or just computer)\r\n- InstanceName: The SQL Server service name (instance name only)\r\n- ComputerName: The computer name where the SQL Server instance is running\r\n- DatabaseName: The name of the database\r\n- RW: The read/write status (READ_WRITE or READ_ONLY)\r\n- Status: The database availability state (ONLINE, OFFLINE, EMERGENCY, or RESTORING)\r\n- Access: The user connection restriction level (SINGLE_USER, RESTRICTED_USER, or MULTI_USER)\nAdditional properties available:\r\n- Database: The SMO Database object for this database (hidden from default display)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbState -SqlInstance sqlserver2014a\nGets options for all databases of the sqlserver2014a instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbState -SqlInstance sqlserver2014a -Database HR, Accounting\nGets options for both HR and Accounting database of the sqlserver2014a instance\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbState -SqlInstance sqlserver2014a -Exclude HR\nGets options for all databases of the sqlserver2014a instance except HR\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e\u0027sqlserver2014a\u0027, \u0027sqlserver2014b\u0027 | Get-DbaDbState\nGets options for all databases of sqlserver2014a and sqlserver2014b instances", "Description": "Gets three key database state properties from sys.databases that DBAs frequently need to check:\n- \"RW\" options: READ_ONLY or READ_WRITE (whether database accepts modifications)\n- \"Status\" options: ONLINE, OFFLINE, EMERGENCY, RESTORING (database availability state)\n- \"Access\" options: SINGLE_USER, RESTRICTED_USER, MULTI_USER (user connection restrictions)\n\nThis function is useful for quickly auditing database configurations across instances, especially when troubleshooting connectivity issues or preparing for maintenance operations. System databases (master, model, msdb, tempdb, distribution) are excluded by default since their states rarely change.\n\nReturns an object with SqlInstance, DatabaseName, RW, Status, and Access properties for each user database.", "Links": "https://dbatools.io/Get-DbaDbState", "Synopsis": "Retrieves database state information including read/write status, availability, and user access mode", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which user databases to check for state information. Accepts multiple database names as an array.\r\nUse this when you need to audit specific databases rather than checking all databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies which user databases to exclude from the state check. Accepts multiple database names as an array.\r\nUse this when you want to check most databases but skip specific ones, such as databases under maintenance.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Database", "StoredProcedure", "Proc" ], "CommandName": "Get-DbaDbStoredProcedure", "Name": "Get-DbaDbStoredProcedure", "Author": "Klaas Vandenberghe (@PowerDbaKlaas)", "Syntax": "Get-DbaDbStoredProcedure [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-ExcludeSystemSp] [[-Name] \u003cString[]\u003e] [[-Schema] \u003cString[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.StoredProcedure\nReturns one StoredProcedure object per stored procedure found in the specified databases. Each object represents a single stored procedure, including system and user-defined procedures unless \r\nfiltered.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: The database name containing the stored procedure\r\n- Schema: The schema in which the stored procedure is defined\r\n- ObjectId: The unique identifier for the stored procedure object (displayed as ID)\r\n- CreateDate: The date and time when the stored procedure was created\r\n- DateLastModified: The date and time when the stored procedure was last modified\r\n- Name: The name of the stored procedure\r\n- ImplementationType: The implementation type (T-SQL or CLR)\r\n- Startup: Boolean indicating if the procedure is marked as a startup procedure\nAdditional properties available (from SMO StoredProcedure object):\r\n- DatabaseId: The unique identifier of the database containing the procedure\r\n- IsSystemObject: Boolean indicating if this is a system-defined stored procedure\r\n- And all other standard SMO StoredProcedure properties (use Select-Object * to see all)\nWhen -ExcludeSystemSp is specified, system stored procedures are filtered out and only user-defined procedures are returned.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbStoredProcedure -SqlInstance sql2016\nGets all database Stored Procedures\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbStoredProcedure -SqlInstance Server1 -Database db1\nGets the Stored Procedures for the db1 database\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbStoredProcedure -SqlInstance Server1 -ExcludeDatabase db1\nGets the Stored Procedures for all databases except db1\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbStoredProcedure -SqlInstance Server1 -ExcludeSystemSp\nGets the Stored Procedures for all databases that are not system objects\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Get-DbaDbStoredProcedure\nGets the Stored Procedures for the databases on Sql1 and Sql2/sqlexpress\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance Server1 -ExcludeSystem | Get-DbaDbStoredProcedure\nPipe the databases from Get-DbaDatabase into Get-DbaDbStoredProcedure\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eGet-DbaDbStoredProcedure -SqlInstance Server1 -Database db1 -Name schema1.proc1\nGets the Stored Procedure proc1 in the schema1 schema in the db1 database\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eGet-DbaDbStoredProcedure -SqlInstance Server1 -Name db1.schema1.proc1\nGets the Stored Procedure proc1 in the schema1 schema in the db1 database\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003eGet-DbaDbStoredProcedure -SqlInstance Server1 -Database db1 -Name proc1\nGets the Stored Procedure proc1 in the db1 database\n-------------------------- EXAMPLE 10 --------------------------\nPS C:\\\u003eGet-DbaDbStoredProcedure -SqlInstance Server1 -Database db1 -Schema schema1\nGets the Stored Procedures in schema1 for the db1 database", "Description": "Retrieves stored procedures from one or more SQL Server databases, returning detailed information including schema, creation dates, and implementation details. This function helps DBAs inventory stored procedures across instances, analyze database objects for documentation or migration planning, and locate specific procedures by name or schema. You can filter results by database, schema, or procedure name, and exclude system stored procedures to focus on user-defined objects. Supports multi-part naming conventions for precise targeting of specific procedures.", "Links": "https://dbatools.io/Get-DbaDbStoredProcedure", "Synopsis": "Retrieves stored procedures from SQL Server databases with detailed metadata and filtering options", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances", "", false, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to search for stored procedures. Accepts database names and supports wildcards.\r\nUse this when you need to focus on specific databases instead of searching across all databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specified databases from the stored procedure search. Accepts database names and supports wildcards.\r\nUseful when you want results from most databases but need to skip specific ones like development or staging databases.", "", false, "false", "", "" ], [ "ExcludeSystemSp", "Excludes system stored procedures from results, showing only user-defined stored procedures.\r\nUse this when you want to focus on custom business logic and avoid the hundreds of built-in SQL Server system procedures.", "", false, "false", "False", "" ], [ "Name", "Specifies exact stored procedure names to retrieve. Supports two-part names (schema.procedure) and three-part names (database.schema.procedure).\r\nUse this when searching for specific procedures by name rather than browsing all procedures in a database or schema.", "", false, "false", "", "" ], [ "Schema", "Filters results to stored procedures within the specified schema(s). Accepts multiple schema names.\r\nUseful for organizing results by application area or when working with multi-tenant databases that separate objects by schema.", "", false, "false", "", "" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase for pipeline processing.\r\nUse this to chain commands when you need to filter databases first, then retrieve stored procedures from the filtered results.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Database", "Synonym" ], "CommandName": "Get-DbaDbSynonym", "Name": "Get-DbaDbSynonym", "Author": "Mikey Bronowski (@MikeyBronowski), bronowski.it", "Syntax": "Get-DbaDbSynonym [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-ExcludeDatabase] \u003cString[]\u003e] [[-Schema] \u003cString[]\u003e] [[-ExcludeSchema] \u003cString[]\u003e] [[-Synonym] \u003cString[]\u003e] [[-ExcludeSynonym] \u003cString[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Synonym\nReturns one Synonym object per database synonym found. The output includes details about each synonym and its target object mapping.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance hosting the synonym\r\n- InstanceName: The SQL Server instance name where the synonym is located\r\n- SqlInstance: The full SQL Server instance name (ComputerName\\InstanceName)\r\n- Database: The database containing the synonym\r\n- Schema: The schema that contains the synonym\r\n- Name: The name of the synonym object\r\n- BaseServer: The linked server name if the synonym references a remote object, or the server name for local references\r\n- BaseDatabase: The database containing the target object that the synonym references\r\n- BaseSchema: The schema containing the target object that the synonym references\r\n- BaseObject: The name of the target object that the synonym references (table, view, function, etc.)\nAll properties from the base SMO Synonym object are accessible through Select-Object * even though only the default properties are displayed without using Select-Object.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbSynonym -SqlInstance localhost\nReturns all database synonyms in all databases on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbSynonym -SqlInstance localhost, sql2016\nReturns all synonyms of all database(s) on the local and sql2016 SQL Server instances\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$servers = Get-Content C:\\servers.txt\nPS C:\\\u003e $servers | Get-DbaDbSynonym\nReturns synonyms of all database(s) for every server in C:\\servers.txt\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbSynonym -SqlInstance localhost -Database db1\nReturns synonyms of the database db1 on localhost.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaDbSynonym -SqlInstance localhost -Database db1 -Synonym \u0027synonym1\u0027\nReturns the synonym1 synonym in the db1 database on localhost.", "Description": "Returns database synonym objects along with their target object details including base server, database, schema, and object name. Synonyms are database-scoped aliases that point to objects in the same or different databases, even on remote servers. This function helps DBAs document database dependencies, track cross-database references, and analyze synonym usage across their SQL Server environment. The output includes both the synonym definition and its underlying target, making it useful for impact analysis when planning database migrations or refactoring.", "Links": "https://dbatools.io/Get-DbaDbSynonym", "Synopsis": "Retrieves database synonyms and their target object mappings from SQL Server instances", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.", "", false, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which database(s) to search for synonyms. Accepts wildcards for pattern matching.\r\nUse this when you need to focus on specific databases instead of scanning all databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific database(s) from the synonym search. Accepts wildcards for pattern matching.\r\nUseful for skipping system databases, test environments, or databases you know don\u0027t contain relevant synonyms.", "", false, "false", "", "" ], [ "Schema", "Filters synonyms to only those in the specified schema(s). Accepts wildcards for pattern matching.\r\nUse this when you need to focus on synonyms within specific schemas, such as application-specific or departmental schemas.", "", false, "false", "", "" ], [ "ExcludeSchema", "Excludes synonyms from specific schema(s) in the results. Accepts wildcards for pattern matching.\r\nHelpful for filtering out system schemas or schemas that contain synonyms you\u0027re not interested in analyzing.", "", false, "false", "", "" ], [ "Synonym", "Specifies exact synonym name(s) to retrieve. Accepts multiple synonym names as an array.\r\nUse this when you need details about specific synonyms, such as checking where a particular synonym points or verifying its target object.", "", false, "false", "", "" ], [ "ExcludeSynonym", "Excludes specific synonym(s) from the results by name. Accepts multiple synonym names as an array.\r\nUseful when you want to see all synonyms except certain ones you already know about or don\u0027t need to review.", "", false, "false", "", "" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase via pipeline input. Allows you to chain database filtering commands.\r\nUse this to process synonyms only from databases that meet specific criteria, such as specific compatibility levels or last backup dates.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "Shows what would happen if the command were to run. No actions are actually performed.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before executing any changing operations within the command.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Database", "Tables" ], "CommandName": "Get-DbaDbTable", "Name": "Get-DbaDbTable", "Author": "Stephen Bennett, sqlnotesfromtheunderground.wordpress.com", "Syntax": "Get-DbaDbTable [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-ExcludeDatabase] \u003cString[]\u003e] [-IncludeSystemDBs] [[-Table] \u003cString[]\u003e] [[-Schema] \u003cString[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Table\nReturns one Table object per table found in the specified databases. Each object is enhanced with dbatools-specific properties for server connection context.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: The database name containing the table\r\n- Schema: The schema name that contains the table\r\n- Name: The table name\r\n- IndexSpaceUsed: Total space used by indexes for the table (in KB, not available in Azure SQL Database)\r\n- DataSpaceUsed: Space used by data for the table (in KB, not available in Azure SQL Database)\r\n- RowCount: Number of rows in the table\r\n- HasClusteredIndex: Boolean indicating if table has a clustered index\nVersion-specific properties (included in output when available):\r\n- IsPartitioned: Boolean indicating if table is partitioned (SQL Server 2005+)\r\n- ChangeTrackingEnabled: Boolean indicating if change tracking is enabled (SQL Server 2008+)\r\n- IsFileTable: Boolean indicating if table is a FileTable (SQL Server 2012+)\r\n- IsMemoryOptimized: Boolean indicating if table is memory-optimized (SQL Server 2014+)\r\n- IsNode: Boolean indicating if table is a node table for graph database (SQL Server 2017+)\r\n- IsEdge: Boolean indicating if table is an edge table for graph database (SQL Server 2017+)\nAdditional properties available from the SMO Table object:\r\n- FullTextIndex: FullTextIndex object for accessing full-text search configuration (if configured)\r\n- CreateDate: DateTime when the table was created\r\n- DateLastModified: DateTime when the table was last modified\r\n- IsSystemObject: Boolean indicating if this is a system table\r\n- FileStreamPartitionColumn: Name of the column used for FileStream partitioning\r\n- AnsiNullsStatus: Boolean indicating ANSI NULLs setting\r\n- QuotedIdentifierStatus: Boolean indicating QUOTED_IDENTIFIER setting\nAll properties from the base SMO Table object are accessible via Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbTable -SqlInstance DEV01 -Database Test1\nReturn all tables in the Test1 database\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbTable -SqlInstance DEV01 -Database MyDB -Table MyTable\nReturn only information on the table MyTable from the database MyDB\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbTable -SqlInstance DEV01 -Database MyDB -Table MyTable -Schema MySchema\nReturn only information on the table MyTable from the database MyDB and only from the schema MySchema\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbTable -SqlInstance DEV01 -Table MyTable\nReturns information on table called MyTable if it exists in any database on the server, under any schema\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaDbTable -SqlInstance DEV01 -Table dbo.[First.Table]\nReturns information on table called First.Table on schema dbo if it exists in any database on the server\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e\u0027localhost\u0027,\u0027localhost\\namedinstance\u0027 | Get-DbaDbTable -Database DBA -Table Commandlog\nReturns information on the CommandLog table in the DBA database on both instances localhost and the named instance localhost\\namedinstance\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eGet-DbaDbTable -SqlInstance DEV01 -Table \"[[DbName]]].[Schema.With.Dots].[`\"[Process]]`\"]\" -Verbose\nReturn table information for instance Dev01 and table Process with special characters in the schema name", "Description": "Returns detailed table information including row counts, space usage (IndexSpaceUsed, DataSpaceUsed), and special table characteristics like memory optimization, partitioning, and FileTable status. Essential for database capacity planning, documentation, and finding tables with specific features across multiple databases. Supports complex three-part naming with special characters and can filter by database, schema, or specific table names.", "Links": "https://dbatools.io/Get-DbaDbTable", "Synopsis": "Retrieves table metadata including space usage, row counts, and table features from SQL Server databases", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input.", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to retrieve table information from. Accepts multiple database names and wildcards.\r\nUse this when you need table data from specific databases instead of scanning all databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific databases from table retrieval. Accepts multiple database names and wildcards.\r\nHelpful when you want most databases but need to skip problematic or irrelevant ones like temp databases.", "", false, "false", "", "" ], [ "IncludeSystemDBs", "Includes system databases (master, model, msdb, tempdb) in the table scan.\r\nBy default system databases are excluded since they rarely contain user tables of interest.", "", false, "false", "False", "" ], [ "Table", "Specifies specific tables to retrieve using one, two, or three-part naming (table, schema.table, or database.schema.table).\r\nUse this when you need information on particular tables instead of all tables in the database.\r\nWrap names containing special characters in square brackets and escape actual ] characters by doubling them.", "Name", false, "false", "", "" ], [ "Schema", "Filters results to tables within specific schemas. Accepts multiple schema names.\r\nUseful for focusing on application schemas while excluding utility or system schemas.", "", false, "false", "", "" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase via pipeline input.\r\nUse this when you have already filtered databases and want to pass them directly for table processing.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Database", "Trigger" ], "CommandName": "Get-DbaDbTrigger", "Name": "Get-DbaDbTrigger", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaDbTrigger [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.DatabaseDdlTrigger\nReturns one DatabaseDdlTrigger object per database trigger found on the specified databases. The function enhances the SMO object with additional dbatools properties via Add-Member.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Name: The name of the database-level DDL trigger\r\n- IsEnabled: Boolean indicating whether the trigger is enabled\r\n- DateLastModified: DateTime when the trigger was last modified\nAdditional properties available (from SMO DatabaseDdlTrigger object):\r\n- CreateDate: DateTime when the trigger was created\r\n- EventSet: The set of DDL events that fire the trigger (CREATE_TABLE, ALTER_TABLE, DROP_TABLE, etc.)\r\n- ExecutionContext: The execution context of the trigger (Caller, Owner, or specific user)\r\n- TextHeader: The header portion of the trigger definition\r\n- TextBody: The body portion of the trigger SQL code\r\n- Text: The complete T-SQL definition of the trigger\r\n- Urn: The uniform resource name (URN) uniquely identifying the trigger\r\n- State: The state of the SMO object (Existing, Creating, Dropping, etc.)\nAll properties from the base SMO DatabaseDdlTrigger object are accessible via Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbTrigger -SqlInstance sql2017\nReturns all database triggers\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2017 -Database supa | Get-DbaDbTrigger\nReturns all triggers for database supa on sql2017\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbTrigger -SqlInstance sql2017 -Database supa\nReturns all triggers for database supa on sql2017", "Description": "Retrieves all database-level DDL triggers from one or more SQL Server instances. Database triggers fire in response to DDL events like CREATE, ALTER, or DROP statements within a specific database, making them useful for change auditing and security monitoring. This function helps DBAs inventory these triggers for compliance reporting, troubleshooting performance issues, or documenting automated database change tracking mechanisms. Returns trigger details including name, enabled status, and last modification date.", "Links": "https://dbatools.io/Get-DbaDbTrigger", "Synopsis": "Retrieves database-level DDL triggers from SQL Server instances for security auditing and change tracking analysis.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", false, "false", "", "" ], [ "SqlCredential", "SqlLogin to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance..", "", false, "false", "", "" ], [ "Database", "Specifies which databases to scan for DDL triggers. Accepts wildcards for pattern matching.\r\nUse this when you need to audit triggers in specific databases rather than checking all databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific databases from the trigger scan. Useful for skipping system databases or databases under maintenance.\r\nCommonly used to exclude tempdb, model, or databases that don\u0027t require trigger auditing.", "", false, "false", "", "" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase via pipeline input for targeted trigger analysis.\r\nUse this when you want to process a pre-filtered set of database objects instead of specifying database names.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Udf", "Database" ], "CommandName": "Get-DbaDbUdf", "Name": "Get-DbaDbUdf", "Author": "Klaas Vandenberghe (@PowerDbaKlaas)", "Syntax": "Get-DbaDbUdf [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-ExcludeSystemUdf] [[-Schema] \u003cString[]\u003e] [[-ExcludeSchema] \u003cString[]\u003e] [[-Name] \u003cString[]\u003e] [[-ExcludeName] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.UserDefinedFunction, Microsoft.SqlServer.Management.Smo.UserDefinedAggregate\nReturns one object per User Defined Function or User Defined Aggregate found in the specified databases. Both SMO object types are combined in a single output stream, with UserDefinedAggregates \r\nalways being user-created (no system aggregates exist in SQL Server).\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: The name of the database containing the function/aggregate\r\n- Schema: The schema that contains the function/aggregate\r\n- CreateDate: DateTime when the function/aggregate was originally created\r\n- DateLastModified: DateTime of the most recent modification to the function/aggregate\r\n- Name: The name of the User Defined Function or User Defined Aggregate\r\n- DataType: The return data type of the function/aggregate (for example, \u0027int\u0027, \u0027varchar\u0027, \u0027table\u0027, etc.)\nAdditional properties available from SMO (UserDefinedFunction):\r\n- IsSystemObject: Boolean indicating if this is a system-created object (True for system functions, False for user-created)\r\n- AssemblyName: Name of the .NET assembly if this is a CLR-based function\r\n- ClassName: Class name within the assembly for CLR-based functions\r\n- ExecutionContext: Whether function executes in caller or owner context\r\n- IsInlineTableValuedFunction: Boolean for inline table-valued functions\r\n- IsSqlTabular: Boolean indicating if this is a SQL table-valued function\r\n- QuotedIdentifierStatus: Boolean indicating quoted identifier setting\r\n- ReturnsNullOnNullInput: Boolean indicating NULL handling behavior\r\n- Text: The T-SQL source code or assembly reference of the function\nNote: UserDefinedAggregate objects do not have the IsSystemObject property. The -ExcludeSystemUdf switch filters out system functions but does not affect aggregates (which are never system objects).", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbUdf -SqlInstance sql2016\nGets all database User Defined Functions and User Defined Aggregates\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbUdf -SqlInstance Server1 -Database db1\nGets the User Defined Functions and User Defined Aggregates for the db1 database\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbUdf -SqlInstance Server1 -ExcludeDatabase db1\nGets the User Defined Functions and User Defined Aggregates for all databases except db1\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbUdf -SqlInstance Server1 -ExcludeSystemUdf\nGets the User Defined Functions and User Defined Aggregates for all databases that are not system objects (there can be 100+ system User Defined Functions in each DB)\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Get-DbaDbUdf\nGets the User Defined Functions and User Defined Aggregates for the databases on Sql1 and Sql2/sqlexpress", "Description": "Retrieves all User Defined Functions (UDFs) and User Defined Aggregates from one or more SQL Server databases, returning detailed metadata including schema, creation dates, and data types. This function helps DBAs inventory custom database logic, analyze code dependencies during migrations, and audit user-created functions for security or performance reviews. You can filter results by database, schema, or function name, and exclude system functions to focus on custom business logic.", "Links": "https://dbatools.io/Get-DbaDbUdf", "Synopsis": "Retrieves User Defined Functions and User Defined Aggregates from SQL Server databases with filtering and metadata", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to retrieve User Defined Functions from. Accepts wildcards for pattern matching.\r\nUse this when you need to audit UDFs in specific databases rather than scanning the entire instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies databases to skip when retrieving User Defined Functions. Useful for excluding system databases or databases under maintenance.\r\nCommonly used to exclude tempdb, model, or large databases that don\u0027t contain custom business logic.", "", false, "false", "", "" ], [ "ExcludeSystemUdf", "Filters out built-in SQL Server system functions from the results, showing only custom user-created functions.\r\nEssential when auditing business logic since system databases can contain 100+ built-in UDFs that obscure custom code.", "", false, "false", "False", "" ], [ "Schema", "Limits results to User Defined Functions within specific schemas. Accepts multiple schema names.\r\nUseful for focusing on functions owned by particular applications or development teams, such as \u0027Sales\u0027 or \u0027Reporting\u0027 schemas.", "", false, "false", "", "" ], [ "ExcludeSchema", "Excludes User Defined Functions from specific schemas when retrieving results.\r\nHelpful for filtering out legacy schemas, test schemas, or third-party application schemas that aren\u0027t relevant to your analysis.", "", false, "false", "", "" ], [ "Name", "Retrieves specific User Defined Functions by name. Accepts multiple function names and supports wildcards.\r\nUse this when searching for particular functions during troubleshooting or when documenting specific business logic components.", "", false, "false", "", "" ], [ "ExcludeName", "Excludes specific User Defined Functions from results by name. Supports wildcards for pattern matching.\r\nUseful for filtering out known test functions, deprecated functions, or utility functions that clutter audit reports.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "User", "Database" ], "CommandName": "Get-DbaDbUser", "Name": "Get-DbaDbUser", "Author": "Klaas Vandenberghe (@PowerDbaKlaas)", "Syntax": "Get-DbaDbUser [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-ExcludeSystemUser] [[-User] \u003cString[]\u003e] [[-Login] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.User\nReturns one User object per database user found. The output is filtered based on the -User, -Login, and -ExcludeSystemUser parameters.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: The name of the database containing the user\r\n- CreateDate: DateTime when the user was created\r\n- DateLastModified: DateTime when the user was last modified\r\n- Name: The name of the database user\r\n- Login: The associated server login name (empty string if user is an orphan)\r\n- LoginType: The type of login (SqlLogin, WindowsUser, WindowsGroup, Certificate, AsymmetricKey, or ExternalUser)\r\n- AuthenticationType: The authentication method (Database or Windows)\r\n- State: The object state (Existing, Creating, Dropping, etc.)\r\n- HasDbAccess: Boolean indicating if the user has database access\r\n- DefaultSchema: The default schema associated with the user\nAdditional properties available (from SMO User object):\r\n- ID: Unique object ID within the database\r\n- IsSystemObject: Boolean indicating if this is a built-in system user (dbo, guest, INFORMATION_SCHEMA, etc.)\r\n- IsDisabled: Boolean indicating if the user is disabled\r\n- Urn: Uniform Resource Name identifier for the user\r\n- Sid: Security identifier for Windows-authenticated users\r\n- MustChangePassword: Boolean indicating if user must change password on next login (SQL logins only)\r\n- PasswordExpirationEnabled: Boolean indicating if password expiration policy is enabled\r\n- PasswordExpired: Boolean indicating if password has expired\nAll properties from the base SMO User object are accessible via Select-Object * even though only default properties are displayed.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbUser -SqlInstance sql2016\nGets all database users\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbUser -SqlInstance Server1 -Database db1\nGets the users for the db1 database\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbUser -SqlInstance Server1 -ExcludeDatabase db1\nGets the users for all databases except db1\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbUser -SqlInstance Server1 -ExcludeSystemUser\nGets the users for all databases that are not system objects, like \u0027dbo\u0027, \u0027guest\u0027 or \u0027INFORMATION_SCHEMA\u0027\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Get-DbaDbUser\nGets the users for the databases on Sql1 and Sql2/sqlexpress\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaDbUser -SqlInstance Server1 -Database db1 -User user1, user2\nGets the users \u0027user1\u0027 and \u0027user2\u0027 from the db1 database\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eGet-DbaDbUser -SqlInstance Server1 -Login login1, login2\nGets the users associated with the logins \u0027login1\u0027 and \u0027login2\u0027", "Description": "Retrieves all database user accounts from one or more databases, showing their associated server logins, authentication types, and access states. This function is essential for security audits, user access reviews, and compliance reporting where you need to see who has database-level access and how their accounts are configured. You can filter results by specific users, logins, databases, or exclude system accounts to focus on custom user accounts that require regular review.", "Links": "https://dbatools.io/Get-DbaDbUser", "Synopsis": "Retrieves database user accounts and their associated login mappings from SQL Server databases", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to query for user accounts. Accepts multiple database names and supports wildcards.\r\nUse this when you need to audit users in specific databases rather than scanning all databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies databases to skip when retrieving user accounts. Useful for excluding system databases or databases you don\u0027t manage.\r\nCommon practice is to exclude tempdb, model, or development databases when focusing on production user access reviews.", "", false, "false", "", "" ], [ "ExcludeSystemUser", "Excludes built-in system users like \u0027dbo\u0027, \u0027guest\u0027, \u0027INFORMATION_SCHEMA\u0027, and other system-created accounts.\r\nUse this switch during security audits to focus only on custom user accounts that require regular access review and management.", "", false, "false", "False", "" ], [ "User", "Filters results to specific database user names. Accepts multiple user names for targeted queries.\r\nUse this when investigating specific user accounts or verifying permissions for particular users during access reviews or troubleshooting.", "", false, "false", "", "" ], [ "Login", "Filters results to database users associated with specific server logins. Shows which databases a login has user accounts in.\r\nEssential for understanding a login\u0027s database-level access across the instance, especially during user access audits or when removing departing employees.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Database", "UserDefinedTableType", "Type" ], "CommandName": "Get-DbaDbUserDefinedTableType", "Name": "Get-DbaDbUserDefinedTableType", "Author": "Ant Green (@ant_green)", "Syntax": "Get-DbaDbUserDefinedTableType [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-Type] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.UserDefinedTableType\nReturns one UserDefinedTableType object per user-defined table type found. System objects are automatically excluded.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The name of the computer hosting the SQL Server instance\r\n- InstanceName: The name of the SQL Server instance\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: The name of the database containing the user-defined table type\r\n- ID: The unique identifier (ID) of the user-defined table type within the database\r\n- Name: The name of the user-defined table type\r\n- Columns: The collection of columns defined in the table type (ColumnCollection object)\r\n- Owner: The owner (schema) of the user-defined table type\r\n- CreateDate: The date and time when the user-defined table type was created\r\n- IsSystemObject: Boolean indicating whether this is a system object (always False for returned results)\r\n- Version: The internal version number of the user-defined table type\nAdditional properties available (from SMO UserDefinedTableType object):\r\n- DefaultSchema: The default schema for the table type\r\n- ExtendedProperties: Extended properties (key/value pairs) for the table type\r\n- Urn: Unique resource name identifying the object in the SQL Server instance\r\n- State: The state of the object (Existing, Creating, Pending, etc.)\nAll properties from the base SMO object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbUserDefinedTableType -SqlInstance sql2016\nGets all database user defined table types in all the databases\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbUserDefinedTableType -SqlInstance Server1 -Database db1\nGets all the user defined table types for the db1 database\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbUserDefinedTableType -SqlInstance Server1 -Database db1 -Type type1\nGets type1 user defined table type from db1 database", "Description": "Retrieves user-defined table types from SQL Server databases, which are custom data types used as table-valued parameters in stored procedures and functions. This command helps DBAs audit these schema-bound objects, document their structure and usage, or identify dependencies before making database changes. Returns detailed information including column definitions, ownership, and creation dates across multiple databases and instances.", "Links": "https://dbatools.io/Get-DbaDbUserDefinedTableType", "Synopsis": "Retrieves user-defined table types from SQL Server databases", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances", "", false, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to retrieve user-defined table types from. Accepts database names and supports wildcards for pattern matching.\r\nUse this when you need to examine table types in specific databases rather than all databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies databases to exclude from the search for user-defined table types. Accepts database names and wildcards.\r\nUse this when you want to scan most databases but skip specific ones like system databases or inactive databases.", "", false, "false", "", "" ], [ "Type", "Filters results to include only specific user-defined table type names. Accepts an array of type names for multiple selections.\r\nUse this when you need to examine particular table types across databases, such as auditing usage of a specific custom type.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "View", "Database" ], "CommandName": "Get-DbaDbView", "Name": "Get-DbaDbView", "Author": "Klaas Vandenberghe (@PowerDbaKlaas)", "Syntax": "Get-DbaDbView [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-ExcludeSystemView] [[-View] \u003cString[]\u003e] [[-Schema] \u003cString[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.View\nReturns one View object per database view found that matches the filter criteria.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: The database name containing the view\r\n- Schema: The schema name where the view is defined\r\n- CreateDate: The datetime when the view was created\r\n- DateLastModified: The datetime when the view was last modified\r\n- Name: The name of the view\nAdditional properties available (from SMO View object):\r\n- IsSystemObject: Boolean indicating if this is a system view\r\n- IsEncrypted: Boolean indicating if the view definition is encrypted\r\n- IsBound: Boolean indicating if the view references only available objects\r\n- Implementation: String indicating the view implementation (Standard or Unknown)\r\n- PropertyCount: Integer count of the number of properties the view has\r\n- TextHeader: String containing the header portion of the view definition\r\n- TextMode: The text mode of the view\nAll properties from the SMO View object are accessible by using Select-Object * or by using the property names directly.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbView -SqlInstance sql2016\nGets all database views\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbView -SqlInstance Server1 -Database db1\nGets the views for the db1 database\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbView -SqlInstance Server1 -ExcludeDatabase db1\nGets the views for all databases except db1\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbView -SqlInstance Server1 -ExcludeSystemView\nGets the views for all databases that are not system objects (there can be 400+ system views in each DB)\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Get-DbaDbView\nGets the views for the databases on Sql1 and Sql2/sqlexpress\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance Server1 -ExcludeSystem | Get-DbaDbView\nPipe the databases from Get-DbaDatabase into Get-DbaDbView\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eGet-DbaDbView -SqlInstance Server1 -Database db1 -View vw1\nGets the view vw1 for the db1 database", "Description": "Retrieves all database views from SQL Server instances along with their schema, creation dates, and modification timestamps. This helps DBAs document database architecture, analyze view dependencies, and audit database objects across multiple servers and databases. The function excludes system views by default when requested, making it useful for focusing on custom business logic views.", "Links": "https://dbatools.io/Get-DbaDbView", "Synopsis": "Retrieves SQL Server database views with metadata for documentation and analysis.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.", "", false, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to search for views. Use this when you need to focus on specific databases instead of scanning all databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies databases to skip when retrieving views. Useful when you want results from most databases but need to exclude specific ones like test or staging databases.", "", false, "false", "", "" ], [ "ExcludeSystemView", "Excludes SQL Server system views from results to focus only on user-created views. Essential when documenting custom application views since each database can contain 400+ system views that clutter \r\noutput.", "", false, "false", "False", "" ], [ "View", "Specifies specific view names to retrieve instead of returning all views. Supports three-part naming (database.schema.view) to target views across different databases and schemas in a single query.", "", false, "false", "", "" ], [ "Schema", "Filters results to views within specific schemas only. Useful for organizing output when databases have views spread across multiple schemas like dbo, reporting, or application-specific schemas.", "", false, "false", "", "" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase through the pipeline. Allows you to filter databases first with Get-DbaDatabase then retrieve views from only those selected databases.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Diagnostic", "VLF", "Database", "LogFile" ], "CommandName": "Get-DbaDbVirtualLogFile", "Name": "Get-DbaDbVirtualLogFile", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaDbVirtualLogFile [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-IncludeSystemDBs] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per virtual log file (VLF) found in each database transaction log.\nProperties:\r\n- ComputerName: The name of the computer hosting the SQL Server instance\r\n- InstanceName: The name of the SQL Server instance\r\n- SqlInstance: The full SQL Server instance name (ComputerName\\InstanceName)\r\n- Database: The name of the database containing the virtual log file\r\n- RecoveryUnitId: The recovery unit identifier for the VLF\r\n- FileId: The transaction log file ID (typically 0 for the primary log file)\r\n- FileSize: The size of the virtual log file in bytes\r\n- StartOffset: The starting offset of this VLF within the transaction log file in bytes\r\n- FSeqNo: The virtual log file sequence number - indicates the order of VLFs in the transaction log\r\n- Status: The status of the VLF (0=unused, 1=active, 2=recoverable)\r\n- Parity: The parity value used for recovery tracking and alternate backup validation\r\n- CreateLsn: The Log Sequence Number (LSN) at which this VLF was created", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDbVirtualLogFile -SqlInstance sqlcluster\nReturns all user database virtual log file details for the sqlcluster instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbVirtualLogFile -SqlInstance sqlserver | Group-Object -Property Database | Where-Object Count -gt 50\nReturns user databases that have 50 or more VLFs.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e\u0027sqlserver\u0027,\u0027sqlcluster\u0027 | Get-DbaDbVirtualLogFile\nReturns all VLF information for the sqlserver and sqlcluster SQL Server instances. Processes data via the pipeline.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbVirtualLogFile -SqlInstance sqlcluster -Database db1, db2\nReturns the VLF counts for the db1 and db2 databases on sqlcluster.", "Description": "This function uses DBCC LOGINFO to return detailed metadata about each virtual log file (VLF) within database transaction logs. The output includes VLF size, file offsets, sequence numbers, status, and parity information that\u0027s essential for analyzing transaction log structure and performance.\n\nHaving a transaction log file with too many virtual log files (VLFs) can hurt database performance. Too many VLFs can cause transaction log backups to slow down and can also slow down database recovery and, in extreme cases, even affect insert/update/delete performance.\n\nCommon use cases include identifying databases with excessive VLF counts (typically over 50-100), analyzing VLF size distribution to spot fragmentation issues, and monitoring VLF status during active transactions. This data helps DBAs make informed decisions about log file growth settings and maintenance schedules.\n\nReferences:\nhttp://www.sqlskills.com/blogs/kimberly/transaction-log-vlfs-too-many-or-too-few/\nhttp://blogs.msdn.com/b/saponsqlserver/archive/2012/02/22/too-many-virtual-log-files-vlfs-can-cause-slow-database-recovery.aspx\n\nIf you\u0027ve got a high number of VLFs, you can use Expand-DbaDbLogFile to reduce the number.", "Links": "https://dbatools.io/Get-DbaDbVirtualLogFile", "Synopsis": "Retrieves detailed virtual log file (VLF) metadata from transaction logs for performance analysis and troubleshooting.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to analyze for VLF information. Accepts wildcards for pattern matching.\r\nUse this when you need to focus on specific databases instead of checking all databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies which databases to skip during VLF analysis. Accepts wildcards for pattern matching.\r\nUse this to exclude problematic databases or those you don\u0027t need to monitor for VLF issues.", "", false, "false", "", "" ], [ "IncludeSystemDBs", "Include system databases (master, model, msdb, tempdb) in the VLF analysis.\r\nBy default, only user databases are checked since system database VLF counts are typically less critical for performance tuning.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Storage", "Data", "Log", "Backup" ], "CommandName": "Get-DbaDefaultPath", "Name": "Get-DbaDefaultPath", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaDefaultPath [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance with the default file paths configured for that server.\nProperties:\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name (ServiceName)\r\n- SqlInstance: The full SQL Server instance name in computer\\instance format (DomainInstanceName)\r\n- Data: The default directory path for new database data files\r\n- Log: The default directory path for new transaction log files\r\n- Backup: The default directory path for database backups\r\n- ErrorLog: The directory path where SQL Server stores error log files", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDefaultPath -SqlInstance sql01\\sharepoint\nReturns the default file paths for sql01\\sharepoint\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$servers = \"sql2014\",\"sql2016\", \"sqlcluster\\sharepoint\"\nPS C:\\\u003e $servers | Get-DbaDefaultPath\nReturns the default file paths for \"sql2014\",\"sql2016\" and \"sqlcluster\\sharepoint\"", "Description": "Retrieves the default directory paths that SQL Server uses for new database files, transaction logs, backups, and error logs. This information is essential for capacity planning, automated database provisioning, and understanding where SQL Server will place files when no explicit path is specified. The function uses multiple fallback methods to determine these paths, including server properties, system queries, and examining existing system databases when standard properties are unavailable.", "Links": "https://dbatools.io/Get-DbaDefaultPath", "Synopsis": "Retrieves default file paths for SQL Server data, log, backup, and error log directories", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. Accepts named instances (server\\instance) and pipeline input for batch processing.\r\nUse this to query multiple SQL Server instances at once to compare their default path configurations across your environment.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\r\nUse this when Windows Authentication isn\u0027t available or when you need to connect using SQL Server Authentication or service accounts.\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Dependency", "Utility" ], "CommandName": "Get-DbaDependency", "Name": "Get-DbaDependency", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaDependency [[-InputObject] \u003cObject\u003e] [-AllowSystemObjects] [-Parents] [-IncludeSelf] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Dataplat.Dbatools.Database.Dependency\nReturns one object per dependent object (or prerequisite if using -Parents switch). Objects are sorted by deployment tier, with tier 1 being the lowest-level dependencies that must be created first.\nProperties:\r\n- ComputerName: The name of the SQL Server computer\r\n- ServiceName: The SQL Server service name\r\n- SqlInstance: The full SQL Server instance name\r\n- Dependent: The name of the dependent database object\r\n- Type: The SMO object type (Table, View, StoredProcedure, UserDefinedFunction, etc.)\r\n- Owner: The schema/owner of the object\r\n- IsSchemaBound: Boolean indicating if the object is schema-bound (relevant for views and functions)\r\n- Parent: The name of the parent object (the object being depended upon or depending on this object)\r\n- ParentType: The SMO type of the parent object\r\n- Tier: Integer indicating the deployment tier (1 = base dependencies, higher numbers = dependent on lower-numbered tiers)\r\n- Object: The SMO object instance for the dependent object (allows access to all SMO properties)\r\n- Urn: The URN (Uniform Resource Name) of the dependent object\r\n- OriginalResource: The original input object being analyzed for dependencies\r\n- Script: The T-SQL creation script for the dependent object, ready for deployment\nWhen -Parents switch is used, Tier values are negative (e.g., -1, -2) to indicate prerequisite dependencies rather than dependent objects. When -IncludeSelf is used, the original input object is \r\nincluded in the results with Tier 0.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$table = (Get-DbaDatabase -SqlInstance sql2012 -Database Northwind).tables | Where-Object Name -eq Customers\nPS C:\\\u003e $table | Get-DbaDependency\nReturns everything that depends on the \"Customers\" table", "Description": "This function discovers SQL Server object dependencies using SMO (SQL Server Management Objects) and returns detailed information including creation scripts and deployment order.\nBy default, it finds all objects that depend on your input object - perfect for impact analysis before making changes or understanding what might break if you modify something.\n\nThe function returns objects in hierarchical tiers, showing you exactly which objects need to be created first when deploying to a new environment.\nEach result includes the T-SQL creation script, so you can generate deployment scripts in the correct dependency order without manually figuring out prerequisites.\n\nUse the \u0027Parents\u0027 switch to reverse the direction and find what your object depends on instead - useful for understanding all the prerequisites needed before creating or moving an object.\nThis is particularly valuable when migrating individual objects between environments or troubleshooting missing dependencies.\n\nFor more details on dependency relationships, see:\nhttps://technet.microsoft.com/en-us/library/ms345449(v=sql.105).aspx", "Links": "https://dbatools.io/Get-DbaDependency", "Synopsis": "Maps SQL Server object dependencies and generates creation scripts in proper deployment order", "Availability": "Windows, Linux, macOS", "Params": [ [ "InputObject", "Specifies the SQL Server object (table, view, stored procedure, function, etc.) to analyze for dependencies.\r\nAccepts any SMO object from Get-DbaDatabase, Get-DbaDbTable, Get-DbaDbStoredProcedure, and similar commands.\r\nUse this when you need to understand what objects will be affected by changes to a specific database object.", "", false, "true (ByValue)", "", "" ], [ "AllowSystemObjects", "Includes system objects like sys tables, system functions, and built-in stored procedures in dependency results.\r\nUse this when you need complete dependency mapping including SQL Server internal objects.\r\nMost DBAs can leave this off since system dependencies rarely impact deployment or migration planning.", "", false, "false", "False", "" ], [ "Parents", "Reverses the dependency direction to show what objects the input depends on rather than what depends on it.\r\nEssential for understanding prerequisites when migrating objects or troubleshooting \"object not found\" errors.\r\nUse this to identify all dependencies that must exist before you can create or restore the target object.", "", false, "false", "False", "" ], [ "IncludeSelf", "Includes the original input object in the results along with its dependencies.\r\nHelpful when generating complete deployment scripts that need to recreate both the object and everything it depends on.\r\nCommonly used when exporting database schemas or preparing objects for cross-environment deployment.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Deprecated", "General" ], "CommandName": "Get-DbaDeprecatedFeature", "Name": "Get-DbaDeprecatedFeature", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaDeprecatedFeature [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per deprecated SQL Server feature that has been used on the instance (with usage count \u003e 0).\nProperties:\r\n- ComputerName: The name of the computer running the SQL Server instance\r\n- InstanceName: The name of the SQL Server instance (from SQL Server\u0027s perspective)\r\n- SqlInstance: The full SQL Server instance name (ComputerName\\InstanceName format)\r\n- DeprecatedFeature: The name of the deprecated SQL Server feature\r\n- UsageCount: Integer count of how many times this deprecated feature has been used", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDeprecatedFeature -SqlInstance sql2008, sqlserver2012\nGet usage information relating to deprecated features on the servers sql2008 and sqlserver2012.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDeprecatedFeature -SqlInstance sql2008\nGet usage information relating to deprecated features on server sql2008.", "Description": "Queries the sys.dm_os_performance_counters system view to identify which deprecated SQL Server features have been used on your instances and how frequently they\u0027ve been accessed. This information is essential for upgrade planning, as deprecated features may be removed in future SQL Server versions and could cause application failures.\n\nThe function returns only features that have been used (usage count greater than zero), helping you prioritize which code needs to be modernized before upgrading SQL Server. Common deprecated features include old JOIN syntax, legacy data types, and obsolete T-SQL functions.\n\nMore information: https://learn.microsoft.com/en-us/sql/relational-databases/performance-monitor/sql-server-deprecated-features-object", "Links": "https://dbatools.io/Get-DbaDeprecatedFeature", "Synopsis": "Identifies deprecated SQL Server features currently in use with their usage counts from performance counters.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Storage", "Disk", "Space", "OS" ], "CommandName": "Get-DbaDiskSpace", "Name": "Get-DbaDiskSpace", "Author": "Chrissy LeMaire (@cl), netnerds.net | Jakob Bindslet", "Syntax": "Get-DbaDiskSpace [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-Unit] \u003cString\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-ExcludeDrive] \u003cString[]\u003e] [-CheckFragmentation] [-Force] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Dataplat.Dbatools.Computer.DiskSpace\nReturns one object per disk volume on the target computer(s). The output includes comprehensive disk space information retrieved from Windows WMI, with capacity and free space available in multiple \r\nunit formats (Bytes, KB, MB, GB, TB, PB).\nDefault display properties (shown without using Select-Object):\r\n- ComputerName: The name of the computer\r\n- Name: The volume name (drive letter or UNC path, e.g., \u0027C:\\\u0027 or \u0027\\\\server\\share\u0027)\r\n- Label: The volume label/name if assigned\r\n- Capacity: Total disk capacity in the specified unit (default GB)\r\n- Free: Free space available in the specified unit (default GB)\r\n- PercentFree: Percentage of disk space that is free\r\n- BlockSize: File system block size in bytes\nAdditional properties available (use Select-Object * to view):\r\n- FileSystem: File system type (NTFS, FAT32, ReFS, etc.)\r\n- Type: Drive type identifier (corresponds to DriveType)\r\n- DriveType: Enumerated drive type (LocalDisk, RemovableDisk, NetworkDrive, etc.)\r\n- IsSqlDisk: Boolean indicating if SQL Server files are detected on this disk\r\n- Server: Server name (same as ComputerName)\nSize information in all units (dynamically calculated):\r\n- SizeInBytes, FreeInBytes: Capacity and free space in bytes\r\n- SizeInKB, FreeInKB: Capacity and free space in kilobytes\r\n- SizeInMB, FreeInMB: Capacity and free space in megabytes\r\n- SizeInGB, FreeInGB: Capacity and free space in gigabytes\r\n- SizeInTB, FreeInTB: Capacity and free space in terabytes\r\n- SizeInPB, FreeInPB: Capacity and free space in petabytes\nBy default, only local disks (DriveType 2) and removable disks (DriveType 3) are returned. Use -Force to include all drive types (network drives, CD/DVD, etc.). Use -ExcludeDrive to filter out \r\nspecific volumes.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDiskSpace -ComputerName srv0042\nGet disk space for the server srv0042.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDiskSpace -ComputerName srv0042 -Unit MB\nGet disk space for the server srv0042 and displays in megabytes (MB).\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDiskSpace -ComputerName srv0042, srv0007 -Unit TB\nGet disk space from two servers and displays in terabytes (TB).\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDiskSpace -ComputerName srv0042 -Force\nGet all disk and volume space information.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaDiskSpace -ComputerName srv0042 -ExcludeDrive \u0027C:\\\u0027\nGet all disk and volume space information.", "Description": "Queries Windows disk volumes on SQL Server systems using WMI to gather critical storage information for database administration. Returns comprehensive disk details including capacity, free space, filesystem type, and optional fragmentation analysis.\n\nEssential for SQL Server capacity planning, this function helps DBAs monitor disk space before growth limits impact database operations. Use it to verify adequate space for backup operations, identify performance bottlenecks from fragmented volumes hosting data or log files, and maintain compliance documentation for storage utilization.\n\nBy default, only local disks and removable disks are shown (DriveType 2 and 3), which covers most SQL Server storage scenarios. Hidden system volumes are excluded unless the Force parameter is used.\n\nRequires Windows administrator access on target SQL Server systems.", "Links": "https://dbatools.io/Get-DbaDiskSpace", "Synopsis": "Retrieves disk space and filesystem details from SQL Server host systems for capacity monitoring and performance analysis.", "Availability": "Windows only", "Params": [ [ "ComputerName", "Specifies the SQL Server host systems to query for disk space information. Accepts multiple computer names for bulk monitoring.\r\nUse this to check storage capacity across your SQL Server environment before database growth or backup operations impact available space.", "", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Credential object used to connect to the computer as a different user.", "", false, "false", "", "" ], [ "Unit", "This parameter has been deprecated and will be removed in 1.0.0.\r\nAll size properties (Bytes, KB, MB, GB, TB, PB) are now available simultaneously in the output object but hidden by default for cleaner display.", "", false, "false", "GB", "Bytes,KB,MB,GB,TB,PB" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "ExcludeDrive", "Specifies drive letters to exclude from the disk space report, using the format \u0027C:\\\u0027 or \u0027D:\\\u0027.\r\nUse this to skip system drives or non-SQL storage when focusing on database file locations, or to exclude network drives that may cause timeouts.", "", false, "false", "", "" ], [ "CheckFragmentation", "Enables filesystem fragmentation analysis for all volumes, which can impact SQL Server I/O performance when database or log files are stored on fragmented drives.\r\nThis significantly increases runtime (seconds to minutes per volume) but provides critical data for troubleshooting slow database operations or planning defragmentation maintenance.", "", false, "false", "False", "" ], [ "Force", "Includes all drive types and hidden volumes in the results, not just local and removable disks (DriveType 2 and 3).\r\nUse this when you need complete storage visibility including network drives, CD/DVD drives, or system volumes that might host SQL Server components like backup locations or tempdb files.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Diagnostic", "Engine", "Corruption" ], "CommandName": "Get-DbaDump", "Name": "Get-DbaDump", "Author": "Garry Bargsley (@gbargsley), blog.garrybargsley.com", "Syntax": "Get-DbaDump [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per memory dump file found on the SQL Server instance. Each object contains information about a single .mdmp file created by SQL Server for crash diagnostics.\nProperties:\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- FileName: The file path and name of the memory dump file (.mdmp)\r\n- CreationTime: DateTime indicating when the memory dump was created\r\n- Size: The size of the memory dump file (formatted as dbasize for easy human-readable display, e.g., \"1.5 GB\")", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDump -SqlInstance sql2016\nShows the detailed information for memory dump(s) located on sql2016 instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDump -SqlInstance sql2016 -SqlCredential sqladmin\nShows the detailed information for memory dump(s) located on sql2016 instance. Logs into the SQL Server using the SQL login \u0027sqladmin\u0027", "Description": "Queries the sys.dm_server_memory_dumps dynamic management view to return details about memory dump files (.mdmp) generated by SQL Server. Memory dumps are created when SQL Server encounters crashes, assertion failures, or other critical errors that require investigation. This function helps DBAs quickly identify when dumps have been generated, their size, and creation time, which is essential for troubleshooting server stability issues and working with Microsoft Support for crash analysis.", "Links": "https://dbatools.io/Get-DbaDump", "Synopsis": "Retrieves SQL Server memory dump file information from sys.dm_server_memory_dumps DMV.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": "Endpoint", "CommandName": "Get-DbaEndpoint", "Name": "Get-DbaEndpoint", "Author": "Garry Bargsley (@gbargsley), blog.garrybargsley.com", "Syntax": "Get-DbaEndpoint [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Endpoint] \u003cString[]\u003e] [[-Type] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Endpoint\nReturns one Endpoint object per endpoint found on the SQL Server instance, with custom properties added for connection details and network information.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name (service name)\r\n- SqlInstance: The fully qualified SQL Server instance name (Computer\\Instance)\r\n- ID: The unique identifier of the endpoint\r\n- Name: The name of the endpoint\r\n- IPAddress: The IP address the endpoint listens on (when TCP is configured; otherwise null)\r\n- Port: The TCP port the endpoint listens on (when TCP is configured; otherwise null)\r\n- EndpointState: The current state of the endpoint (Started or Stopped)\r\n- EndpointType: The type of endpoint (DatabaseMirroring, ServiceBroker, Soap, or TSql)\r\n- Owner: The SQL Server login that owns the endpoint\r\n- IsAdminEndpoint: Boolean indicating if this is an administrative endpoint\r\n- Fqdn: Fully qualified domain name and port in connection string format (TCP://hostname:port) for endpoints with TCP listeners; null for endpoints without TCP configuration\r\n- IsSystemObject: Boolean indicating if this is a system-created endpoint\nAdditional properties available (from SMO Endpoint object):\r\n- CreateDate: The date and time when the endpoint was created\r\n- DateLastModified: The date and time when the endpoint was last modified\r\n- Payload: Protocol-specific configuration details for the endpoint\r\n- Protocol: Protocol configuration details (includes Tcp, NamedPipes, SharedMemory configuration objects)\r\n- ProtocolName: The name of the protocol used\nNote: The IPAddress, Port, and Fqdn properties are custom-added by this function to enhance output. When an endpoint has TCP listeners configured, these properties are populated; otherwise, they are \r\nnull or empty. The Fqdn property is automatically resolved with DNS lookups to provide a fully qualified domain name for connectivity testing.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaEndpoint -SqlInstance localhost\nReturns all endpoints on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaEndpoint -SqlInstance localhost, sql2016\nReturns all endpoints for the local and sql2016 SQL Server instances", "Description": "Retrieves all SQL Server endpoints including DatabaseMirroring, ServiceBroker, Soap, and TSql types with their network configuration details. This function provides essential information for troubleshooting connectivity issues, documenting high availability setups, and performing security audits. It automatically resolves DNS names and constructs connection strings (FQDN format) for endpoints that have TCP listeners, making it easier to validate network accessibility and plan firewall configurations.", "Links": "https://dbatools.io/Get-DbaEndpoint", "Synopsis": "Retrieves SQL Server endpoints with network connectivity details for troubleshooting and documentation.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Endpoint", "Specifies one or more endpoint names to retrieve instead of returning all endpoints. Accepts exact endpoint names and supports multiple values.\r\nUse this when you need to examine specific endpoints like \u0027Mirroring\u0027 or \u0027AlwaysOn_health\u0027 rather than scanning all configured endpoints.", "", false, "false", "", "" ], [ "Type", "Filters endpoints by their functional type. Valid options: DatabaseMirroring, ServiceBroker, Soap, and TSql.\r\nUse this to focus on specific endpoint categories, such as \u0027DatabaseMirroring\u0027 for Always On AG troubleshooting or \u0027ServiceBroker\u0027 for message queuing configurations.", "", false, "false", "", "DatabaseMirroring,ServiceBroker,Soap,TSql" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Logging", "Instance", "ErrorLog" ], "CommandName": "Get-DbaErrorLog", "Name": "Get-DbaErrorLog", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaErrorLog [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-LogNumber] \u003cInt32[]\u003e] [[-Source] \u003cObject[]\u003e] [[-Text] \u003cString\u003e] [[-After] \u003cDateTime\u003e] [[-Before] \u003cDateTime\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.LogFileEntry\nReturns one LogFileEntry object per error log entry found. If multiple log numbers are specified, all entries from all requested log files are returned. Entries are processed in reverse log order \r\n(newest logs first) to prioritize recent activity.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- LogDate: The date and time when the log entry was created (DateTime)\r\n- Source: The process ID or source component that created the entry (e.g., spid123, Backup, Logon)\r\n- Text: The full text content of the log entry message\nAdditional properties available (from SMO LogFileEntry object):\r\n- ProcessInfo: The raw process identifier or source component (same as Source but without aliasing)\nAll properties from the base SMO object are accessible even though only default properties are displayed without using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaErrorLog -SqlInstance sql01\\sharepoint\nReturns every log entry from sql01\\sharepoint SQL Server instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaErrorLog -SqlInstance sql01\\sharepoint -LogNumber 3, 6\nReturns all log entries for log number 3 and 6 on sql01\\sharepoint SQL Server instance.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaErrorLog -SqlInstance sql01\\sharepoint -Source Logon\nReturns every log entry, with a source of Logon, from sql01\\sharepoint SQL Server instance.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaErrorLog -SqlInstance sql01\\sharepoint -LogNumber 3 -Text \"login failed\"\nReturns every log entry for log number 3, with \"login failed\" in the text, from sql01\\sharepoint SQL Server instance.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$servers = \"sql2014\",\"sql2016\", \"sqlcluster\\sharepoint\"\nPS C:\\\u003e $servers | Get-DbaErrorLog -LogNumber 0\nReturns the most recent SQL Server error logs for \"sql2014\",\"sql2016\" and \"sqlcluster\\sharepoint\"\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaErrorLog -SqlInstance sql01\\sharepoint -After \u00272016-11-14 00:00:00\u0027\nReturns every log entry found after the date 14 November 2016 from sql101\\sharepoint SQL Server instance.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eGet-DbaErrorLog -SqlInstance sql01\\sharepoint -Before \u00272016-08-16 00:00:00\u0027\nReturns every log entry found before the date 16 August 2016 from sql101\\sharepoint SQL Server instance.", "Description": "Retrieves entries from SQL Server error logs across all available log files (0-99, where 0 is current and 99 is oldest).\nEssential for troubleshooting SQL Server issues, monitoring login failures, tracking system events, and compliance auditing.\nSupports filtering by log number, source type, text patterns, and date ranges to quickly locate specific errors or events.\nReads from all available error logs by default, so you don\u0027t have to check each log file manually.", "Links": "https://dbatools.io/Get-DbaErrorLog", "Synopsis": "Retrieves SQL Server error log entries for troubleshooting and monitoring", "Availability": "Windows only", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", false, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "LogNumber", "Specifies which error log file to read by index number (0-99), where 0 is the current active log and higher numbers are older archived logs.\r\nUse this to target specific log files when troubleshooting issues from a particular time period or to avoid reading all logs for performance.\r\nSQL Server keeps 6 log files by default but can be configured up to 99 archived logs.", "", false, "false", "", "" ], [ "Source", "Filters log entries by the source component that generated the message, such as \"Logon\", \"Server\", \"Backup\", or \"spid123\".\r\nUse this to focus on specific SQL Server subsystems when troubleshooting authentication issues, backup problems, or tracking activity from particular processes.", "", false, "false", "", "" ], [ "Text", "Searches for log entries containing specific text patterns using wildcard matching (supports * wildcards).\r\nUse this to find specific error messages, user names, database names, or any text string within log entries for targeted troubleshooting.", "", false, "false", "", "" ], [ "After", "Returns only log entries that occurred after the specified date and time.\r\nUse this to focus on recent events or investigate issues that started after a known point in time, such as after a deployment or configuration change.", "", false, "false", "", "" ], [ "Before", "Returns only log entries that occurred before the specified date and time.\r\nUse this to investigate historical issues, exclude recent events from analysis, or focus on problems that existed prior to a specific incident or change.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Instance", "ErrorLog", "Logging" ], "CommandName": "Get-DbaErrorLogConfig", "Name": "Get-DbaErrorLogConfig", "Author": "Shawn Melton (@wsmelton), wsmelton.github.io", "Syntax": "Get-DbaErrorLogConfig [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance with error log configuration details.\nProperties:\r\n- ComputerName: The name of the computer hosting the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- LogCount: The number of error log files retained by SQL Server (integer)\r\n- LogSize: The maximum size of each error log file in bytes (only available on SQL Server 2012+, $null on SQL Server 2008 R2 and earlier). Uses dbasize object for human-readable display\r\n- LogPath: The file system directory path where error log files are stored (string)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaErrorLogConfig -SqlInstance server2017,server2014\nReturns error log configuration for server2017 and server2014", "Description": "Retrieves current error log configuration from SQL Server instances, showing how many log files are retained, where they\u0027re stored, and size limits if configured. This information helps DBAs understand log retention policies and troubleshoot logging issues without connecting to SQL Server Management Studio. Log size information is only available on SQL Server 2012 and later versions.", "Links": "https://dbatools.io/Get-DbaErrorLogConfig", "Synopsis": "Retrieves SQL Server error log configuration settings including file count, size limits, and storage location", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Diagnostic", "Query" ], "CommandName": "Get-DbaEstimatedCompletionTime", "Name": "Get-DbaEstimatedCompletionTime", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaEstimatedCompletionTime [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per long-running operation that SQL Server can provide completion estimates for. Only operations with an estimated_completion_time greater than zero are returned.\nDefault display properties:\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: The database where the operation is running\r\n- Login: The login/user who initiated the operation\r\n- Command: The command being executed (BACKUP, RESTORE, DBCC CHECKDB, ALTER INDEX, etc.)\r\n- PercentComplete: The percentage of completion (0-100)\r\n- StartTime: DateTime when the operation started\r\n- RunningTime: Elapsed time formatted as HH:MM:SS\r\n- EstimatedTimeToGo: Estimated remaining time formatted as HH:MM:SS\r\n- EstimatedCompletionTime: Projected completion DateTime\nAdditional properties available:\r\n- Text: The T-SQL query text (excluded from default view, use Select-Object * to display)\nOnly operations supporting progress tracking show completion estimates. Quick queries and standard SELECT statements won\u0027t appear in results.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaEstimatedCompletionTime -SqlInstance sql2016\nGets estimated completion times for queries performed against the entire server\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaEstimatedCompletionTime -SqlInstance sql2016 | Select-Object *\nGets estimated completion times for queries performed against the entire server PLUS the SQL query text of each command\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaEstimatedCompletionTime -SqlInstance sql2016 | Where-Object { $_.Text -match \u0027somequerytext\u0027 }\nGets results for commands whose queries only match specific text (match is like LIKE but way more powerful)\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaEstimatedCompletionTime -SqlInstance sql2016 -Database Northwind,pubs,Adventureworks2014\nGets estimated completion times for queries performed against the Northwind, pubs, and Adventureworks2014 databases", "Description": "Retrieves real-time progress information for long-running SQL Server maintenance and administrative operations by querying sys.dm_exec_requests. This function helps DBAs monitor the status of time-intensive tasks without having to guess when they\u0027ll complete or manually check SQL Server Management Studio.\n\nShows progress details including percent complete, running time, estimated time remaining, and projected completion time. Only returns operations that SQL Server can provide completion estimates for - quick queries and standard SELECT statements won\u0027t appear in the results.\n\nPercent complete will show for the following commands:\n\nALTER INDEX REORGANIZE\nAUTO_SHRINK option with ALTER DATABASE\nBACKUP DATABASE\nDBCC CHECKDB\nDBCC CHECKFILEGROUP\nDBCC CHECKTABLE\nDBCC INDEXDEFRAG\nDBCC SHRINKDATABASE\nDBCC SHRINKFILE\nRECOVERY\nRESTORE DATABASE\nROLLBACK\nTDE ENCRYPTION\n\nParticularly useful during scheduled maintenance windows, large database restores, or when troubleshooting performance issues where you need visibility into what\u0027s currently running and how much longer it will take.\n\nFor additional information, check out https://blogs.sentryone.com/loriedwards/patience-dm-exec-requests/ and https://docs.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-exec-requests-transact-sql", "Links": "https://dbatools.io/Get-DbaEstimatedCompletionTime", "Synopsis": "Monitors progress and estimated completion times for long-running SQL Server operations", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "SqlLogin to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance..", "", false, "false", "", "" ], [ "Database", "Filters results to show only long-running operations within the specified database(s). Accepts multiple database names or wildcards.\r\nUse this when you need to monitor specific databases during maintenance windows or troubleshoot performance issues in particular databases.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes long-running operations from the specified database(s) when monitoring across the entire instance.\r\nHelpful when you want to monitor all databases except system databases or exclude databases with known maintenance operations.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": "Performance", "CommandName": "Get-DbaExecutionPlan", "Name": "Get-DbaExecutionPlan", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaExecutionPlan [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-SinceCreation] \u003cDateTime\u003e] [[-SinceLastExecution] \u003cDateTime\u003e] [-ExcludeEmptyQueryPlan] [-Force] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject (default)\nReturns one object per execution plan found in the SQL Server plan cache. Each object contains parsed execution plan information with query metadata and cost/performance details.\nDefault display properties:\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- DatabaseName: The database name where the query executes\r\n- ObjectName: The object name (procedure, function, or NULL for ad-hoc queries)\r\n- QueryPosition: Row number ordering statements within a batch\r\n- SqlHandle: Hexadecimal representation of the SQL handle for the query\r\n- PlanHandle: Hexadecimal representation of the plan handle\r\n- CreationTime: DateTime when the execution plan was created\r\n- LastExecutionTime: DateTime when the plan was last executed\r\n- StatementCondition: XML node containing statement conditions\r\n- StatementSimple: XML node for simple statements\r\n- StatementId: Statement identifier within the batch\r\n- StatementCompId: Statement compilation ID\r\n- StatementType: Type of statement (SELECT, INSERT, UPDATE, DELETE, etc.)\r\n- RetrievedFromCache: Boolean indicating if plan was retrieved from cache\r\n- StatementSubTreeCost: Estimated subtree cost (decimal)\r\n- StatementEstRows: Estimated number of rows returned (int/decimal)\r\n- SecurityPolicyApplied: Boolean indicating if Row-Level Security policy was applied\r\n- StatementOptmLevel: Optimization level (int)\r\n- QueryHash: Hashed identifier for the query text\r\n- QueryPlanHash: Hashed identifier for the query plan\r\n- StatementOptmEarlyAbortReason: Reason for early optimization abort if applicable\r\n- CardinalityEstimationModelVersion: Cardinality estimation version used (int)\r\n- ParameterizedText: Parameterized version of the query text\r\n- StatementSetOptions: SET options active during statement compilation\r\n- QueryPlan: XML node containing the execution plan tree structure\r\n- BatchConditionXml: XML node for batch-level conditions\r\n- BatchSimpleXml: XML node for batch-level simple statements\nAdditional properties available (excluded from default view):\r\n- BatchQueryPlanRaw: Complete batch-level query plan as XML object\r\n- SingleStatementPlanRaw: Single statement plan as XML object\r\n- PlanWarnings: Plan warnings and advice if applicable\nSystem.Data.DataTable (when -Force is specified)\nReturns all columns from the Dynamic Management Views (sys.dm_exec_query_stats, sys.dm_exec_query_plan, sys.dm_exec_text_query_plan) without parsing or transformation. Provides raw access to all \r\navailable execution statistics, compilation details, and metadata for advanced analysis.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaExecutionPlan -SqlInstance sqlserver2014a\nGets all execution plans on sqlserver2014a\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaExecutionPlan -SqlInstance sqlserver2014a -Database db1, db2 -SinceLastExecution \u00272016-07-01 10:47:00\u0027\nGets all execution plans for databases db1 and db2 on sqlserver2014a since July 1, 2016 at 10:47 AM.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaExecutionPlan -SqlInstance sqlserver2014a, sql2016 -Exclude db1 | Format-Table\nGets execution plan info for all databases except db1 on sqlserver2014a and sql2016 and makes the output pretty\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaExecutionPlan -SqlInstance sql2014 -Database AdventureWorks2014, pubs -Force\nGets super detailed information for execution plans on only for AdventureWorks2014 and pubs\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$servers = \"sqlserver2014a\",\"sql2016t\"\nPS C:\\\u003e $servers | Get-DbaExecutionPlan -Force\nGets super detailed information for execution plans on sqlserver2014a and sql2016", "Description": "Retrieves execution plans from SQL Server\u0027s plan cache using Dynamic Management Views (sys.dm_exec_query_stats, sys.dm_exec_query_plan, and sys.dm_exec_text_query_plan). This is essential for performance analysis because it shows you what queries are actually running and how SQL Server is executing them, without having to capture plans in real-time.\n\nThe function returns detailed metadata including database name, object name, creation time, last execution time, query and plan handles, plus the actual XML execution plans. You can filter results by database, creation date, or last execution time to focus on specific queries or time periods. Use this when troubleshooting performance issues, identifying resource-intensive queries, or analyzing query plan changes over time.\n\nThe output can be piped directly to Export-DbaExecutionPlan to save plans as .sqlplan files for detailed analysis in SQL Server Management Studio or other tools.\n\nThanks to following for the queries:\nhttps://www.simple-talk.com/sql/t-sql-programming/dmvs-for-query-plan-metadata/\nhttp://www.scarydba.com/2017/02/13/export-plans-cache-sqlplan-file/", "Links": "https://dbatools.io/Get-DbaExecutionPlan", "Synopsis": "Retrieves cached execution plans and metadata from SQL Server\u0027s plan cache", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to include when retrieving execution plans from the plan cache.\r\nUse this to focus performance analysis on specific databases instead of scanning all databases on the instance.\r\nAccepts multiple database names and supports wildcards for pattern matching.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies which databases to exclude when retrieving execution plans from the plan cache.\r\nUseful when you want to analyze most databases but skip system databases like tempdb or specific application databases.\r\nAccepts multiple database names for flexible filtering.", "", false, "false", "", "" ], [ "SinceCreation", "Filters execution plans to only those created on or after the specified date and time.\r\nUse this to focus on recent query plan changes after deployments, index modifications, or statistics updates.\r\nHelps identify new execution plans that may be causing performance issues.", "", false, "false", "", "" ], [ "SinceLastExecution", "Filters execution plans to only those executed on or after the specified date and time.\r\nEssential for identifying recently active queries when troubleshooting current performance problems.\r\nExcludes older cached plans that are no longer being used by applications.", "", false, "false", "", "" ], [ "ExcludeEmptyQueryPlan", "Excludes execution plans that have null or empty XML query plan data.\r\nUse this to focus only on plans with complete execution plan information for detailed performance analysis.\r\nHelps avoid incomplete results when you need the actual query plan XML for troubleshooting.", "", false, "false", "False", "" ], [ "Force", "Returns all available columns from the Dynamic Management Views instead of the standard curated output.\r\nUse this when you need access to additional execution statistics, compilation details, or other raw plan cache data.\r\nProvides comprehensive information for advanced performance analysis and troubleshooting scenarios.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "General", "ExtendedProperty" ], "CommandName": "Get-DbaExtendedProperty", "Name": "Get-DbaExtendedProperty", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaExtendedProperty [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-Name] \u003cString[]\u003e] [[-InputObject] \u003cPSObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.ExtendedProperty\nReturns one extended property object per extended property found on the specified SQL Server objects. When querying by SqlInstance and Database, this includes extended properties at the database \r\nlevel. When piping objects from other dbatools commands, extended properties from those specific objects are returned.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- ParentName: Name of the SQL Server object that owns this extended property\r\n- Type: The type name of the parent object (e.g., Database, Table, StoredProcedure, Column)\r\n- Name: The name of the extended property\r\n- Value: The value or content of the extended property (can be any string data)\nAdditional properties available (from SMO ExtendedProperty object):\r\n- Parent: Reference to the parent SQL Server object\r\n- Urn: The Uniform Resource Name of the extended property\r\n- Properties: Collection of property objects\r\n- State: The current state of the SMO object (Existing, Creating, Pending, etc.)\nThe Server property added by this command contains the connection object for programmatic access to the parent SQL Server instance.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaExtendedProperty -SqlInstance sql2016\nGets all extended properties on all databases\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaExtendedProperty -SqlInstance Server1 -Database db1\nGets the extended properties for the db1 database\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaExtendedProperty -SqlInstance Server1 -Database db1 -Name info1, info2\nGets the info1 and info2 extended properties within the db1 database\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbStoredProcedure -SqlInstance localhost -Database tempdb | Get-DbaExtendedProperty\nGet the extended properties for all stored procedures in the tempdb database\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaDbTable -SqlInstance localhost -Database mydb -Table mytable | Get-DbaExtendedProperty\nGet the extended properties for the mytable table in the mydb database", "Description": "Retrieves extended properties that contain custom metadata, documentation, and business descriptions attached to SQL Server objects. Extended properties are commonly used by DBAs and developers to store object documentation, version information, business rules, and compliance notes directly within the database schema.\n\nThis function discovers what documentation and metadata exists across your database objects, making it invaluable for database documentation audits, compliance reporting, and understanding legacy systems. You can retrieve properties from databases by default, or pipe in any SQL Server object from other dbatools commands to examine its custom metadata.\n\nWorks with all major SQL Server object types including databases, tables, columns, stored procedures, functions, views, indexes, schemas, triggers, and many others. The command handles both direct database queries and piped objects seamlessly, so you can easily incorporate extended property discovery into broader database analysis workflows.\n\nPerfect for discovering undocumented business logic, finding objects with compliance tags, or building comprehensive database documentation reports from existing metadata.", "Links": "https://dbatools.io/Get-DbaExtendedProperty", "Synopsis": "Retrieves custom metadata and documentation stored as extended properties on SQL Server objects", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to search for extended properties. Only applies when connecting directly to SqlInstance.\r\nUse this when you need to examine extended properties from specific databases rather than all accessible databases on the instance.", "", false, "false", "", "" ], [ "Name", "Filters results to extended properties with specific names. Accepts multiple property names.\r\nUse this when you know the exact property names you\u0027re looking for, such as finding all objects tagged with \u0027Description\u0027 or \u0027Version\u0027 properties.", "Property", false, "false", "", "" ], [ "InputObject", "Accepts SQL Server objects piped from other dbatools commands to examine their extended properties.\r\nUse this to discover metadata on specific objects like tables, stored procedures, or views returned from commands like Get-DbaDbTable or Get-DbaDbStoredProcedure.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Instance", "Security" ], "CommandName": "Get-DbaExtendedProtection", "Name": "Get-DbaExtendedProtection", "Author": "Claudio Silva (@claudioessilva), claudioessilva.eu", "Syntax": "Get-DbaExtendedProtection [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per instance containing the current Extended Protection setting and its interpretation.\nProperties:\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- ExtendedProtection: The current Extended Protection setting as a string combining the numeric value (0, 1, or 2) and its text description (Off, Allowed, or Required), formatted as \"numeric - text\" \r\n(e.g., \"1 - Allowed\")\r\n- AcceptedSpns: The accepted service principal names configured for Extended Protection, returned as individual strings", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaExtendedProtection\nGets Extended Protection on the default (MSSQLSERVER) instance on localhost - requires (and checks for) RunAs admin.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaExtendedProtection -SqlInstance sql01\\SQL2008R2SP2\nSet Extended Protection of SQL Engine for the SQL2008R2SP2 on sql01 to \"Off\". Uses Windows Credentials to both connect and modify the registry.\r\nGets Extended Protection for the SQL2008R2SP2 on sql01. Uses Windows Credentials to both login and view the registry.", "Description": "Retrieves the Extended Protection setting for SQL Server instances to help assess authentication security posture. Extended Protection is a Windows authentication enhancement that helps prevent credential relay attacks by validating channel binding and service principal names.\n\nThis function queries the Windows registry directly rather than connecting to SQL Server, so it requires Windows-level access to the target server. The setting corresponds to what you see in SQL Server Configuration Manager under Network Configuration \u003e Protocols properties, but can be checked programmatically across multiple instances for compliance auditing.\n\nReturns the current setting as both a numeric value (0, 1, 2) and descriptive text (Off, Allowed, Required), together with the accepted SPNs configured for service binding validation.", "Links": "https://dbatools.io/Get-DbaExtendedProtection", "Synopsis": "Retrieves Extended Protection authentication settings from SQL Server network configuration.", "Availability": "Windows only", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Specifies alternative Windows credentials for connecting to the target computer to read registry values. This is for Windows computer access, not SQL Server authentication.\r\nRequired when your current Windows account lacks administrative privileges on the target server or when connecting across domains.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Diagnostic", "Process" ], "CommandName": "Get-DbaExternalProcess", "Name": "Get-DbaExternalProcess", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaExternalProcess [-ComputerName] \u003cDbaInstanceParameter[]\u003e [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per external process spawned by SQL Server on each target computer. For servers with no child processes spawned by SQL Server, nothing is returned.\nProperties:\r\n- ComputerName: The name of the computer where the SQL Server process resides\r\n- ProcessId: The operating system process ID of the child process (unsigned integer)\r\n- Name: The executable name of the child process (e.g., cmd.exe, bcp.exe, DTExec.exe)\r\n- HandleCount: The number of open handles held by the child process (unsigned integer)\r\n- WorkingSetSize: Memory currently in use by the child process in bytes (unsigned long)\r\n- VirtualSize: Total virtual address space reserved by the child process in bytes (unsigned long)\r\n- CimObject: The underlying WMI process object providing full access to all Win32_Process properties\r\n- Credential: The credential object used for the WMI connection (this property is typically not useful for analysis)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaExternalProcess -ComputerName SERVER01, SERVER02\nGets OS processes created by SQL Server on SERVER01 and SERVER02", "Description": "Identifies and returns all child processes created by SQL Server, such as those spawned by xp_cmdshell, BCP operations, SSIS packages, or other external utilities.\n\nThis is particularly useful when troubleshooting sessions with External Wait Types, where SQL Server is waiting for an external process to complete. When sessions appear hung with wait types like WAITFOR_RESULTS or EXTERNAL_SCRIPT_NETWORK_IO, this command helps identify the specific external processes that may be causing the delay.\n\nThe function queries WMI to find the SQL Server process (sqlservr.exe) and then locates all processes where SQL Server is the parent process, providing details about memory usage and resource consumption.\n\nhttps://web.archive.org/web/20201027122300/http://vickyharp.com/2013/12/killing-sessions-with-external-wait-types/", "Links": "https://dbatools.io/Get-DbaExternalProcess", "Synopsis": "Retrieves operating system processes spawned by SQL Server instances", "Availability": "Windows only", "Params": [ [ "ComputerName", "Specifies the SQL Server host computer(s) to check for external processes spawned by SQL Server.\r\nUse this when troubleshooting hung sessions or investigating resource usage from processes like xp_cmdshell, BCP, or SSIS operations.\r\nAccepts multiple computer names and SQL Server instance names with automatic computer resolution.", "", true, "true (ByValue)", "", "" ], [ "Credential", "Allows you to login to $ComputerName using alternative credentials.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Feature", "Component", "General" ], "CommandName": "Get-DbaFeature", "Name": "Get-DbaFeature", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaFeature [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server feature component discovered. Multiple objects are returned when multiple SQL Server versions or instances with different installed features are found on the target \r\nserver(s).\nProperties:\r\n- ComputerName: The name of the Windows server where SQL Server is installed\r\n- Product: The SQL Server product name (e.g., \"SQL Server 2019 Enterprise Edition\")\r\n- Instance: The SQL Server instance name, or \"MSSQLSERVER\" for the default instance\r\n- InstanceID: The SQL Server instance ID identifier from the registry\r\n- Feature: The specific SQL Server component that is installed (e.g., Database Engine, Analysis Services, Reporting Services, Integration Services, Replication, Full-Text Search)\r\n- Language: The language/locale of the SQL Server installation (e.g., \"English\")\r\n- Edition: The SQL Server edition (Enterprise, Standard, Express, Developer, Evaluation, Web)\r\n- Version: The version number of SQL Server in format (e.g., \"15.0.2000.5\")\r\n- Clustered: Boolean indicating if this SQL Server instance is part of a failover cluster (True/False)\r\n- Configured: Boolean indicating if the SQL Server component is fully configured and operational (True/False)\nEach row represents one installed feature. A single SQL Server instance with multiple installed features will generate multiple objects.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaFeature -ComputerName sql2017, sql2016, sql2005\nGets all SQL Server features for all instances on sql2017, sql2016 and sql2005.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaFeature -Verbose\nGets all SQL Server features for all instances on localhost. Outputs to screen if no instances are found.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaFeature -ComputerName sql2017 -Credential ad\\sqldba\nGets all SQL Server features for all instances on sql2017 using the ad\\sqladmin credential (which has access to the Windows Server).", "Description": "Executes SQL Server\u0027s built-in feature discovery report to inventory all installed SQL Server components, editions, and instances across one or more servers. This function automates the manual process of running setup.exe /Action=RunDiscovery and parsing the resulting XML report, making it perfect for compliance auditing, license tracking, and environment documentation.\n\nThe function returns structured data showing exactly what SQL Server features are installed, which instances they belong to, their versions, editions, and configuration status. This is essential for DBAs who need to understand their SQL Server landscape without manually checking each server or running discovery reports individually.\n\nInspired by Dave Mason\u0027s (@BeginTry) post at\nhttps://itsalljustelectrons.blogspot.be/2018/04/SQL-Server-Discovery-Report.html\n\nAssumptions:\n1. The sub-folder \"Microsoft SQL Server\" exists in [System.Environment]::GetFolderPath(\"ProgramFiles\"),\neven if SQL was installed to a non-default path. This has been\nverified on SQL 2008R2 and SQL 2012. Further verification may be needed.\n2. The discovery report displays installed components for the version of SQL\nServer associated with setup.exe, along with installed components of all\nlesser versions of SQL Server that are installed.", "Links": "https://dbatools.io/Get-DbaFeature", "Synopsis": "Discovers installed SQL Server features and components across multiple servers", "Availability": "Windows only", "Params": [ [ "ComputerName", "Specifies the Windows computer names where you want to discover SQL Server features and components. Accepts multiple computers for bulk discovery operations.\r\nUse this when you need to inventory SQL Server installations across your environment for compliance auditing or license tracking.\r\nRequires PowerShell remoting to be enabled on remote computers. Note that this targets the Windows host, not SQL instance names.", "", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Allows you to login to servers using alternative credentials. To use:\n$cred = Get-Credential, then pass $cred object to the -Credential parameter.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Storage", "File", "Path" ], "CommandName": "Get-DbaFile", "Name": "Get-DbaFile", "Author": "Brandon Abshire, netnerds.net", "Syntax": "Get-DbaFile [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Path] \u003cString[]\u003e] [[-FileType] \u003cString[]\u003e] [[-Depth] \u003cInt32\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per file found in the specified directories across all target instances.\nDefault display properties (via Select-DefaultView):\r\n- Filename: The full path of the file on the target server (with path separators adapted for the host OS)\nAdditional properties available (via Select-Object *):\r\n- ComputerName: The name of the computer hosting the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- RemoteFilename: The UNC path to the file for remote access (\\\\ComputerName\\share\\path)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaFile -SqlInstance sqlserver2014a -Path E:\\Dir1\nLogs into the SQL Server \"sqlserver2014a\" using Windows credentials and searches E:\\Dir for all files\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaFile -SqlInstance sqlserver2014a -SqlCredential $cred -Path \u0027E:\\sql files\u0027\nLogs into the SQL Server \"sqlserver2014a\" using alternative credentials and returns all files in \u0027E:\\sql files\u0027\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$all = Get-DbaDefaultPath -SqlInstance sql2014\nPS C:\\\u003e Get-DbaFile -SqlInstance sql2014 -Path $all.Data, $all.Log, $all.Backup -Depth 3\nReturns the files in the default data, log and backup directories on sql2014, 3 directories deep (recursively).\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaFile -SqlInstance sql2014 -Path \u0027E:\\Dir1\u0027, \u0027E:\\Dir2\u0027\nReturns the files in \"E:\\Dir1\" and \"E:Dir2\" on sql2014\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaFile -SqlInstance sql2014, sql2016 -Path \u0027E:\\Dir1\u0027 -FileType fsf, mld\nFinds files in E:\\Dir1 ending with \".fsf\" and \".mld\" for both the servers sql2014 and sql2016.", "Description": "Searches directories on SQL Server machines remotely without requiring direct file system access or RDP connections. Uses the xp_dirtree extended stored procedure to return file listings that can be filtered by extension and searched recursively to specified depths. Defaults to the instance\u0027s data directory but accepts additional paths for comprehensive file system exploration.\n\nCommon use cases include locating orphaned database files, finding backup files for restores, auditing disk usage, and preparing for file migrations.\n\nYou can filter by extension using the -FileType parameter. By default, the default data directory will be returned. You can provide and additional paths to search using the -Path parameter.\n\nThanks to serg-52 for the query: https://www.sqlservercentral.com/Forums/Topic1642213-391-1.aspx", "Links": "https://dbatools.io/Get-DbaFile", "Synopsis": "Enumerates files and directories on remote SQL Server instances using xp_dirtree", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Allows you to login to servers using alternative credentials", "", false, "false", "", "" ], [ "Path", "Specifies additional directory paths to search beyond the instance\u0027s default data directory. Accepts multiple paths as an array.\r\nUse this when you need to scan specific locations for orphaned files, backup locations, or custom database file directories.\r\nDefaults to the instance\u0027s data directory if not specified.", "", false, "false", "", "" ], [ "FileType", "Filters results to only show files with specific extensions. Pass extensions without the dot (e.g., \u0027mdf\u0027, \u0027ldf\u0027, \u0027bak\u0027).\r\nUse this to find specific database files like data files (mdf, ndf), log files (ldf), or backup files (bak, trn).\r\nAccepts multiple extensions to search for different file types simultaneously.", "", false, "false", "", "" ], [ "Depth", "Controls how many subdirectory levels to search recursively. Default is 1 (current directory only).\r\nIncrease this value when searching deep folder structures for scattered database files or backup archives.\r\nHigher values take more time but ensure comprehensive file discovery across complex directory trees.", "", false, "false", "1", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": "Filestream", "CommandName": "Get-DbaFilestream", "Name": "Get-DbaFilestream", "Author": "Stuart Moore (@napalmgram) | Chrissy LeMaire (@cl)", "Syntax": "Get-DbaFilestream [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per instance queried, containing both service-level and instance-level FileStream configuration status.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The name of the computer hosting the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- InstanceAccess: Human-readable description of instance-level FileStream access (Disabled, T-SQL access enabled, or Full access enabled)\r\n- ServiceAccess: Human-readable description of service-level FileStream access (Disabled, FileStream enabled for T-SQL access, FileStream enabled for T-SQL and IO streaming access, or FileStream \r\nenabled for T-SQL, IO streaming, and remote clients)\r\n- ServiceShareName: The Windows file share name used for FileStream when service-level access is enabled\nAdditional properties available (via Select-Object *):\r\n- InstanceAccessLevel: Numeric code for instance-level FileStream access (0-2)\r\n- ServiceAccessLevel: Numeric code for service-level FileStream access (0-3)\r\n- Credential: The Windows credentials used for service-level queries (passed from -Credential parameter)\r\n- SqlCredential: The SQL Server credentials used for instance-level queries (passed from -SqlCredential parameter)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaFilestream -SqlInstance server1\\instance2\nWill return the status of Filestream configuration for the service and instance server1\\instance2\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaFilestream -SqlInstance server1\\instance2 -SqlCredential sqladmin\nPrompts for the password to the SQL Login \"sqladmin\" then returns the status of Filestream configuration for the service and instance server1\\instance2", "Description": "Retrieves FileStream configuration status by checking both the SQL Server service configuration and the instance-level sp_configure settings. This function helps DBAs quickly identify FileStream configuration mismatches between service and instance levels, which are common causes of FileStream functionality issues. The function returns detailed access levels, share names, and indicates whether a restart is pending to apply configuration changes.", "Links": "https://dbatools.io/Get-DbaFilestream", "Synopsis": "Retrieves FileStream configuration status at both the SQL Server service and instance levels.", "Availability": "Windows only", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.", "", false, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Credential", "Login to the target Windows server using alternative credentials.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Network", "Connection", "Firewall" ], "CommandName": "Get-DbaFirewallRule", "Name": "Get-DbaFirewallRule", "Author": "Andreas Jordan (@JordanOrdix), ordix.de", "Syntax": "Get-DbaFirewallRule [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-Credential] \u003cPSCredential\u003e] [[-Type] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one firewall rule object per matching SQL Server firewall rule on the target computer. Each object contains details about the rule\u0027s protocol, port, and program path.\nDefault properties returned:\r\n- ComputerName: The name of the computer hosting the SQL Server instance\r\n- InstanceName: The SQL Server instance name (null for Browser rules)\r\n- SqlInstance: The full SQL Server instance name (computer\\instance format; null for Browser)\r\n- DisplayName: The display name of the firewall rule\r\n- Type: Category of rule (Engine, Browser, DAC, or DatabaseMirroring)\r\n- Protocol: Protocol type used by the rule (TCP, UDP, etc.)\r\n- LocalPort: The port number(s) the rule applies to\r\n- Program: The executable path allowed through the firewall\nAdditional properties available:\r\n- Name: The internal name of the firewall rule\r\n- Rule: The raw Get-NetFirewallRule object with all native properties\r\n- Credential: The credential object used for execution\nWhen an error occurs during remote execution, an error object is returned instead with:\r\n- ComputerName: The target computer name\r\n- Warning: Any warning messages from Get-NetFirewallRule\r\n- Error: Error message details if the operation failed\r\n- Exception: The exception object containing full error information\r\n- Details: Full diagnostic information from the remote execution", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaFirewallRule -SqlInstance SRV1\nReturns the firewall rule for the default instance on SRV1.\r\nIn case the instance is not listening on port 1433, it also returns the firewall rule for the SQL Server Browser.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaFirewallRule -SqlInstance SRV1\\SQL2016 -Type Engine\nReturns only the firewall rule for the instance SQL2016 on SRV1.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaFirewallRule -SqlInstance SRV1\\SQL2016 -Type Browser\nPS C:\\\u003e Get-DbaFirewallRule -SqlInstance SRV1 -Type Browser\nBoth commands return the firewall rule for the SQL Serer Browser on SRV1.\r\nAs the Browser is not bound to a specific instance, only the computer part of SqlInstance is used.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaFirewallRule -SqlInstance SRV1\\SQL2016 -Type AllInstance\nReturns all firewall rules on the computer SRV1 related to SQL Server.\r\nThe value \"AllInstance\" only uses the computer name part of SqlInstance.", "Description": "Retrieves Windows firewall rules for SQL Server components from target computers, helping DBAs troubleshoot connectivity issues and audit network security configurations. This command queries firewall rules for the SQL Server Engine, Browser service, and Dedicated Admin Connection (DAC) to identify which ports are open and what programs are allowed through the firewall.\n\nMost useful when SQL Server connections are failing and you need to verify firewall rules are correctly configured, or when conducting security audits to document which SQL Server ports are exposed. The command only works with standardized firewall rules created by New-DbaFirewallRule, as it relies on specific group names and naming conventions.\n\nThis is a wrapper around Get-NetFirewallRule executed at the target computer, so the NetSecurity PowerShell module must be available on the remote system. The command returns detailed information including port numbers, protocols, and executable paths for each firewall rule.\n\nThe functionality is currently limited. Help to extend the functionality is welcome.\n\nAs long as you can read this note here, there may be breaking changes in future versions.\nSo please review your scripts using this command after updating dbatools.", "Links": "https://dbatools.io/Get-DbaFirewallRule", "Synopsis": "Retrieves Windows firewall rules for SQL Server components from target computers for network troubleshooting and security auditing.", "Availability": "Windows only", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "Credential", "Credential object used to connect to the Computer as a different user.", "", false, "false", "", "" ], [ "Type", "Specifies which SQL Server firewall rule types to retrieve from the target computer.\r\nUse this when you need to focus on specific SQL Server components during network troubleshooting or security audits.\nValid values are:\r\n* Engine - Returns firewall rules for the SQL Server Database Engine service\r\n* Browser - Returns firewall rules for the SQL Server Browser service (UDP 1434)\r\n* DAC - Returns firewall rules for the Dedicated Admin Connection\r\n* DatabaseMirroring - Returns firewall rules for database mirroring or Availability Groups\r\n* AllInstance - Returns all SQL Server-related firewall rules on the target computer\nWhen omitted, returns Engine and DAC rules for the specified instance, plus Browser rules if the instance uses a non-standard port.", "", false, "false", "", "Engine,Browser,DAC,DatabaseMirroring,AllInstance" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Certificate", "Security" ], "CommandName": "Get-DbaForceNetworkEncryption", "Name": "Get-DbaForceNetworkEncryption", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaForceNetworkEncryption [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance with the Force Network Encryption configuration details.\nProperties:\r\n- ComputerName: The name of the computer hosting the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance format)\r\n- ForceEncryption: Boolean indicating whether Force Network Encryption is enabled on the instance\r\n- CertificateThumbprint: The SHA-1 thumbprint of the certificate used for encryption, or $null if no certificate is configured", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaForceNetworkEncryption\nGets Force Encryption properties on the default (MSSQLSERVER) instance on localhost - requires (and checks for) RunAs admin.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaForceNetworkEncryption -SqlInstance sql01\\SQL2008R2SP2\nGets Force Network Encryption for the SQL2008R2SP2 on sql01. Uses Windows Credentials to both login and view the registry.", "Description": "Retrieves the Force Network Encryption setting and associated certificate from SQL Server\u0027s network configuration stored in the Windows registry. This setting determines whether SQL Server requires all client connections to use encryption, preventing unencrypted communication.\n\nUseful for security audits and compliance checks to verify that network encryption policies are properly configured across your SQL Server estate. The function accesses the SuperSocketNetLib registry key where SQL Server stores its network security settings, requiring Windows-level access rather than SQL Server authentication.", "Links": "https://dbatools.io/Get-DbaForceNetworkEncryption", "Synopsis": "Retrieves Force Network Encryption configuration from SQL Server\u0027s network settings", "Availability": "Windows only", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. Defaults to localhost.", "", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Allows you to login to the computer (not sql instance) using alternative Windows credentials", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Database", "Index" ], "CommandName": "Get-DbaHelpIndex", "Name": "Get-DbaHelpIndex", "Author": "Nic Cain, sirsql.net", "Syntax": "Get-DbaHelpIndex [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [[-ObjectName] \u003cString\u003e] [-IncludeStats] [-IncludeDataTypes] [-Raw] [-IncludeFragmentation] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per index and optionally per statistics object. Each object represents an index or statistics on a table, providing comprehensive information about its structure, usage, and \r\nmaintenance characteristics.\nDefault properties:\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: The name of the database containing the index\r\n- Object: The table containing the index (schema.table format)\r\n- Index: The name of the index; empty string for statistics-only rows\r\n- Statistics: The name of the statistics object; null for index rows\r\n- IndexType: Type of index structure (Clustered Index, Nonclustered Index, Heap) with optional qualifiers (PRIMARY KEY, UNIQUE, UNIQUE CONSTRAINT)\r\n- KeyColumns: Comma-separated list of key columns with optional DESC markers and data types (if -IncludeDataTypes)\r\n- IncludeColumns: Comma-separated list of included columns with optional data types (if -IncludeDataTypes); empty string if none\r\n- FilterDefinition: Filter predicate for filtered indexes; empty string if no filter\r\n- FillFactor: Fill factor value (0-100) for the index; empty string for statistics rows\r\n- DataCompression: Compression type (Row, Page, or ColumnStore); empty string for No Compression\r\n- IndexReads: Numeric count of index seeks, scans, and lookups (formatted with thousands separators unless -Raw)\r\n- IndexUpdates: Numeric count of index write operations (formatted with thousands separators unless -Raw)\r\n- Size: Index size in kilobytes; formatted as N0 unless -Raw (then dbasize object) (formatted with thousands separators unless -Raw); empty string for statistics rows\r\n- IndexRows: Numeric row count in the index or statistics; formatted with thousands separators unless -Raw\r\n- IndexLookups: Numeric count of lookup operations (only for heap or clustered index); empty string for statistics rows\r\n- MostRecentlyUsed: DateTime of most recent index usage; null if never used (1900 year) or no usage data\r\n- StatsSampleRows: Number of rows sampled when statistics were built/updated; empty for index rows\r\n- StatsRowMods: Number of modifications to underlying data since last statistics update; empty for index rows\r\n- HistogramSteps: Number of steps in the statistics histogram; empty for index rows\r\n- StatsLastUpdated: DateTime when statistics were last updated; empty for index rows\r\n- IndexFragInPercent: Fragmentation percentage (0-100 formatted as F2 decimal) of the index; only present when -IncludeFragmentation specified; empty string otherwise\nWhen -IncludeStats is specified, statistics-only objects are also returned with index-specific properties set to empty strings and statistics properties populated.\nWhen -Raw is specified, numeric values return as dbasize objects rather than formatted strings, enabling calculations and comparisons without string parsing.\nAll properties are returned as strings in default mode for display formatting. Use -Raw for numeric calculations.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaHelpIndex -SqlInstance localhost -Database MyDB\nReturns information on all indexes on the MyDB database on the localhost.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaHelpIndex -SqlInstance localhost -Database MyDB,MyDB2\nReturns information on all indexes on the MyDB \u0026 MyDB2 databases.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaHelpIndex -SqlInstance localhost -Database MyDB -ObjectName dbo.Table1\nReturns index information on the object dbo.Table1 in the database MyDB.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaHelpIndex -SqlInstance localhost -Database MyDB -ObjectName dbo.Table1 -IncludeStats\nReturns information on the indexes and statistics for the table dbo.Table1 in the MyDB database.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaHelpIndex -SqlInstance localhost -Database MyDB -ObjectName dbo.Table1 -IncludeDataTypes\nReturns the index information for the table dbo.Table1 in the MyDB database, and includes the data types for the key and include columns.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaHelpIndex -SqlInstance localhost -Database MyDB -ObjectName dbo.Table1 -Raw\nReturns the index information for the table dbo.Table1 in the MyDB database, and returns the numerical data without localized separators.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eGet-DbaHelpIndex -SqlInstance localhost -Database MyDB -IncludeStats -Raw\nReturns the index information for all indexes in the MyDB database as well as their statistics, and formats the numerical data without localized separators.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eGet-DbaHelpIndex -SqlInstance localhost -Database MyDB -IncludeFragmentation\nReturns the index information for all indexes in the MyDB database as well as their fragmentation\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2017 -Database MyDB | Get-DbaHelpIndex\nReturns the index information for all indexes in the MyDB database", "Description": "This function queries SQL Server DMVs to return detailed index and statistics information for performance analysis, index maintenance planning, and identifying optimization opportunities. You can target all indexes in a database or focus on a specific table to analyze index usage patterns, sizes, and fragmentation levels.\n\nEssential for DBAs performing index tuning, this command helps identify unused indexes for removal, oversized indexes consuming storage, and indexes requiring maintenance based on fragmentation or usage statistics. The data combines structural information (key columns, include columns, filters) with runtime metrics (reads, updates, last used) to provide a complete index health picture.\n\nUses SQL Server DMVs and system tables, requiring SQL Server 2008 or later.\n\nThe data includes:\n- ObjectName: the table containing the index\n- IndexType: clustered/non-clustered/columnstore and whether the index is unique/primary key\n- KeyColumns: the key columns of the index\n- IncludeColumns: any include columns in the index\n- FilterDefinition: any filter that may have been used in the index\n- DataCompression: row/page/none depending upon whether or not compression has been used\n- IndexReads: the number of reads of the index since last restart or index rebuild\n- IndexUpdates: the number of writes to the index since last restart or index rebuild\n- SizeKB: the size the index in KB\n- IndexRows: the number of the rows in the index (note filtered indexes will have fewer rows than exist in the table)\n- IndexLookups: the number of lookups that have been performed (only applicable for the heap or clustered index)\n- MostRecentlyUsed: when the index was most recently queried (default to 1900 for when never read)\n- StatsSampleRows: the number of rows queried when the statistics were built/rebuilt\n- StatsRowMods: the number of changes to the statistics since the last rebuild\n- HistogramSteps: the number of steps in the statistics histogram\n- StatsLastUpdated: when the statistics were last rebuilt", "Links": "https://dbatools.io/Get-DbaHelpIndex", "Synopsis": "Retrieves comprehensive index and statistics information from SQL Server databases for performance analysis and optimization.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to analyze for index and statistics information. Accepts multiple database names and wildcard patterns.\r\nUse this when you need to focus your analysis on specific databases rather than scanning the entire instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Databases to skip during the index analysis process. Useful for excluding system databases or databases currently under maintenance.\r\nCommonly used to exclude tempdb or databases that are offline or in restoring state.", "", false, "false", "", "" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase for pipeline processing.\r\nEnables filtering databases first, then analyzing only the indexes on those specific databases.", "", false, "true (ByValue)", "", "" ], [ "ObjectName", "Targets index analysis to a specific table using either single name (uses default schema) or two-part naming like \u0027schema.table\u0027.\r\nEssential when troubleshooting performance issues on a specific table or when you need detailed statistics information on SQL Server 2005 instances.", "", false, "false", "", "" ], [ "IncludeStats", "Returns statistics objects in addition to indexes, providing complete picture of query optimization structures.\r\nUse this when analyzing query plan issues or determining which statistics might be missing or stale for specific tables.", "", false, "false", "False", "" ], [ "IncludeDataTypes", "Adds data type information for all key and include columns in the index definitions.\r\nHelpful when analyzing index key size, planning composite indexes, or understanding why certain indexes might be inefficient.", "", false, "false", "False", "" ], [ "Raw", "Returns numeric values without formatting (no thousands separators) and Size as a dbasize object.\r\nUse this when feeding results into other functions or when you need precise numeric values for calculations.", "", false, "false", "False", "" ], [ "IncludeFragmentation", "Adds fragmentation percentage data by querying sys.dm_db_index_physical_stats with DETAILED mode.\r\nCritical for index maintenance planning but significantly increases execution time on large databases with many indexes.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Instance", "Security" ], "CommandName": "Get-DbaHideInstance", "Name": "Get-DbaHideInstance", "Author": "Tracy Boggiano @TracyBoggiano, databaseuperhero.com", "Syntax": "Get-DbaHideInstance [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per instance containing the current Hide Instance setting.\nProperties:\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- HideInstance: Boolean indicating if the instance is hidden from network discovery ($true if hidden, $false if visible)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaHideInstance\nGets Hide Instance properties on the default (MSSQLSERVER) instance on localhost - requires (and checks for) RunAs admin.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaHideInstance -SqlInstance sql01\\SQL2008R2SP2\nGets Force Network Encryption for the SQL2008R2SP2 on sql01. Uses Windows Credentials to both login and view the registry.", "Description": "Retrieves the Hide Instance setting from the Windows registry for SQL Server instances. This security setting controls whether the instance appears when clients browse the network for available SQL Server instances. When Hide Instance is enabled, the SQL Server instance will not respond to broadcast requests from SQL Server Browser service, making it invisible to network discovery tools. DBAs use this setting as a security hardening measure to reduce the attack surface by preventing unauthorized discovery of SQL Server instances. Note that this requires Windows administrative access to the target server, not SQL Server permissions.", "Links": "https://dbatools.io/Get-DbaHideInstance", "Synopsis": "Retrieves the Hide Instance setting from SQL Server registry configuration", "Availability": "Windows only", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. Defaults to localhost.", "", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Allows you to login to the computer (not sql instance) using alternative Windows credentials", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Deployment", "Updates", "Patches" ], "CommandName": "Get-DbaInstalledPatch", "Name": "Get-DbaInstalledPatch", "Author": "Hiram Fleitas, @hiramfleitas, fleitasarts.com", "Syntax": "Get-DbaInstalledPatch [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server patch found on the target computer(s). Patches are filtered from the Windows Registry to include only those with \"Hotfix\" or \"Service Pack\" in their display name and \r\n\"SQL\" anywhere in the name.\nProperties:\r\n- ComputerName: The name of the computer where the patch was found\r\n- Name: The display name of the patch as shown in Windows Registry (e.g., \"Hotfix for SQL Server 2019 (KB5012345)\")\r\n- Version: The version number of the patch as stored in Registry\r\n- InstallDate: The installation date converted to DbaDate type; use .Date property for date-only access or .DateTime for full datetime", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaInstalledPatch -ComputerName HiramSQL1, HiramSQL2\nGets a list of SQL Server patches installed on HiramSQL1 and HiramSQL2.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-Content C:\\Monitoring\\Servers.txt | Get-DbaInstalledPatch\nGets the SQL Server patches from a list of computers in C:\\Monitoring\\Servers.txt.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaInstalledPatch -ComputerName SRV1 | Sort-Object InstallDate.Date\nGets the SQL Server patches from SRV1 and orders by date. Note that we use\r\na special customizable date datatype for InstallDate so you\u0027ll need InstallDate.Date", "Description": "Queries the Windows Registry to retrieve a complete history of SQL Server patches installed on one or more computers. This includes Cumulative Updates (CUs), Service Packs, and Hotfixes that have been applied to any SQL Server instance on the target machines.\n\nEssential for patch compliance audits, pre-upgrade planning, and troubleshooting environments where you need to verify what patches have been installed and when. The function returns patch names, versions, and installation dates so you can quickly assess patch levels across your SQL Server estate without manually checking each server.\n\nTo test if your build is up to date, use Test-DbaBuild.", "Links": "https://dbatools.io/Get-DbaInstalledPatch", "Synopsis": "Retrieves installed SQL Server patches from Windows Registry for patch compliance and audit reporting.", "Availability": "Windows only", "Params": [ [ "ComputerName", "Specifies the target computers to query for SQL Server patch information. Accepts single computer names, comma-separated lists, or pipeline input from text files.\r\nUse this to audit patch levels across multiple servers for compliance reporting or pre-upgrade planning.\r\nDefaults to the local computer when not specified.", "", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Credential object used to connect to the Computer as a different user.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Audit", "Security", "SqlAudit" ], "CommandName": "Get-DbaInstanceAudit", "Name": "Get-DbaInstanceAudit", "Author": "Garry Bargsley (@gbargsley), blog.garrybargsley.com", "Syntax": "Get-DbaInstanceAudit [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Audit] \u003cString[]\u003e] [[-ExcludeAudit] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Audit\nReturns one Audit object for each SQL Server audit configured at the instance level.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The name of the computer hosting the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Name: The name of the SQL Server audit\r\n- IsEnabled: Boolean indicating if the audit is currently enabled\r\n- OnFailure: Action to take when an audit event cannot be written (Continue, Shutdown, FailOperation)\r\n- MaximumFiles: Maximum number of audit files to retain\r\n- MaximumFileSize: Maximum size for each audit file\r\n- MaximumFileSizeUnit: Unit of measurement for MaximumFileSize (Megabyte, Gigabyte, Terabyte)\r\n- MaximumRolloverFiles: Number of files to rollover before recycling the oldest file\r\n- QueueDelay: Delay in milliseconds before flushing audit records to the audit target\r\n- ReserveDiskSpace: Boolean indicating if disk space equal to MaximumFileSize is pre-allocated\r\n- FullName: Full local file path where audit events are stored\nAdditional properties available:\r\n- RemoteFullName: Remote UNC path to the audit file location (\\\\computername\\c$\\path\\filename)\r\n- FilePath: Directory path where audit files are stored\r\n- FileName: Name of the audit file\r\n- Enabled: Same as IsEnabled property\nAll properties from the base SMO Audit object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaInstanceAudit -SqlInstance localhost\nReturns all Security Audits on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaInstanceAudit -SqlInstance localhost, sql2016\nReturns all Security Audits for the local and sql2016 SQL Server instances", "Description": "Retrieves all configured SQL Server audit objects at the instance level, which define where security audit events are stored and how they\u0027re managed. These audits capture login attempts, permission changes, and other security-related activities across the entire SQL Server instance. The function returns detailed information including audit file paths, size limits, rollover settings, and current status, helping DBAs monitor compliance and troubleshoot security configurations without manually querying system views.", "Links": "https://dbatools.io/Get-DbaInstanceAudit", "Synopsis": "Retrieves SQL Server audit objects from instance-level security auditing configurations.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function\r\nto be executed against multiple SQL Server instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Audit", "Specifies which audit objects to retrieve by name. Accepts multiple audit names to return only those specific audits.\r\nUse this when you need to check configuration or status for particular audits instead of retrieving all instance-level audits.", "", false, "false", "", "" ], [ "ExcludeAudit", "Specifies which audit objects to exclude from results by name. Accepts multiple audit names to filter out unwanted audits.\r\nUse this when you want to retrieve most audits but skip specific ones, such as excluding test or temporary audits from compliance reports.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Audit", "Security", "SqlAudit" ], "CommandName": "Get-DbaInstanceAuditSpecification", "Name": "Get-DbaInstanceAuditSpecification", "Author": "Garry Bargsley (@gbargsley), blog.garrybargsley.com", "Syntax": "Get-DbaInstanceAuditSpecification [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.ServerAuditSpecification\nReturns one ServerAuditSpecification object for each server-level audit specification configured on the SQL Server instance.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The name of the computer hosting the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- ID: Unique identifier for the server audit specification within the instance\r\n- Name: The name of the server audit specification\r\n- AuditName: The name of the SQL Server Audit that this specification is associated with\r\n- Enabled: Boolean indicating if the audit specification is currently enabled\r\n- CreateDate: DateTime when the audit specification was created\r\n- DateLastModified: DateTime when the audit specification was last modified\r\n- Guid: Globally unique identifier for the audit specification\nAll properties from the base SMO ServerAuditSpecification object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaInstanceAuditSpecification -SqlInstance localhost\nReturns all Security Audit Specifications on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaInstanceAuditSpecification -SqlInstance localhost, sql2016\nReturns all Security Audit Specifications for the local and sql2016 SQL Server instances", "Description": "Returns all server-level audit specifications configured on SQL Server instances, including their enabled status, associated audit names, and configuration details. This helps DBAs inventory audit configurations for compliance reporting, security assessments, and ensuring proper event monitoring is in place. Server audit specifications define which events are captured by SQL Server Audit at the instance level, such as login attempts, permission changes, and database access patterns.", "Links": "https://dbatools.io/Get-DbaInstanceAuditSpecification", "Synopsis": "Retrieves server-level audit specifications from SQL Server instances for compliance and security monitoring", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function\r\nto be executed against multiple SQL Server instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Install", "Instance", "Utility" ], "CommandName": "Get-DbaInstanceInstallDate", "Name": "Get-DbaInstanceInstallDate", "Author": "Mitchell Hamann (@SirCaptainMitch), mitchellhamann.com", "Syntax": "Get-DbaInstanceInstallDate [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [-IncludeWindows] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance with installation date information.\nDefault properties (without -IncludeWindows):\r\n- ComputerName: The name of the computer hosting the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance format)\r\n- SqlInstallDate: DateTime when SQL Server was originally installed (DbaDateTime type)\nWhen -IncludeWindows is specified, an additional property is included:\r\n- WindowsInstallDate: DateTime when the Windows operating system was installed (DbaDateTime type)\nThe SqlInstallDate and WindowsInstallDate properties are DbaDateTime objects that provide formatted date/time display and can be manipulated as standard datetime values. Queries sys.server_principals \r\n(SQL Server 2005+) or dbo.sysservers (SQL Server 2000) to determine installation dates.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaInstanceInstallDate -SqlInstance SqlBox1\\Instance2\nReturns an object with SQL Instance Install date as a string.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaInstanceInstallDate -SqlInstance winserver\\sqlexpress, sql2016\nReturns an object with SQL Instance Install date as a string for both SQLInstances that are passed to the cmdlet.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e\u0027sqlserver2014a\u0027, \u0027sql2016\u0027 | Get-DbaInstanceInstallDate\nReturns an object with SQL Instance Install date as a string for both SQLInstances that are passed to the cmdlet via the pipeline.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaInstanceInstallDate -SqlInstance sqlserver2014a, sql2016 -IncludeWindows\nReturns an object with the Windows Install date and the SQL install date as a string.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaRegServer -SqlInstance sql2014 | Get-DbaInstanceInstallDate\nReturns an object with SQL Instance install date as a string for every server listed in the Central Management Server on sql2014", "Description": "Queries system tables (sys.server_principals or sysservers) to determine when SQL Server was originally installed on each target instance. This information is essential for compliance auditing, license management, and tracking hardware refresh cycles. The function automatically handles different SQL Server versions using the appropriate system table, and can optionally retrieve the Windows OS installation date through WMI for complete infrastructure documentation. Returns structured data including computer name, instance name, and precise installation timestamps.", "Links": "https://dbatools.io/Get-DbaInstanceInstallDate", "Synopsis": "Retrieves SQL Server installation dates by querying system tables for compliance auditing and infrastructure tracking.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Credential", "Windows credentials used for WMI connection when retrieving Windows OS installation date with -IncludeWindows.\r\nOnly required when the current user lacks WMI access to the target server or when connecting across domains.", "", false, "false", "", "" ], [ "IncludeWindows", "Retrieves the Windows OS installation date in addition to SQL Server installation date using WMI.\r\nUseful for infrastructure audits requiring both application and operating system installation timestamps.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "TabCompletion", "Autocomplete" ], "CommandName": "Get-DbaInstanceList", "Name": "Get-DbaInstanceList", "Author": "the dbatools team + Claude", "Syntax": "Get-DbaInstanceList [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.String\nReturns instance names as strings. Each instance name in the user-maintained\r\nautocomplete list is returned as a separate string object.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaInstanceList\nReturns all instance names from the user-maintained autocomplete list.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaInstanceList | Remove-DbaInstanceList\nRemoves all instances from the user-maintained autocomplete list.", "Description": "Returns all SQL Server instance names from the user-maintained list that is pre-loaded\ninto the dbatools tab completion cache for the -SqlInstance parameter. This list allows\nusers to have their frequently used instances available for autocomplete in their\nPowerShell terminal without needing to connect to them first.\n\nUse Add-DbaInstanceList to add instances to the list and Remove-DbaInstanceList to\nremove them.\n\nInstances can also be pre-loaded at module import time by setting the\n$env:DBATOOLS_KNOWN_INSTANCES environment variable to a comma-separated list of instance\nnames in your PowerShell profile.", "Links": "https://dbatools.io/Get-DbaInstanceList", "Synopsis": "Returns the user-maintained list of SQL Server instances used for tab completion.", "Availability": "Windows, Linux, macOS", "Params": [ ] }, { "Tags": [ "Instance", "Configure", "Configuration", "General" ], "CommandName": "Get-DbaInstanceProperty", "Name": "Get-DbaInstanceProperty", "Author": "Klaas Vandenberghe (@powerdbaklaas)", "Syntax": "Get-DbaInstanceProperty [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-InstanceProperty] \u003cObject[]\u003e] [[-ExcludeInstanceProperty] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per instance property from the Information, UserOptions, and Settings collections. The function returns properties from three separate SMO collections, outputting each property \r\nwith contextual information about which collection it came from.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The name of the computer hosting the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance format)\r\n- Name: The property name (e.g., DefaultFile, MaxWorkerThreads, LoginMode, TcpPort)\r\n- Value: The current value of the configuration property (string or mixed type depending on property)\r\n- PropertyType: The type of property collection - either \"Information\", \"UserOption\", or \"Setting\"\nThe -InstanceProperty and -ExcludeInstanceProperty parameters filter which specific properties are returned but do not change the output structure.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaInstanceProperty -SqlInstance localhost\nReturns SQL Server instance properties on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaInstanceProperty -SqlInstance sql2, sql4\\sqlexpress\nReturns SQL Server instance properties on default instance on sql2 and sqlexpress instance on sql4\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e\u0027sql2\u0027,\u0027sql4\u0027 | Get-DbaInstanceProperty\nReturns SQL Server instance properties on sql2 and sql4\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaInstanceProperty -SqlInstance sql2,sql4 -InstanceProperty DefaultFile\nReturns SQL Server instance property DefaultFile on instance sql2 and sql4\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaInstanceProperty -SqlInstance sql2,sql4 -ExcludeInstanceProperty DefaultFile\nReturns all SQL Server instance properties except DefaultFile on instance sql2 and sql4\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Get-DbaInstanceProperty -SqlInstance sql2 -SqlCredential $cred\nConnects using sqladmin credential and returns SQL Server instance properties from sql2", "Description": "Retrieves all instance-level configuration properties from SQL Server\u0027s Information, UserOptions, and Settings collections via SMO. This gives you a complete inventory of server settings like default file paths, memory configuration, security options, and user defaults in a standardized format. Essential for configuration audits, compliance reporting, environment comparisons, and troubleshooting configuration-related issues across multiple instances.", "Links": "https://dbatools.io/Get-DbaInstanceProperty", "Synopsis": "Retrieves comprehensive SQL Server instance configuration properties for auditing and comparison", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "InstanceProperty", "Specifies which SQL Server instance properties to include from Information, UserOptions, and Settings collections. Accepts wildcards and arrays.\r\nUse this to focus on specific configuration properties like DefaultFile, MaxWorkerThreads, or LoginMode when auditing particular settings across instances.", "", false, "false", "", "" ], [ "ExcludeInstanceProperty", "Specifies which SQL Server instance properties to exclude from the results. Accepts wildcards and arrays.\r\nUse this to filter out noisy or irrelevant properties when you need a cleaner view of configuration data for reporting or comparison.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Management", "Protocol", "OS" ], "CommandName": "Get-DbaInstanceProtocol", "Name": "Get-DbaInstanceProtocol", "Author": "Klaas Vandenberghe (@PowerDbaKlaas)", "Syntax": "Get-DbaInstanceProtocol [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "WMI ServerNetworkProtocol object\nReturns one WMI ServerNetworkProtocol object per network protocol found on the target computer(s). The returned objects include Enable() and Disable() script methods for managing protocol states \r\nprogrammatically.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The name of the computer running SQL Server\r\n- InstanceName: The SQL Server instance name\r\n- DisplayName: The user-friendly name of the protocol (TCP/IP, Named Pipes, Shared Memory, VIA)\r\n- Name: The technical protocol name as recognized by SQL Server WMI\r\n- MultiIP: Boolean indicating if the protocol supports multiple IP configurations\r\n- IsEnabled: Boolean indicating whether the protocol is currently enabled or disabled\nMethods available on returned objects:\r\n- Enable(): Enables the network protocol; returns 0 on success\r\n- Disable(): Disables the network protocol; returns 0 on success\nThese methods can be called directly on the returned objects to manage protocol states without using SQL Server Configuration Manager.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaInstanceProtocol -ComputerName sqlserver2014a\nGets the SQL Server related server protocols on computer sqlserver2014a.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027sql1\u0027,\u0027sql2\u0027,\u0027sql3\u0027 | Get-DbaInstanceProtocol\nGets the SQL Server related server protocols on computers sql1, sql2 and sql3.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaInstanceProtocol -ComputerName sql1,sql2\nGets the SQL Server related server protocols on computers sql1 and sql2.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e(Get-DbaInstanceProtocol -ComputerName sql1 | Where-Object { $_.DisplayName -eq \u0027Named Pipes\u0027 }).Disable()\nDisables the VIA ServerNetworkProtocol on computer sql1.\r\nIf successful, return code 0 is shown.", "Description": "Retrieves the configuration and status of SQL Server network protocols (TCP/IP, Named Pipes, Shared Memory, VIA) by querying the WMI ComputerManagement namespace. This is essential for troubleshooting connectivity issues, auditing network configurations for security compliance, and managing protocol settings across multiple SQL Server instances.\n\nThe returned protocol objects include Enable() and Disable() methods, allowing you to manage protocol states directly without opening SQL Server Configuration Manager. This is particularly useful for automating security hardening by disabling unnecessary protocols or standardizing configurations across your environment.\n\nRequires Local Admin rights on destination computer(s).", "Links": "https://dbatools.io/Get-DbaInstanceProtocol", "Synopsis": "Retrieves SQL Server network protocol configuration and status from target computers.", "Availability": "Windows only", "Params": [ [ "ComputerName", "Specifies the target computer(s) where SQL Server instances are running. Accepts computer names, fully qualified domain names, or IP addresses.\r\nUse this when you need to check network protocol configurations on remote SQL Server machines for connectivity troubleshooting or security audits.", "cn,host,Server", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Credential object used to connect to the computer as a different user.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Database", "Trigger", "General" ], "CommandName": "Get-DbaInstanceTrigger", "Name": "Get-DbaInstanceTrigger", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaInstanceTrigger [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Trigger\nReturns one Trigger object per server-level DDL trigger on the specified instance(s).\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- ID: Unique identifier for the trigger\r\n- Name: The name of the trigger\r\n- AnsiNullsStatus: ANSI NULLS setting (ON or OFF)\r\n- AssemblyName: CLR assembly name (for CLR-based triggers)\r\n- BodyStartIndex: Starting character position of the trigger body in the script\r\n- ClassName: CLR class name (for CLR-based triggers)\r\n- CreateDate: DateTime when the trigger was created\r\n- DateLastModified: DateTime of the most recent modification\r\n- DdlTriggerEvents: DDL events that cause the trigger to fire (CREATE, ALTER, DROP, etc.)\r\n- ExecutionContext: Security context of trigger execution (Caller, Owner, or specific principal name)\r\n- ExecutionContextLogin: The principal that executes the trigger\r\n- ImplementationType: Implementation type (T-SQL or CLR)\r\n- IsDesignMode: Boolean indicating if the trigger is in design mode\r\n- IsEnabled: Boolean indicating if the trigger is active\r\n- IsEncrypted: Boolean indicating if the trigger body is encrypted\r\n- IsSystemObject: Boolean indicating if this is a system object\r\n- MethodName: CLR method name (for CLR-based triggers)\r\n- QuotedIdentifierStatus: QUOTED_IDENTIFIER setting\r\n- State: Current state of the SMO object (Existing, Creating, Pending, etc.)\r\n- TextHeader: The text header of the trigger definition\r\n- TextMode: The text mode setting for the trigger\nAll properties from the base SMO Trigger object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaInstanceTrigger -SqlInstance sql2017\nReturns all server triggers on sql2017", "Description": "Returns server-level DDL triggers that monitor and respond to instance-wide events like CREATE, ALTER, and DROP statements. Server triggers are commonly used for security auditing, change tracking, and preventing unauthorized schema modifications across all databases on an instance. This function helps identify what automated responses are configured at the server level, which is essential for troubleshooting unexpected DDL blocking and documenting compliance controls.", "Links": "https://dbatools.io/Get-DbaInstanceTrigger", "Synopsis": "Retrieves server-level DDL triggers from SQL Server instances for auditing and documentation", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "SqlLogin to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance..", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Instance", "Configure", "UserOption", "General" ], "CommandName": "Get-DbaInstanceUserOption", "Name": "Get-DbaInstanceUserOption", "Author": "Klaas Vandenberghe (@powerdbaklaas)", "Syntax": "Get-DbaInstanceUserOption [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Property\nReturns one Property object per user option configured at the instance level, representing the default user options that apply to new database connections.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Name: The name of the user option (e.g., ANSI_NULLS, QUOTED_IDENTIFIER, ANSI_PADDING, ANSI_WARNINGS, ARITHABORT, CONCAT_NULL_YIELDS_NULL, CURSOR_CLOSE_ON_COMMIT, NUMERIC_ROUNDABORT, \r\nIMPLICIT_TRANSACTIONS)\r\n- Value: The current value of the user option (typically ON or OFF for boolean options, or a numeric value)\nAll properties from the base SMO Property object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaInstanceUserOption -SqlInstance localhost\nReturns SQL Instance user options on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaInstanceUserOption -SqlInstance sql2, sql4\\sqlexpress\nReturns SQL Instance user options on default instance on sql2 and sqlexpress instance on sql4\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e\u0027sql2\u0027,\u0027sql4\u0027 | Get-DbaInstanceUserOption\nReturns SQL Instance user options on sql2 and sql4", "Description": "Returns the default user options configured at the SQL Server instance level that are automatically applied to new database connections. These settings include ANSI compliance options like ANSI_NULLS, QUOTED_IDENTIFIER, date format preferences, and other connection-level defaults. This is useful when standardizing connection behavior across environments or troubleshooting why applications behave differently on different instances. Unlike Get-DbaDbccUserOption which shows current session settings, this command shows the instance defaults that would be inherited by new connections.", "Links": "https://dbatools.io/Get-DbaInstanceUserOption", "Synopsis": "Retrieves instance-level user option defaults that affect new database connections", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.\r\nThis can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Diagnostic", "IOLatency" ], "CommandName": "Get-DbaIoLatency", "Name": "Get-DbaIoLatency", "Author": "Patrick Flynn (@sqllensman)", "Syntax": "Get-DbaIoLatency [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database file on the SQL Server instance, providing detailed I/O performance metrics collected from sys.dm_io_virtual_file_stats.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The name of the computer hosting the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- DatabaseId: Internal ID of the database containing the file\r\n- DatabaseName: Name of the database containing the file\r\n- FileId: Internal ID of the file within the database\r\n- PhysicalName: Operating system file path of the file\r\n- NumberOfReads: Total count of read operations since SQL Server instance startup\r\n- IoStallRead: Total wait time in milliseconds spent waiting for read operations to complete\r\n- NumberOfwrites: Total count of write operations since SQL Server instance startup\r\n- IoStallWrite: Total wait time in milliseconds spent waiting for write operations to complete\r\n- IoStall: Total cumulative I/O wait time in milliseconds (reads + writes)\r\n- NumberOfBytesRead: Total number of bytes read from this file since instance startup\r\n- NumberOfBytesWritten: Total number of bytes written to this file since instance startup\r\n- SampleMilliseconds: Time in milliseconds since the SQL Server instance started (used for duration calculations)\r\n- SizeOnDiskBytes: Current size of the file on disk in bytes\nHidden properties (excluded from default display but available with Select-Object *):\r\n- FileHandle: Internal file handle reference\r\n- ReadLatency: Average read latency calculated as IoStallRead / NumberOfReads in milliseconds\r\n- WriteLatency: Average write latency calculated as IoStallWrite / NumberOfwrites in milliseconds\r\n- Latency: Average I/O latency for both reads and writes calculated as IoStall / (NumberOfReads + NumberOfwrites) in milliseconds\r\n- AvgBPerRead: Average bytes per read operation calculated as NumberOfBytesRead / NumberOfReads\r\n- AvgBPerWrite: Average bytes per write operation calculated as NumberOfBytesWritten / NumberOfwrites\r\n- AvgBPerTransfer: Average bytes per I/O operation (both reads and writes combined)\nAll latency values are in milliseconds and are calculated to handle division by zero when no I/O has occurred (returns 0 in such cases).", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaIoLatency -SqlInstance sql2008, sqlserver2012\nGet IO subsystem latency statistics for servers sql2008 and sqlserver2012.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$output = Get-DbaIoLatency -SqlInstance sql2008 | Select-Object * | ConvertTo-DbaDataTable\nCollects all IO subsystem latency statistics on server sql2008 into a Data Table.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e\u0027sql2008\u0027,\u0027sqlserver2012\u0027 | Get-DbaIoLatency\nGet IO subsystem latency statistics for servers sql2008 and sqlserver2012 via pipline\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Get-DbaIoLatency -SqlInstance sql2008 -SqlCredential $cred\nConnects using sqladmin credential and returns IO subsystem latency statistics from sql2008", "Description": "Queries sys.dm_io_virtual_file_stats to collect detailed I/O performance statistics for every database file on the SQL Server instance. Returns calculated latency metrics including read latency, write latency, and overall latency in milliseconds, plus throughput statistics like average bytes per read and write operation. Essential for diagnosing slow database performance caused by storage bottlenecks, helping you identify which specific database files are experiencing high I/O wait times. Based on Paul Randal\u0027s SQL Server performance tuning methodology.\n\nReference: https://www.sqlskills.com/blogs/paul/how-to-examine-io-subsystem-latencies-from-within-sql-server/\n https://www.sqlskills.com/blogs/paul/capturing-io-latencies-period-time/", "Links": "https://dbatools.io/Get-DbaIoLatency", "Synopsis": "Retrieves I/O latency metrics for all database files to identify storage performance bottlenecks", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The SQL Server instance. Server version must be SQL Server version 2008 or higher.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Deployment", "Install", "Patch", "Update" ], "CommandName": "Get-DbaKbUpdate", "Name": "Get-DbaKbUpdate", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaKbUpdate [-Name] \u003cString[]\u003e [-Simple] [[-Language] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per KB update link found in the Microsoft update catalog. The properties returned depend on whether the -Simple switch is used and whether build version information is available \r\nfrom Get-DbaBuild.\nDefault display properties (full detailed output, when -Simple is NOT used):\r\n- Title: The name/title of the KB update (e.g., \"Cumulative Update 23 for SQL Server 2019\")\r\n- NameLevel: SQL Server release name (SQL Server 2019, 2017, etc.) from Get-DbaBuild\r\n- SPLevel: Service Pack level (SP0, SP1, etc.) from Get-DbaBuild\r\n- KBLevel: KB article number from Get-DbaBuild\r\n- CULevel: Cumulative Update number from Get-DbaBuild\r\n- BuildLevel: Full build number from Get-DbaBuild\r\n- SupportedUntil: Support end date from Get-DbaBuild\r\n- Architecture: CPU architecture - \"x64\", \"x86\", or \"ARM64\" based on extracted architecture information\r\n- Language: Language identifier for the KB update (e.g., \"en-US\" for English)\r\n- Hotfix: Boolean or status indicating if this is a hotfix (True/False)\r\n- Description: Full description of the KB update contents and fixes\r\n- LastModified: DateTime when the KB update was last modified\r\n- Size: File size of the download package\r\n- Classification: Microsoft classification (Critical, Important, Security Update, etc.)\r\n- SupportedProducts: Array of supported SQL Server versions/editions\r\n- MSRCNumber: Microsoft Security Response Center bulletin number if applicable\r\n- MSRCSeverity: MSRC severity rating (Critical, Important, Moderate, Low)\r\n- RebootBehavior: Whether installation requires reboot (Yes, No, Can be deferred)\r\n- RequestsUserInput: Whether installation requires user input (Yes, No)\r\n- ExclusiveInstall: Whether this update is exclusive/incompatible with other updates (Yes, No)\r\n- NetworkRequired: Whether network connectivity is required during installation (Yes, No)\r\n- UninstallNotes: Notes about uninstalling this update\r\n- UninstallSteps: Steps required to uninstall this update\r\n- UpdateId: Internal Microsoft update catalog GUID\r\n- Supersedes: Array of KB articles superseded by this update\r\n- SupersededBy: Array of KB articles that supersede this update\r\n- Link: Direct HTTP/HTTPS download URL from download.windowsupdate.com\nWhen -Simple switch is specified (reduced property set for performance):\r\n- Title: The name/title of the KB update\r\n- Architecture: CPU architecture (x64, x86, etc.)\r\n- Language: Language identifier\r\n- Hotfix: Boolean indicating if this is a hotfix\r\n- UpdateId: Internal Microsoft update catalog GUID\r\n- Link: Direct download URL\nWhen build information is unavailable from Get-DbaBuild:\r\nThe following properties are excluded: NameLevel, SPLevel, KBLevel, CULevel, BuildLevel, SupportedUntil\nNote: The function returns one object per download link found. A single KB article may have multiple links if different architectures or languages are available.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaKbUpdate -Name KB4057119\nGets detailed information about KB4057119. This works for SQL Server or any other KB.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaKbUpdate -Name KB4057119, 4057114\nGets detailed information about KB4057119 and KB4057114. This works for SQL Server or any other KB.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaKbUpdate -Name KB4057119, 4057114 -Simple\nA lil faster. Returns, at the very least: Title, Architecture, Language, Hotfix, UpdateId and Link\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaKbUpdate -Name KB4057119 -Language ja\nGets detailed information about KB4057119 in Japanese. This works for SQL Server or any other KB.\r\n(Link property includes the links for Japanese version of SQL Server if the KB was Service Pack)\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaKbUpdate -Name KB4057119 -Language ja | Save-DbaKbUpdate\nDownloads Japanese version of KB4057119.", "Description": "Searches Microsoft\u0027s update catalog website to retrieve comprehensive information about KB updates including service packs, hotfixes, and cumulative updates. Returns detailed metadata such as supported products, architecture, language, file size, supersession information, and direct download links. Integrates with Get-DbaBuild to provide SQL Server-specific versioning details when available, making it essential for patch management and update research workflows. Note that parsing multiple web pages can be slow since Microsoft doesn\u0027t provide an API for this data.", "Links": "https://dbatools.io/Get-DbaKbUpdate", "Synopsis": "Retrieves detailed metadata and download links for Microsoft KB updates from the update catalog", "Availability": "Windows, Linux, macOS", "Params": [ [ "Name", "Specifies the KB article number to search for, with or without the \u0027KB\u0027 prefix. Accepts multiple values for batch processing.\r\nUse this to retrieve update information for specific knowledge base articles like security patches, cumulative updates, or service packs.", "", true, "false", "", "" ], [ "Simple", "Returns only essential update information to improve performance by skipping detailed web scraping. Provides Title, Architecture, Language, Hotfix status, UpdateId, and download Link.\r\nUse this when you need basic KB information quickly or when processing many updates where full details aren\u0027t required.", "", false, "false", "False", "" ], [ "Language", "Filters results to show only updates for a specific language when multiple language versions exist. Service Packs typically have separate files per language, while Cumulative Updates usually include \r\nall languages in one file.\r\nUse this when you need updates for non-English environments or want to download language-specific packages. Accepts standard language codes like \"en\" for English, \"de\" for German, or \"ja\" for \r\nJapanese.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "DisasterRecovery", "Backup" ], "CommandName": "Get-DbaLastBackup", "Name": "Get-DbaLastBackup", "Author": "Klaas Vandenberghe (@PowerDBAKlaas)", "Syntax": "Get-DbaLastBackup [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-ExcludeReplica] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database processed, containing backup status information and compliance metrics.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: The name of the database\r\n- LastFullBackup: DateTime of the most recent full backup (DbaDateTime object with Date subproperty)\r\n- LastDiffBackup: DateTime of the most recent differential backup (DbaDateTime object with Date subproperty)\r\n- LastLogBackup: DateTime of the most recent transaction log backup (DbaDateTime object with Date subproperty)\nAdditional properties available (use Select-Object * to display):\r\n- RecoveryModel: Database recovery model (Simple, Full, or BulkLogged)\r\n- SinceFull: DbaTimeSpan representing time elapsed since last full backup; null if never backed up\r\n- SinceDiff: DbaTimeSpan representing time elapsed since last differential backup; null if never backed up\r\n- SinceLog: DbaTimeSpan representing time elapsed since last transaction log backup; null if never backed up\r\n- LastFullBackupIsCopyOnly: Boolean indicating if the last full backup was copy-only\r\n- LastDiffBackupIsCopyOnly: Boolean indicating if the last differential backup was copy-only (always false per SQL Server rules)\r\n- LastLogBackupIsCopyOnly: Boolean indicating if the last transaction log backup was copy-only\r\n- DatabaseCreated: DateTime when the database was created\r\n- DaysSinceDbCreated: Integer number of days since database creation\r\n- Status: String status indicator - \"OK\", \"New database, not backed up yet\", \"No Full or Diff Back Up in the last day\", or \"No Log Back Up in the last hour\"\nThe LastFullBackup, LastDiffBackup, and LastLogBackup properties are DbaDateTime objects that can be compared with .Date subproperty.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaLastBackup -SqlInstance ServerA\\sql987\nReturns a custom object with Server name, Database name, and the date the last time backups were performed.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaLastBackup -SqlInstance ServerA\\sql987 | Select-Object *\nReturns a custom object with Server name, Database name, and the date the last time backups were performed, and also recoverymodel and calculations on how long ago backups were taken and what the \r\nstatus is.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaLastBackup -SqlInstance ServerA\\sql987 | Select-Object * | Out-Gridview\nReturns a gridview displaying ComputerName, InstanceName, SqlInstance, Database, RecoveryModel, LastFullBackup, LastDiffBackup, LastLogBackup, SinceFull, SinceDiff, SinceLog, \r\nLastFullBackupIsCopyOnly, LastDiffBackupIsCopyOnly, LastLogBackupIsCopyOnly, DatabaseCreated, DaysSinceDbCreated, Status\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$MyInstances | Get-DbaLastBackup | Where-Object -FilterScript { $_.LastFullBackup.Date -lt (Get-Date).AddDays(-3) } | Format-Table -Property SqlInstance, Database, LastFullBackup\nReturns all databases on the given instances without a full backup in the last three days.\r\nNote that the property LastFullBackup is a custom object, with the subproperty Date of type datetime and therefore suitable for comparison with dates.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaLastBackup -SqlInstance ServerA\\sql987 | Where-Object { $_.LastFullBackupIsCopyOnly -eq $true }\nFilters for the databases that had a copy_only full backup done as the last backup.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaLastBackup -SqlInstance sql2019, sql2019b -ExcludeReplica\nReturns last backup information for all databases on both instances, excluding availability group databases\r\nwhere the current instance is not the preferred backup replica. This prevents false alerts when secondary\r\nreplicas appear to have no recent backups because backups are only performed on the preferred replica.", "Description": "Queries msdb backup history to retrieve the most recent full, differential, and transaction log backup dates for each database. This function helps DBAs quickly identify backup gaps and verify compliance with backup policies by showing when each backup type was last performed. The function also calculates elapsed time since each backup and provides status indicators to highlight potential issues, such as databases with no recent backups or transaction log backups that are overdue in full recovery model databases. Default output includes Server, Database, LastFullBackup, LastDiffBackup, and LastLogBackup columns.", "Links": "https://dbatools.io/Get-DbaLastBackup", "Synopsis": "Retrieves last backup dates and times for database backup compliance monitoring", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to check for backup history. Accepts wildcards for pattern matching.\r\nUse this when you need to focus on specific databases rather than scanning all databases on the instance.\r\nHelpful for monitoring critical production databases or troubleshooting backup issues on particular databases.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific databases from the backup history check. Commonly used to skip system databases or test databases.\r\nUse this when you want to check most databases but exclude certain ones like tempdb, development databases, or databases with known backup exemptions.", "", false, "false", "", "" ], [ "ExcludeReplica", "When this switch is enabled, databases in an AlwaysOn Availability Group where the current SQL Server instance\r\nis not the preferred backup replica are excluded from the results.\r\nThis is useful when running Get-DbaLastBackup against multiple servers in an availability group to avoid\r\nfalse positives where secondary replicas appear to have missing backups because backups are taken on the preferred replica only.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "CHECKDB", "Database", "Utility" ], "CommandName": "Get-DbaLastGoodCheckDb", "Name": "Get-DbaLastGoodCheckDb", "Author": "Jakob Bindslet (jakob@bindslet.dk)", "Syntax": "Get-DbaLastGoodCheckDb [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-InputObject] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database processed, containing database integrity check status and compliance metrics.\nProperties:\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: The name of the database\r\n- DatabaseCreated: DateTime when the database was created; $null if the date cannot be determined\r\n- LastGoodCheckDb: DateTime of the last successful DBCC CHECKDB operation; $null if CHECKDB has never been performed\r\n- DaysSinceDbCreated: Numeric value (days and fractional days) representing time elapsed since database creation\r\n- DaysSinceLastGoodCheckDb: Integer number of days since the last successful CHECKDB; only present if CHECKDB was previously run\r\n- Status: String status indicator - \"Ok\" (CHECKDB within last 7 days), \"New database, not checked yet\" (created within last 7 days), or \"CheckDB should be performed\" (overdue for CHECKDB)\r\n- DataPurityEnabled: Boolean indicating if data purity checks are enabled; $null for SQL Server 2008 and newer when not running as sysadmin; based on dbi_dbccFlags field for SQL Server 2005-2008\r\n- CreateVersion: Integer representing the internal version of the database (from dbi_createVersion DBCC DBINFO field); available only when running SQL Server 2008 and earlier or as sysadmin\r\n- DbccFlags: Integer representing DBCC flags from the database (from dbi_dbccFlags DBCC DBINFO field); available only when running SQL Server 2008 and earlier or as sysadmin\nNotes:\r\n- For SQL Server 2005-2008: Uses DBCC DBINFO() WITH TABLERESULTS to retrieve LastGoodCheckDb, CreateVersion, and DbccFlags\r\n- For SQL Server 2008 R2 and newer: Uses SMO LastGoodCheckDbTime property (CreateVersion and DbccFlags are not available)\r\n- CreateVersion and DbccFlags are only populated when running as sysadmin or on SQL Server versions prior to 2010\r\n- If CHECKDB has never been performed, LastGoodCheckDb will be $null and Status will indicate \"New database\" or \"should be performed\"", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaLastGoodCheckDb -SqlInstance ServerA\\sql987\nReturns a custom object displaying Server, Database, DatabaseCreated, LastGoodCheckDb, DaysSinceDbCreated, DaysSinceLastGoodCheckDb, Status and DataPurityEnabled\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaLastGoodCheckDb -SqlInstance ServerA\\sql987 -SqlCredential sqladmin | Format-Table -AutoSize\nReturns a formatted table displaying Server, Database, DatabaseCreated, LastGoodCheckDb, DaysSinceDbCreated, DaysSinceLastGoodCheckDb, Status and DataPurityEnabled. Authenticates using SQL Server \r\nauthentication.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaLastGoodCheckDb -SqlInstance sql2016 -ExcludeDatabase \"TempDB\" | Format-Table -AutoSize\nReturns a formatted table displaying Server, Database, DatabaseCreated, LastGoodCheckDb, DaysSinceDbCreated, DaysSinceLastGoodCheckDb, Status and DataPurityEnabled. All databases except for \"TempDB\" \r\nwill be displayed in the output.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2016 -Database DB1, DB2 | Get-DbaLastGoodCheckDb | Format-Table -AutoSize\nReturns a formatted table displaying Server, Database, DatabaseCreated, LastGoodCheckDb, DaysSinceDbCreated, DaysSinceLastGoodCheckDb, Status and DataPurityEnabled. Only databases DB1 abd DB2 will be \r\ndisplayed in the output.", "Description": "Retrieves and compares the timestamp for the last successful DBCC CHECKDB operation along with database creation dates. This helps DBAs monitor database integrity checking compliance and identify databases that need attention.\n\nThe function returns comprehensive information including days since the last good CHECKDB, database creation date, current status assessment (Ok, New database not checked yet, or CheckDB should be performed), and data purity settings. Use this to quickly identify which databases are overdue for integrity checks in your maintenance routines.\n\nThis function supports SQL Server 2005 and higher. For SQL Server 2008 and earlier, it uses DBCC DBINFO() WITH TABLERESULTS to extract the dbi_dbccLastKnownGood field. For newer versions, it uses the LastGoodCheckDbTime property from SMO.\n\nPlease note that this script uses the DBCC DBINFO() WITH TABLERESULTS. DBCC DBINFO has several known weak points, such as:\n- DBCC DBINFO is an undocumented feature/command.\n- The LastKnowGood timestamp is updated when a DBCC CHECKFILEGROUP is performed.\n- The LastKnowGood timestamp is updated when a DBCC CHECKDB WITH PHYSICAL_ONLY is performed.\n- The LastKnowGood timestamp does not get updated when a database in READ_ONLY.\n\nAn empty ($null) LastGoodCheckDb result indicates that a good DBCC CHECKDB has never been performed.\n\nSQL Server 2008R2 has a \"bug\" that causes each databases to possess two dbi_dbccLastKnownGood fields, instead of the normal one.\n\nThis script will only display the newest timestamp. If -Verbose is specified, the function will announce every time more than one dbi_dbccLastKnownGood fields is encountered.", "Links": "https://dbatools.io/Get-DbaLastGoodCheckDb", "Synopsis": "Retrieves the last successful DBCC CHECKDB timestamp and integrity status for databases", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. Defaults to localhost.", "", false, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to check for their last good CHECKDB status. Accepts wildcards for pattern matching.\r\nWhen omitted, all user and system databases on the instance will be processed. Use this to focus on specific databases or groups of databases when monitoring CHECKDB compliance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific databases from the CHECKDB status check. Commonly used to skip system databases like TempDB or databases with known maintenance schedules.\r\nAccepts wildcards and multiple database names to filter out databases that don\u0027t need regular CHECKDB monitoring.", "", false, "false", "", "" ], [ "InputObject", "Accepts database objects piped from Get-DbaDatabase, allowing for complex filtering scenarios before checking CHECKDB status.\r\nUse this when you need to apply advanced database filtering logic or when chaining multiple dbatools commands together.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "LatchStatistics", "Waits" ], "CommandName": "Get-DbaLatchStatistic", "Name": "Get-DbaLatchStatistic", "Author": "Patrick Flynn (@sqllensman)", "Syntax": "Get-DbaLatchStatistic [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Threshold] \u003cInt32\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per latch class that meets the specified cumulative wait time percentage threshold. When using the default 95% threshold, this typically includes 3-10 of the most significant latch \r\nclasses; using 100% threshold returns all non-BUFFER latch classes.\nProperties:\r\n- ComputerName: The name of the computer hosting the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- WaitType: The latch class name from sys.dm_os_latch_stats (e.g., ACCESS_METHODS_LATCH_EX, BUFFER_LATCH_EX)\r\n- WaitSeconds: Total wait time for this latch class in seconds (decimal with 2 decimal places)\r\n- WaitCount: Number of waiting requests for this latch class (bigint)\r\n- Percentage: Percentage of total latch wait time contributed by this latch class (0-100, decimal with 2 decimal places)\r\n- AverageWaitSeconds: Average wait time per request for this latch class in seconds (decimal with 4 decimal places, calculated as WaitSeconds/WaitCount)\r\n- URL: Direct hyperlink to SQLSkills documentation for this latch class (format: https://www.sqlskills.com/help/latches/{LatchClass})", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaLatchStatistic -SqlInstance sql2008, sqlserver2012\nCheck latch statistics for servers sql2008 and sqlserver2012\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaLatchStatistic -SqlInstance sql2008 -Threshold 98\nCheck latch statistics on server sql2008 for thresholds above 98%\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$output = Get-DbaLatchStatistic -SqlInstance sql2008 -Threshold 100 | Select-Object * | ConvertTo-DbaDataTable\nCollects all latch statistics on server sql2008 into a Data Table.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e\u0027sql2008\u0027,\u0027sqlserver2012\u0027 | Get-DbaLatchStatistic\nGet latch statistics for servers sql2008 and sqlserver2012 via pipline\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Get-DbaLatchStatistic -SqlInstance sql2008 -SqlCredential $cred\nConnects using sqladmin credential and returns latch statistics from sql2008\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e$output = Get-DbaLatchStatistic -SqlInstance sql2008\nPS C:\\\u003e $output\r\nPS C:\\\u003e foreach ($row in ($output | Sort-Object -Unique Url)) { Start-Process ($row).Url }\nDisplays the output then loads the associated sqlskills website for each result. Opens one tab per unique URL.", "Description": "Analyzes latch wait statistics from sys.dm_os_latch_stats to help identify latch contention issues that may be causing performance problems. This function implements Paul Randal\u0027s methodology for latch troubleshooting by returning the most significant latch classes based on cumulative wait time percentage. Each result includes direct links to SQLSkills documentation explaining what each latch class means and how to resolve related issues, making it easier to diagnose and fix latch-related performance bottlenecks without manually querying system DMVs.\n\nReturns:\n LatchClass\n WaitSeconds\n WaitCount\n Percentage\n AverageWaitSeconds\n URL\n\nReference: https://www.sqlskills.com/blogs/paul/advanced-performance-troubleshooting-waits-latches-spinlocks/\n https://www.sqlskills.com/blogs/paul/most-common-latch-classes-and-what-they-mean/", "Links": "https://dbatools.io/Get-DbaLatchStatistic", "Synopsis": "Retrieves latch contention statistics from SQL Server to identify performance bottlenecks", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The SQL Server instance. Server version must be SQL Server version 2005 or higher.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Threshold", "Specifies the cumulative percentage threshold for filtering which latch classes to return. Only returns latch classes that contribute to the specified percentage of total wait time.\r\nUse this to focus on the most significant latch contention issues by excluding less impactful latch classes from the results. Default is 95% per Paul Randal\u0027s methodology.", "", false, "false", "95", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "LinkedServer", "Linked" ], "CommandName": "Get-DbaLinkedServer", "Name": "Get-DbaLinkedServer", "Author": "Stephen Bennett, sqlnotesfromtheunderground.wordpress.com", "Syntax": "Get-DbaLinkedServer [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-LinkedServer] \u003cObject[]\u003e] [[-ExcludeLinkedServer] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.LinkedServer\nReturns one LinkedServer object per configured linked server found on the target instance(s). When filtered, returns only the linked servers matching the specified criteria.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Name: The name of the linked server\r\n- RemoteServer: The data source or remote server name (from DataSource property)\r\n- ProductName: The product type of the linked server\r\n- Impersonate: Boolean or collection indicating if impersonation is enabled\r\n- RemoteUser: The remote user login mapped for this linked server connection\r\n- Publisher: The distribution publisher for the linked server (if applicable)\r\n- Distributor: The distributor server (if applicable)\r\n- DateLastModified: DateTime indicating when the linked server configuration was last modified\nAdditional properties available from SMO LinkedServer object (accessible via Select-Object *):\r\n- LinkedServerType: Type of linked server (SqlServer, OleDbProvider, etc.)\r\n- RpsSiteUrl: RPS site URL if configured\r\n- LoginSecure: Boolean indicating if Windows authentication is enforced\r\n- ConnectionTimeout: Timeout in seconds for linked server connections\r\n- QueryTimeout: Query timeout in seconds on the linked server\r\n- Collation: Collation setting for the linked server\r\n- LazySchemaValidation: Boolean indicating lazy schema validation setting\r\n- UseRemoteCollation: Boolean indicating if remote collation is used\r\n- IsPublisher: Boolean indicating if this linked server is a publisher\r\n- IsDistributor: Boolean indicating if this linked server is a distributor\r\n- IsSubscriber: Boolean indicating if this linked server is a subscriber", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaLinkedServer -SqlInstance DEV01\nReturns all linked servers for the SQL Server instance DEV01\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaRegServer -SqlInstance DEV01 -Group SQLDEV | Get-DbaLinkedServer | Out-GridView\nReturns all linked servers for a group of servers from SQL Server Central Management Server (CMS). Send output to GridView.", "Description": "Pulls complete linked server information from one or more SQL Server instances, including remote server names, authentication methods, and security settings. This helps DBAs audit cross-server connections for compliance reporting, troubleshoot connectivity issues, and document distributed database architectures. Returns details about the remote server, product type, impersonation settings, and login mappings for each configured linked server.", "Links": "https://dbatools.io/Get-DbaLinkedServer", "Synopsis": "Retrieves linked server configurations and connection details from SQL Server instances.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function\r\nto be executed against multiple SQL Server instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "LinkedServer", "Specifies one or more linked server names to retrieve information for. Accepts an array of server names for filtering results.\r\nUse this when you need details on specific linked servers instead of all configured linked servers on the instance.", "", false, "false", "", "" ], [ "ExcludeLinkedServer", "Specifies one or more linked server names to exclude from the results. Accepts an array of server names to filter out.\r\nUse this when you want to skip specific linked servers, such as excluding test or deprecated connections from your inventory.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "LinkedServer", "Login" ], "CommandName": "Get-DbaLinkedServerLogin", "Name": "Get-DbaLinkedServerLogin", "Author": "Adam Lancaster, github.com/lancasteradam", "Syntax": "Get-DbaLinkedServerLogin [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-LinkedServer] \u003cString[]\u003e] [[-LocalLogin] \u003cString[]\u003e] [[-ExcludeLocalLogin] \u003cString[]\u003e] [[-InputObject] \u003cObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.LinkedServerLogin\nReturns one LinkedServerLogin object per local login mapping configured on the linked server.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Name: The name of the local SQL Server login\r\n- RemoteUser: The remote user account on the linked server\r\n- Impersonate: Boolean indicating if the remote user credentials are impersonated\nAdditional properties available (from SMO LinkedServerLogin object):\r\n- DateLastModified: DateTime when the login mapping was last modified\r\n- Parent: Reference to the parent LinkedServer object\r\n- State: Current state of the SMO object (Existing, Creating, Pending, etc.)\r\n- Urn: The Uniform Resource Name for the object\nAll properties from the base SMO object are accessible even though only default properties are displayed without using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaLinkedServerLogin -SqlInstance sql01 -LinkedServer linkedServer1 -LocalLogin login1\nGets the linked server login \"login1\" from the linked server \"linkedServer1\" on sql01.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaLinkedServerLogin -SqlInstance sql01 -LinkedServer linkedServer1 -ExcludeLocalLogin login2\nGets the linked server login(s) from the linked server \"linkedServer1\" on sql01 and excludes the login2 linked server login.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e(Get-DbaLinkedServer -SqlInstance sql01 -LinkedServer linkedServer1) | Get-DbaLinkedServerLogin -LocalLogin login1\nGets the linked server login \"login1\" from the linked server \"linkedServer1\" on sql01 using a pipeline with the linked server passed in.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e(Connect-DbaInstance -SqlInstance sql01) | Get-DbaLinkedServerLogin -LinkedServer linkedServer1 -LocalLogin login1\nGets the linked server login \"login1\" from the linked server \"linkedServer1\" on sql01 using a pipeline with the instance passed in.", "Description": "Retrieves the login mappings configured for linked servers, showing how local SQL Server logins are mapped to remote server credentials. This function returns details about each login mapping including the local login name, remote user account, and whether impersonation is enabled. Use this to audit linked server security configurations, troubleshoot authentication issues between servers, or document cross-server login relationships for compliance purposes.", "Links": "https://dbatools.io/Get-DbaLinkedServerLogin", "Synopsis": "Retrieves linked server login mappings and authentication configurations from SQL Server instances.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function\r\nto be executed against multiple SQL Server instances.", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "LinkedServer", "Specifies the name(s) of the linked server(s) to retrieve login mappings from. Required when using SqlInstance parameter.\r\nUse this to focus on specific linked servers when you have multiple configured on the instance.", "", false, "false", "", "" ], [ "LocalLogin", "Filters results to only include specific local SQL Server login names that have mappings configured for the linked server.\r\nUseful when auditing a specific user\u0027s access or troubleshooting authentication for particular accounts.", "", false, "false", "", "" ], [ "ExcludeLocalLogin", "Excludes specific local SQL Server login names from the results, showing all other configured login mappings.\r\nUse this to hide system accounts or service accounts when focusing on user login mappings.", "", false, "false", "", "" ], [ "InputObject", "Accepts piped input from Connect-DbaInstance or Get-DbaLinkedServer commands to work with existing connection objects.\r\nWhen piping from Get-DbaLinkedServer, the LinkedServer parameter becomes optional since the linked server context is already established.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "WhatIf", "Shows what would happen if the command were to run. No actions are actually performed.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before executing any changing operations within the command.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Management", "Locale", "OS" ], "CommandName": "Get-DbaLocaleSetting", "Name": "Get-DbaLocaleSetting", "Author": "Klaas Vandenberghe (@PowerDBAKlaas)", "Syntax": "Get-DbaLocaleSetting [[-ComputerName] \u003cString[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per computer with Windows locale settings from the HKEY_CURRENT_USER\\Control Panel\\International registry key.\nStandard properties (always included):\r\n- ComputerName: The name of the computer where locale settings were retrieved\nAdditional properties (dynamically retrieved from registry):\r\nThe command dynamically reads all values from the HKEY_CURRENT_USER\\Control Panel\\International registry key and adds them as properties. Common properties include:\nLocale and Language Settings:\r\n- Locale: The locale code (e.g., \"00000410\" for Italian)\r\n- LocaleName: The locale name in standard format (e.g., \"it-IT\")\r\n- sLanguage: The language abbreviation (e.g., \"ITA\")\r\n- sCurrency: The currency symbol (e.g., \"€\")\nDate and Time Formatting:\r\n- sLongDate: Format string for long date display\r\n- sShortDate: Format string for short date display\r\n- sTimeFormat: Format string for time display\r\n- sShortTime: Format string for short time display\nNumeric Formatting:\r\n- sDecimal: Decimal separator character (e.g., \".\")\r\n- sList: List separator character (e.g., \",\" or \";\")\r\n- iDigits: Number of digits after decimal separator\nAdditional Integer Settings (prefixed with \u0027i\u0027):\r\n- iCountry: Country/region identifier\r\n- iCurrDigits: Number of digits for currency\r\n- iCurrency: Currency format (0=prefix, 1=suffix)\r\n- iDate: Date format (0=M/D/Y, 1=D/M/Y, 2=Y/M/D)\r\n- iFirstDayOfWeek: First day of week (0=Sunday, 1=Monday, etc.)\r\n- iFirstWeekOfYear: First week of year definition\r\n- iLZero: Leading zero display (0=none, 1=display)\r\n- iTime: Time format (0=12-hour, 1=24-hour)\r\n- iTLZero: Time leading zero for hours (0=none, 1=display)\nAdditional String Settings (prefixed with \u0027s\u0027):\r\n- sAM: AM symbol for 12-hour format\r\n- sPM: PM symbol for 12-hour format\r\n- sThousand: Thousands separator character\nNote: The actual properties returned depend on what is configured in the registry. Not all standard properties may be present on all systems. Use Select-Object * to see all properties available for a \r\nspecific computer.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaLocaleSetting -ComputerName sqlserver2014a\nGets the Locale settings on computer sqlserver2014a.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027sql1\u0027,\u0027sql2\u0027,\u0027sql3\u0027 | Get-DbaLocaleSetting\nGets the Locale settings on computers sql1, sql2 and sql3.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaLocaleSetting -ComputerName sql1,sql2 -Credential $credential\nGets the Locale settings on computers sql1 and sql2 using SQL Authentication to authenticate to the servers.", "Description": "Retrieves Windows locale settings from the Control Panel\\International registry key on one or more computers. These settings directly impact SQL Server\u0027s date/time formatting, currency display, number formatting, and collation behavior.\n\nUseful for auditing regional configurations across your SQL Server environment, troubleshooting locale-related issues, or ensuring consistent settings before SQL Server installations. The function accesses the current user\u0027s locale settings from HKEY_CURRENT_USER\\Control Panel\\International.\n\nRequires Local Admin rights on destination computer(s).", "Links": "https://dbatools.io/Get-DbaLocaleSetting", "Synopsis": "Retrieves Windows locale settings from the registry on SQL Server computers for regional configuration analysis.", "Availability": "Windows only", "Params": [ [ "ComputerName", "Specifies the computer names where you want to retrieve Windows locale settings from the registry. Accepts SQL Server instance names but extracts only the computer portion.\r\nUse this to audit regional configurations across your SQL Server environment, especially before installations or when troubleshooting locale-related issues with date formats, currency display, or \r\ncollation behavior.", "cn,host,Server", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Credential object used to connect to the computer as a different user.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": "Login", "CommandName": "Get-DbaLogin", "Name": "Get-DbaLogin", "Author": "Mitchell Hamann (@SirCaptainMitch) | Rob Sewell (@SQLDBaWithBeard)", "Syntax": "Get-DbaLogin [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Login] \u003cString[]\u003e] [[-IncludeFilter] \u003cString[]\u003e] [[-ExcludeLogin] \u003cString[]\u003e] [[-ExcludeFilter] \u003cString[]\u003e] [-ExcludeSystemLogin] [[-Type] \u003cString\u003e] [-HasAccess] [-Locked] [-Disabled] [-MustChangePassword] [-Detailed] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Login\nReturns one Login object per login account found on the specified SQL Server instance(s). Each login object includes connection context properties and security status information.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Name: The login account name\r\n- LoginType: The type of login (SqlLogin, WindowsUser, or WindowsGroup)\r\n- CreateDate: DateTime when the login was created\r\n- LastLogin: DateTime of the most recent connection (null if never connected or SQL Server 2000)\r\n- HasAccess: Boolean indicating if the login has permission to connect\r\n- IsLocked: Boolean indicating if the login is currently locked due to failed authentication attempts\r\n- IsDisabled: Boolean indicating if the login is disabled\r\n- MustChangePassword: Boolean indicating if the login must change password on next connection\nWhen -Detailed switch is specified, additional properties are included:\r\n- BadPasswordCount: Number of failed login attempts since last successful login\r\n- BadPasswordTime: DateTime of the most recent failed login attempt\r\n- DaysUntilExpiration: Number of days until the login password expires (SQL Server only)\r\n- HistoryLength: Number of previous passwords tracked in history (SQL Server only)\r\n- IsMustChange: Boolean from LOGINPROPERTY indicating password change requirement\r\n- LockoutTime: DateTime when the login was locked due to authentication failures\r\n- PasswordHash: Hexadecimal hash of the password (SQL Server only, sensitive data)\r\n- PasswordLastSetTime: DateTime when the password was last set (SQL Server only)\nAdditional properties always available:\r\n- SidString: Hexadecimal string representation of the login\u0027s Security Identifier (SID)\nAll properties from the base SMO Login object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaLogin -SqlInstance sql2016\nGets all the logins from server sql2016 using NT authentication and returns the SMO login objects\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaLogin -SqlInstance sql2016 -SqlCredential $sqlcred\nGets all the logins for a given SQL Server using a passed credential object and returns the SMO login objects\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaLogin -SqlInstance sql2016 -SqlCredential $sqlcred -Login dbatoolsuser,TheCaptain\nGet specific logins from server sql2016 returned as SMO login objects.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaLogin -SqlInstance sql2016 -IncludeFilter \u0027##*\u0027,\u0027NT *\u0027\nGet all user objects from server sql2016 beginning with \u0027##\u0027 or \u0027NT \u0027, returned as SMO login objects.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaLogin -SqlInstance sql2016 -ExcludeLogin dbatoolsuser\nGet all user objects from server sql2016 except the login dbatoolsuser, returned as SMO login objects.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaLogin -SqlInstance sql2016 -Type Windows\nGet all user objects from server sql2016 that are Windows Logins\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eGet-DbaLogin -SqlInstance sql2016 -Type Windows -IncludeFilter *Rob*\nGet all user objects from server sql2016 that are Windows Logins and have Rob in the name\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eGet-DbaLogin -SqlInstance sql2016 -Type SQL\nGet all user objects from server sql2016 that are SQL Logins\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003eGet-DbaLogin -SqlInstance sql2016 -Type SQL -IncludeFilter *Rob*\nGet all user objects from server sql2016 that are SQL Logins and have Rob in the name\n-------------------------- EXAMPLE 10 --------------------------\nPS C:\\\u003eGet-DbaLogin -SqlInstance sql2016 -ExcludeSystemLogin\nGet all user objects from server sql2016 that are not system objects\n-------------------------- EXAMPLE 11 --------------------------\nPS C:\\\u003eGet-DbaLogin -SqlInstance sql2016 -ExcludeFilter \u0027##*\u0027,\u0027NT *\u0027\nGet all user objects from server sql2016 except any beginning with \u0027##\u0027 or \u0027NT \u0027, returned as SMO login objects.\n-------------------------- EXAMPLE 12 --------------------------\nPS C:\\\u003e\u0027sql2016\u0027, \u0027sql2014\u0027 | Get-DbaLogin -SqlCredential $sqlcred\nUsing Get-DbaLogin on the pipeline, you can also specify which names you would like with -Login.\n-------------------------- EXAMPLE 13 --------------------------\nPS C:\\\u003e\u0027sql2016\u0027, \u0027sql2014\u0027 | Get-DbaLogin -SqlCredential $sqlcred -Locked\nUsing Get-DbaLogin on the pipeline to get all locked logins on servers sql2016 and sql2014.\n-------------------------- EXAMPLE 14 --------------------------\nPS C:\\\u003e\u0027sql2016\u0027, \u0027sql2014\u0027 | Get-DbaLogin -SqlCredential $sqlcred -HasAccess -Disabled\nUsing Get-DbaLogin on the pipeline to get all Disabled logins that have access on servers sql2016 or sql2014.\n-------------------------- EXAMPLE 15 --------------------------\nPS C:\\\u003eGet-DbaLogin -SqlInstance sql2016 -Type SQL -Detailed\nGet all user objects from server sql2016 that are SQL Logins. Get additional info for login available from LoginProperty function\n-------------------------- EXAMPLE 16 --------------------------\nPS C:\\\u003e\u0027sql2016\u0027, \u0027sql2014\u0027 | Get-DbaLogin -SqlCredential $sqlcred -MustChangePassword\nUsing Get-DbaLogin on the pipeline to get all logins that must change password on servers sql2016 and sql2014.", "Description": "Returns detailed information about SQL Server login accounts, including authentication type, security status, and last login times. This function helps DBAs perform security audits by identifying locked, disabled, or expired accounts, and distinguish between Windows and SQL authentication logins. Use it to troubleshoot access issues, generate compliance reports, or review login configurations across multiple instances.", "Links": "https://dbatools.io/Get-DbaLogin", "Synopsis": "Retrieves SQL Server login accounts with filtering options for security audits and access management", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.You must have sysadmin access and server version must be SQL Server version 2000 or higher.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Login", "Specifies specific login names to retrieve instead of returning all logins from the instance.\r\nUse this when you need information about particular accounts for troubleshooting access issues or security audits.", "", false, "false", "", "" ], [ "IncludeFilter", "Includes only logins matching the specified wildcard patterns (supports * and ? wildcards).\r\nUse this to find groups of related logins, such as all domain accounts from a specific organizational unit or service accounts with naming conventions.", "", false, "false", "", "" ], [ "ExcludeLogin", "Excludes specific login names from the results.\r\nUseful when you want all logins except certain service accounts or system logins that you don\u0027t need to review.", "", false, "false", "", "" ], [ "ExcludeFilter", "Excludes logins matching the specified wildcard patterns (supports * and ? wildcards).\r\nCommonly used to filter out system accounts or built-in logins when focusing on user accounts during security reviews.", "", false, "false", "", "" ], [ "ExcludeSystemLogin", "Excludes built-in system logins like sa, BUILTIN\\Administrators, and NT AUTHORITY accounts from results.\r\nUse this when performing user access audits where you only want to see custom logins created for applications and users.", "ExcludeSystemLogins", false, "false", "False", "" ], [ "Type", "Filters results to show only Windows Authentication logins or SQL Server Authentication logins.\r\nUse \u0027Windows\u0027 to review domain accounts and local Windows users, or \u0027SQL\u0027 to audit SQL Server native accounts that store passwords in the database.", "", false, "false", "", "Windows,SQL" ], [ "HasAccess", "Returns only logins that currently have permission to connect to the SQL Server instance.\r\nUse this to verify which accounts can actually access the server, as some logins may exist but be denied connection rights.", "", false, "false", "False", "" ], [ "Locked", "Returns only login accounts that are currently locked due to failed authentication attempts.\r\nUse this to identify accounts that may need to be unlocked or investigate potential security incidents.", "", false, "false", "False", "" ], [ "Disabled", "Returns only login accounts that have been disabled but not dropped from the server.\r\nUse this to identify inactive accounts that should be reviewed for cleanup or re-enabling for returning employees.", "", false, "false", "False", "" ], [ "MustChangePassword", "Returns only SQL Server logins that are flagged to change their password on next login.\r\nUse this to identify accounts with temporary passwords or those requiring password updates due to security policies.", "", false, "false", "False", "" ], [ "Detailed", "Includes additional security-related properties like bad password count, password age, and lockout times.\r\nUse this for comprehensive security audits when you need detailed information about password policies and authentication failures.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Community", "OlaHallengren" ], "CommandName": "Get-DbaMaintenanceSolutionLog", "Name": "Get-DbaMaintenanceSolutionLog", "Author": "Klaas Vandenberghe (@powerdbaklaas) | Simone Bizzotto (@niphlod)", "Syntax": "Get-DbaMaintenanceSolutionLog [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-LogType] \u003cString[]\u003e] [[-Since] \u003cDateTime\u003e] [[-Path] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per index or statistics operation parsed from the IndexOptimize log files. When no log files are found or contain parseable operations, nothing is returned.\nProperties include:\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name\r\n- Database: The database name where the index or statistics operation was performed\r\n- StartTime: DateTime when the operation started (converted from \"Date and time\" field as dbadatetime)\r\n- Duration: The total duration of the operation (converted from \"Duration\" field as timespan)\r\n- Index: The index name for ALTER INDEX operations (null for UPDATE STATISTICS operations)\r\n- Statistics: The statistics name for UPDATE STATISTICS operations (null for ALTER INDEX operations)\r\n- Schema: The schema name containing the table\r\n- Table: The table name\r\n- Action: The action performed (REBUILD or REORGANIZE for indexes, null for statistics)\r\n- Options: The index operation options (FILLFACTOR, PAD_INDEX, etc.)\r\n- Timeout: The lock timeout value in milliseconds (if specified)\r\n- Partition: The partition number for partitioned indexes (null for non-partitioned)\r\n- ObjectType: The type of object being optimized\r\n- IndexType: The type of index (Heap, ClusteredIndex, NonClusteredIndex)\r\n- ImageText: Image text information from the log\r\n- NewLOB: New LOB information\r\n- FileStream: FileStream information\r\n- ColumnStore: ColumnStore information\r\n- AllowPageLocks: Page lock settings\r\n- PageCount: Number of pages in the index\r\n- Fragmentation: Index fragmentation percentage before optimization\r\n- Error: Any errors encountered during the operation (multiline string with newlines joining multiple error lines)\nAll properties from the parsed log file are accessible via Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaMaintenanceSolutionLog -SqlInstance sqlserver2014a\nGets the outcome of the IndexOptimize job on sql instance sqlserver2014a.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaMaintenanceSolutionLog -SqlInstance sqlserver2014a -SqlCredential $credential\nGets the outcome of the IndexOptimize job on sqlserver2014a, using SQL Authentication.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e\u0027sqlserver2014a\u0027, \u0027sqlserver2020test\u0027 | Get-DbaMaintenanceSolutionLog\nGets the outcome of the IndexOptimize job on sqlserver2014a and sqlserver2020test.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaMaintenanceSolutionLog -SqlInstance sqlserver2014a -Path \u0027D:\\logs\\maintenancesolution\\\u0027\nGets the outcome of the IndexOptimize job on sqlserver2014a, reading the log files in their custom location.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaMaintenanceSolutionLog -SqlInstance sqlserver2014a -Since \u00272017-07-18\u0027\nGets the outcome of the IndexOptimize job on sqlserver2014a, starting from july 18, 2017.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaMaintenanceSolutionLog -SqlInstance sqlserver2014a -LogType IndexOptimize\nGets the outcome of the IndexOptimize job on sqlserver2014a, the other options are not yet available! sorry", "Description": "Retrieves detailed execution information from IndexOptimize text log files when LogToTable=\u0027N\u0027 is configured in Ola Hallengren\u0027s MaintenanceSolution. This function parses the text files written to the SQL Server instance\u0027s log directory, extracting index operation details including start times, duration, fragmentation levels, and any errors encountered.\n\nThis command specifically targets scenarios where database logging is disabled and only file-based logging is available. The parsed output includes granular details about each index operation, such as the specific ALTER INDEX commands executed, statistics updates, partition information, and operation outcomes.\n\nBe aware that this command only works if sqlcmd is used to execute the procedures, which is a legacy method not used by newer installations. Currently, only IndexOptimize log parsing is supported - DatabaseBackup and DatabaseIntegrityCheck parsing are not yet available.\n\nFor modern deployments, we recommend using Install-DbaMaintenanceSolution and configuring procedures with LogToTable=\u0027Y\u0027 to enable database-based logging, which provides more reliable access to maintenance history.", "Links": "https://dbatools.io/Get-DbaMaintenanceSolutionLog", "Synopsis": "Parses IndexOptimize text log files from Ola Hallengren\u0027s MaintenanceSolution when database logging is disabled.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "LogType", "Specifies which Ola Hallengren maintenance solution log type to parse from text files. Accepts \u0027IndexOptimize\u0027, \u0027DatabaseBackup\u0027, or \u0027DatabaseIntegrityCheck\u0027.\r\nCurrently only IndexOptimize parsing is supported - use this when you need to analyze index rebuild and reorganize operations from file-based logs.\r\nDatabaseBackup and DatabaseIntegrityCheck parsing are planned for future releases.", "", false, "false", "IndexOptimize", "IndexOptimize,DatabaseBackup,DatabaseIntegrityCheck" ], [ "Since", "Filters log files to include only those created on or after the specified date and time.\r\nUse this when you need to focus on recent maintenance operations or investigate issues that started after a specific point in time.\r\nThe function examines both the filename timestamp and file creation time to determine which logs to process.", "", false, "false", "", "" ], [ "Path", "Specifies a custom directory path where maintenance solution log files are stored. Defaults to the SQL Server instance\u0027s error log directory.\r\nUse this when your maintenance solution jobs write logs to a non-standard location, such as a dedicated maintenance logs folder or shared network path.\r\nThe path must be accessible from the machine where you\u0027re running the command.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": "SMO", "CommandName": "Get-DbaManagementObject", "Name": "Get-DbaManagementObject", "Author": "Ben Miller (@DBAduck), dbaduck.com", "Syntax": "Get-DbaManagementObject [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-VersionNumber] \u003cInt32\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns information about SQL Server Management Object (SMO) assemblies, SqlClient libraries, and SNI modules found on the system or loaded in the PowerShell session. One object is returned per \r\nassembly or module discovered.\nProperties:\r\n- ComputerName: Name of the computer where the assembly or module is located\r\n- Version: Version number of the assembly or module\r\n- Loaded: Boolean indicating if the assembly/module is currently loaded in the PowerShell session\r\n- Path: File path to the assembly or module; null for Global Assembly Cache (GAC) assemblies\r\n- LoadTemplate: Ready-to-use PowerShell command to load the assembly/module via Add-Type\nMultiple output types may be included:\r\n- Local SMO assemblies from PowerShell installation directories (with file paths)\r\n- Global Assembly Cache (GAC) assemblies (without file paths, using AssemblyName)\r\n- Loaded assemblies currently in the AppDomain (with location information)\r\n- SNI modules with corresponding SqlClient assembly references\nUse the LoadTemplate property to quickly load discovered assemblies in PowerShell scripts.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaManagementObject\nReturns all versions of SMO on the computer\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaManagementObject -VersionNumber 13\nReturns just the version specified. If the version does not exist then it will return nothing.", "Description": "Scans the system for SQL Server Management Object (SMO) assemblies, SqlClient libraries, and SNI modules to help troubleshoot version conflicts and connectivity issues. This function checks both the Global Assembly Cache (GAC) and currently loaded assemblies in the PowerShell session, returning version information, load status, file paths, and ready-to-use Add-Type commands. Particularly useful when diagnosing why different SQL Server tools behave differently or when you need to load specific SMO versions in PowerShell scripts.", "Links": "https://dbatools.io/Get-DbaManagementObject", "Synopsis": "Discovers installed SQL Server Management Object (SMO) assemblies and their load status", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the Windows server(s) where you want to scan for SMO assemblies and SQL Client libraries.\r\nUse this when troubleshooting SMO version conflicts across multiple servers or when checking which SQL Server tools are installed on remote machines.", "", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "This command uses Windows credentials. This parameter allows you to connect remotely as a different user.", "", false, "false", "", "" ], [ "VersionNumber", "Filters results to show only assemblies matching the specified major version number (e.g., 13 for SQL Server 2016, 14 for 2017, 15 for 2019).\r\nUse this when you need to verify if a specific SQL Server version\u0027s SMO libraries are installed, particularly when troubleshooting version compatibility issues between different SQL Server tools.", "", false, "false", "0", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "MaxMemory", "Memory" ], "CommandName": "Get-DbaMaxMemory", "Name": "Get-DbaMaxMemory", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaMaxMemory [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance specified, containing memory configuration and physical memory information for comparison.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: Name of the computer hosting the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: Full SQL Server instance name (computer\\instance format)\r\n- Total: Total physical memory on the server in megabytes (MB)\r\n- MaxValue: Configured max server memory setting in megabytes (MB)\nAdditional available property:\r\n- Server: The SMO Server object representing the connected SQL Server instance; accessible for piping or further operations\nUse Select-Object * to access the Server property, or pipe the output to other commands for advanced scenarios.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaMaxMemory -SqlInstance sqlcluster, sqlserver2012\nGet memory settings for instances \"sqlcluster\" and \"sqlserver2012\". Returns results in megabytes (MB).\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaRegServer -SqlInstance sqlcluster | Get-DbaMaxMemory | Where-Object { $_.MaxValue -gt $_.Total }\nFind all servers in Server Central Management Server that have \u0027Max Server Memory\u0027 set to higher than the total memory of the server (think 2147483647)\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eFind-DbaInstance -ComputerName localhost | Get-DbaMaxMemory | Format-Table -AutoSize\nScans localhost for instances using the browser service, traverses all instances and displays memory settings in a formatted table.", "Description": "This command retrieves the SQL Server \u0027Max Server Memory\u0027 configuration setting alongside the total physical memory installed on the server. This comparison helps identify potential memory configuration issues that can impact SQL Server performance.\n\nUse this function to audit memory settings across your environment, troubleshoot performance issues related to memory pressure, or verify that SQL Server isn\u0027t configured to use more memory than physically available. The function is particularly useful for finding instances with the default max memory setting (2147483647 MB) that should be properly configured based on available physical memory.\n\nResults are returned in megabytes (MB) for both the configured max memory and total physical memory values.", "Links": "https://dbatools.io/Get-DbaMaxMemory", "Synopsis": "Retrieves SQL Server max memory configuration and compares it to total physical server memory", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Memory", "General" ], "CommandName": "Get-DbaMemoryCondition", "Name": "Get-DbaMemoryCondition", "Author": "IJeb Reitsma", "Syntax": "Get-DbaMemoryCondition [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per memory pressure notification record found in the SQL Server resource monitor ring buffers. Each object represents a single memory condition event with complete memory \r\nutilization metrics at that point in time.\nProperties:\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Runtime: DateTime when the query was executed in the instance\r\n- NotificationTime: Calculated DateTime of when the memory pressure event occurred\r\n- NotificationType: Type of memory notification (e.g., Low Physical Memory, Low Page File, Low Virtual Address Space)\r\n- MemoryUtilizationPercent: Current memory utilization as a percentage (0-100)\r\n- TotalPhysicalMemory: Total physical RAM in bytes; dbasize object convertible to KB, MB, GB, TB\r\n- AvailablePhysicalMemory: Free physical RAM in bytes; dbasize object convertible to KB, MB, GB, TB\r\n- TotalPageFile: Total page file size in bytes; dbasize object convertible to KB, MB, GB, TB\r\n- AvailablePageFile: Free page file size in bytes; dbasize object convertible to KB, MB, GB, TB\r\n- TotalVirtualAddressSpace: Total virtual address space in bytes; dbasize object convertible to KB, MB, GB, TB\r\n- AvailableVirtualAddressSpace: Free virtual address space in bytes; dbasize object convertible to KB, MB, GB, TB\r\n- NodeId: NUMA node identifier (for systems with multiple memory nodes)\r\n- SQLReservedMemory: SQL Server reserved memory in bytes; dbasize object convertible to KB, MB, GB, TB\r\n- SQLCommittedMemory: SQL Server committed memory in bytes; dbasize object convertible to KB, MB, GB, TB\r\n- RecordId: Unique identifier for this record in the ring buffer\r\n- Type: Record type from the resource monitor ring buffer\r\n- Indicators: Memory pressure indicators value (bit flags representing specific pressure conditions)\r\n- RecordTime: Ring buffer record timestamp in milliseconds (raw tick count)\r\n- CurrentTime: Current system time in milliseconds (sys.ms_ticks, for reference and time-based calculations)\nSize properties return dbasize objects that automatically format as human-readable units (Bytes, KB, MB, GB, TB) when displayed or accessed via properties like .Kilobytes, .Megabytes, .Gigabytes, \r\n.Terabytes.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaMemoryCondition -SqlInstance sqlserver2014a\nReturns the memory conditions for the selected instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaRegServer -SqlInstance sqlserver2014a -Group GroupName | Get-DbaMemoryCondition | Out-GridView\nReturns the memory conditions for a group of servers from SQL Server Central Management Server (CMS). Send output to GridView.", "Description": "Analyzes SQL Server\u0027s internal resource monitor ring buffers to identify memory pressure events and track memory utilization over time. This helps DBAs diagnose performance issues caused by insufficient memory, excessive paging, or memory pressure conditions that trigger automatic memory adjustments.\n\nThe function returns detailed memory statistics including physical memory usage, page file utilization, virtual address space consumption, and SQL Server-specific memory allocation metrics. Each record includes the exact timestamp when memory conditions were recorded, making it valuable for correlating memory pressure with performance degradation during specific time periods.\n\nThis command is based on a query provided by Microsoft support and queries the sys.dm_os_ring_buffers DMV to extract resource monitor notifications.", "Links": "https://dbatools.io/Get-DbaMemoryCondition", "Synopsis": "Retrieves memory pressure notifications and utilization metrics from SQL Server resource monitor ring buffers.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance..", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Management", "OS", "Memory" ], "CommandName": "Get-DbaMemoryUsage", "Name": "Get-DbaMemoryUsage", "Author": "Klaas Vandenberghe (@PowerDBAKlaas)", "Syntax": "Get-DbaMemoryUsage [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-MemoryCounterRegex] \u003cString\u003e] [[-PlanCounterRegex] \u003cString\u003e] [[-BufferCounterRegex] \u003cString\u003e] [[-SSASCounterRegex] \u003cString\u003e] [[-SSISCounterRegex] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per Windows performance counter collected from the target computer. Multiple objects are returned for each SQL Server instance based on the number of memory counters available that \r\nmatch the specified filter patterns. Results include counters from Memory Manager, Plan Cache, Buffer Manager, SSAS, and SSIS depending on which services are installed and accessible on the target \r\nsystem.\nProperties:\r\n- ComputerName: The name of the computer where counters were collected\r\n- SqlInstance: The SQL Server instance name (mssqlserver for default instance, or the instance name for named instances)\r\n- CounterInstance: The performance counter instance identifier extracted from the counter path\r\n- Counter: The name of the Windows performance counter (e.g., Total Server Memory, Free pages, cache pages)\r\n- Pages: Number of pages for buffer pool and plan cache counters; **null for Memory Manager, SSAS, and SSIS counters**. Represents 8 KB pages in the buffer pool or plan cache.\r\n- Memory: Memory usage as dbasize object in bytes. Conversion varies by counter type:\r\n - Memory Manager counters: KB converted to bytes (automatic dbasize formatting)\r\n - Plan Cache counters: Pages * 8192 converted to bytes (automatic dbasize formatting)\r\n - Buffer Manager counters: Pages * 8192 converted to bytes (automatic dbasize formatting)\r\n - SSAS counters: KB converted to bytes (automatic dbasize formatting)\r\n - SSIS counters: MB converted to bytes (automatic dbasize formatting)\nMemory property returns dbasize objects that automatically format as human-readable units (Bytes, KB, MB, GB, TB) when displayed or accessed via properties like .Kilobytes, .Megabytes, .Gigabytes, \r\n.Terabytes.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaMemoryUsage -ComputerName sql2017\nReturns a custom object displaying Server, counter instance, counter, number of pages, memory\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaMemoryUsage -ComputerName sql2017\\sqlexpress -SqlCredential sqladmin | Where-Object { $_.Memory.Megabyte -gt 100 }\nLogs into the sql2017\\sqlexpress as sqladmin using SQL Authentication then returns results only where memory exceeds 100 MB\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$servers | Get-DbaMemoryUsage | Out-Gridview\nGets results from an array of $servers then diplays them in a gridview.", "Description": "Collects detailed memory usage from SQL Server Database Engine, Analysis Services (SSAS), and Integration Services (SSIS) using Windows performance counters. This helps you troubleshoot memory pressure issues and understand how memory is allocated across different SQL Server components on the same server.\n\nGathers counters from Memory Manager (server memory, connection memory, lock memory), Plan Cache (procedure plans, ad-hoc plans), Buffer Manager (total pages, free pages, stolen pages), and service-specific memory usage. Each result shows the counter name, instance, page count where applicable, and memory in both KB and MB.\n\nSSRS does not have memory counters, only memory shrinks and memory pressure state.\n\nThis function requires local admin role on the targeted computers.", "Links": "https://dbatools.io/Get-DbaMemoryUsage", "Synopsis": "Collects memory usage statistics from all SQL Server services using Windows performance counters", "Availability": "Windows only", "Params": [ [ "ComputerName", "Specifies the Windows server to collect memory usage statistics from. Returns data for all SQL Server instances on the server.\r\nUse this when you need to monitor memory usage across multiple instances on a single server or compare memory allocation between different servers.", "Host,cn,Server", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "MemoryCounterRegex", "Filters which SQL Server Memory Manager counters to collect using a regular expression pattern. Controls memory allocation tracking for server memory, connections, locks, cache, optimizer, and \r\nworkspace usage.\r\nCustomize this when you need specific memory counters or when working with non-English SQL Server installations where counter names are localized.\r\nDefault pattern captures the most critical memory allocation counters that DBAs monitor for memory pressure troubleshooting.", "", false, "false", "(Total Server Memory |Target Server Memory |Connection Memory |Lock Memory |SQL Cache Memory |Optimizer Memory |Granted Workspace Memory |Cursor memory usage|Maximum Workspace)", "" ], [ "PlanCounterRegex", "Filters which SQL Server Plan Cache counters to collect using a regular expression pattern. Tracks memory usage for cached execution plans including stored procedures, ad-hoc queries, and prepared \r\nstatements.\r\nUse this to focus on specific plan cache types when investigating plan cache bloat or when working with non-English SQL Server installations.\r\nDefault pattern captures all major plan cache memory consumers that affect query performance and memory allocation.", "", false, "false", "(cache pages|procedure plan|ad hoc sql plan|prepared SQL Plan)", "" ], [ "BufferCounterRegex", "Filters which SQL Server Buffer Manager counters to collect using a regular expression pattern. Monitors buffer pool memory usage including data pages, free pages, stolen pages, and buffer pool \r\nextensions.\r\nModify this when troubleshooting specific buffer pool issues or working with non-English SQL Server installations where counter names are translated.\r\nDefault pattern includes essential buffer pool metrics that indicate memory pressure and buffer pool health.", "", false, "false", "(Free pages|Reserved pages|Stolen pages|Total pages|Database pages|target pages|extension .* pages)", "" ], [ "SSASCounterRegex", "Filters which SQL Server Analysis Services (SSAS) memory counters to collect using a regular expression pattern. Tracks memory consumption for SSAS instances and processing operations.\r\nCustomize this when monitoring specific SSAS memory usage patterns or working with non-English installations where SSAS counter names are localized.\r\nUse when troubleshooting SSAS memory issues or when SSAS and Database Engine compete for server memory resources.", "", false, "false", "(\\\\memory )", "" ], [ "SSISCounterRegex", "Filters which SQL Server Integration Services (SSIS) memory counters to collect using a regular expression pattern. Monitors memory usage for SSIS package execution and service operations.\r\nAdjust this when investigating SSIS memory consumption during ETL operations or working with non-English installations where SSIS counter names are translated.\r\nUseful for identifying memory bottlenecks in SSIS packages or when multiple SQL Server services compete for available memory.", "", false, "false", "(memory)", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "General", "Object", "StoredProcedure", "View", "Table", "Trigger" ], "CommandName": "Get-DbaModule", "Name": "Get-DbaModule", "Author": "Brandon Abshire, netnerds.net", "Syntax": "Get-DbaModule [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-ModifiedSince] \u003cDateTime\u003e] [[-Type] \u003cString[]\u003e] [-ExcludeSystemDatabases] [-ExcludeSystemObjects] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "Get-DbaDbModule", "Outputs": "PSCustomObject\nReturns one object per database module (stored procedure, function, view, trigger, etc.) found in the specified databases that matches the filter criteria.\nProperties:\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: The name of the database containing the module\r\n- Name: The name of the module object\r\n- ObjectID: The SQL Server object ID (int)\r\n- SchemaName: The name of the schema containing the module\r\n- Type: The type of module (VIEW, SQL_STORED_PROCEDURE, SQL_SCALAR_FUNCTION, SQL_TABLE_VALUED_FUNCTION, SQL_INLINE_TABLE_VALUED_FUNCTION, SQL_TRIGGER, DEFAULT_CONSTRAINT, RULE)\r\n- CreateDate: DateTime when the module was first created\r\n- ModifyDate: DateTime when the module was last modified\r\n- IsMsShipped: Boolean indicating if the module is a Microsoft-shipped system object\r\n- ExecIsStartUp: Boolean indicating if the stored procedure is configured to run at SQL Server startup (for stored procedures only)\r\n- Definition: The source code definition of the module (hidden by default, use Select-Object * to view)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaModule -SqlInstance sql2008, sqlserver2012\nReturn all modules for servers sql2008 and sqlserver2012 sorted by Database, Modify_Date ASC.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaModule -SqlInstance sql2008, sqlserver2012 | Select-Object *\nShows hidden definition column (informative wall of text).\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaModule -SqlInstance sql2008 -Database TestDB -ModifiedSince \"2017-01-01 10:00:00\"\nReturn all modules on server sql2008 for only the TestDB database with a modified date after 1 January 2017 10:00:00 AM.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaModule -SqlInstance sql2008 -Type View, Trigger, ScalarFunction\nReturn all modules on server sql2008 for all databases that are triggers, views or scalar functions.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e\u0027sql2008\u0027 | Get-DbaModule -Database TestDB -Type View, StoredProcedure, ScalarFunction\nReturn all modules on server sql2008 for only the TestDB database that are stored procedures, views or scalar functions. Input via Pipeline\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2008 -ExcludeSystem | Get-DbaModule -Type View, Trigger, ScalarFunction\nReturn all modules on server sql2008 for all user databases that are triggers, views or scalar functions.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2008, sqlserver2012 -ExcludeUser | Get-DbaModule -Type StoredProcedure -ExcludeSystemObjects\nReturn all user created stored procedures in the system databases for servers sql2008 and sqlserver2012.", "Description": "Queries sys.sql_modules and sys.objects to find database modules that have been modified within a specified timeframe, helping DBAs track recent code changes for troubleshooting, auditing, or deployment verification.\nEssential for identifying which stored procedures, functions, views, or triggers were altered during maintenance windows or after application deployments.\nReturns metadata including modification dates, schema names, and object types, with the actual module definition hidden by default but available when needed.\nSupports filtering by specific module types and can exclude system objects to focus on user-created code changes.", "Links": "https://dbatools.io/Get-DbaModule", "Synopsis": "Retrieves database modules (stored procedures, functions, views, triggers) modified after a specified date", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", false, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to search for modified modules. Accepts database names or wildcards for pattern matching.\r\nUse this when you need to focus on specific databases rather than scanning all databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific databases from the module search. Useful when you want to search most databases but skip certain ones like test or archive databases.\r\nCommonly used to exclude databases under maintenance or those known to have frequent module changes.", "", false, "false", "", "" ], [ "ModifiedSince", "Returns only modules modified after this date and time. Defaults to 1900-01-01 to include all modules.\r\nEssential for tracking recent code changes after deployments, maintenance windows, or troubleshooting sessions.", "", false, "false", "1900-01-01", "" ], [ "Type", "Filters results to specific module types only. Valid choices include: View, TableValuedFunction, DefaultConstraint, StoredProcedure, Rule, InlineTableValuedFunction, Trigger, ScalarFunction.\r\nUse this when investigating specific types of database objects, such as finding all modified stored procedures after an application release.", "", false, "false", "", "View,TableValuedFunction,DefaultConstraint,StoredProcedure,Rule,InlineTableValuedFunction,Trigger,ScalarFunction" ], [ "ExcludeSystemDatabases", "Excludes system databases (master, model, msdb, tempdb) from the search. Focus on user databases only.\r\nRecommended for routine auditing since system database changes are typically handled by SQL Server updates rather than application deployments.", "", false, "false", "False", "" ], [ "ExcludeSystemObjects", "Excludes Microsoft-shipped system objects from results. Shows only user-created modules.\r\nUse this to filter out built-in SQL Server objects and focus on custom business logic that your team maintains.", "", false, "false", "False", "" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase for pipeline operations. Allows chaining commands together.\r\nUseful for complex filtering scenarios where you first select databases with specific criteria, then search for modules within those databases.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Msdtc", "dtc", "General" ], "CommandName": "Get-DbaMsdtc", "Name": "Get-DbaMsdtc", "Author": "Klaas Vandenberghe (@powerdbaklaas)", "Syntax": "Get-DbaMsdtc [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per target computer containing the MSDTC service status and configuration details. If MSDTC service information cannot be retrieved, nothing is returned for that computer.\nProperties:\r\n- ComputerName: The name of the target computer\r\n- DTCServiceName: The display name of the MSDTC service (Microsoft Distributed Transaction Coordinator)\r\n- DTCServiceState: The current state of the MSDTC service (Running, Stopped, Paused, etc.)\r\n- DTCServiceStatus: The operational status of the MSDTC service (OK, Degraded, etc.)\r\n- DTCServiceStartMode: The start mode configuration of the service (Auto, Manual, Disabled)\r\n- DTCServiceAccount: The Windows account under which the MSDTC service runs\r\n- DTCCID_MSDTC: Component identifier (CID) for the MSDTC component (null if not available)\r\n- DTCCID_MSDTCUIS: Component identifier for the MSDTC User Interface Service component (null if not available)\r\n- DTCCID_MSDTCTIPGW: Component identifier for the MSDTC TIP Gateway component (null if not available)\r\n- DTCCID_MSDTCXATM: Component identifier for the MSDTC XA Transaction Manager component (null if not available)\r\n- networkDTCAccess: Boolean indicating if network DTC access is enabled\r\n- networkDTCAccessAdmin: Boolean indicating if network DTC admin access is enabled\r\n- networkDTCAccessClients: Boolean indicating if DTC network access is enabled for clients\r\n- networkDTCAccessInbound: Boolean indicating if inbound network DTC transactions are enabled\r\n- networkDTCAccessOutBound: Boolean indicating if outbound network DTC transactions are enabled\r\n- networkDTCAccessTip: Boolean indicating if TIP (Transaction Internet Protocol) access is enabled\r\n- networkDTCAccessTransactions: Boolean indicating if network DTC transactions are enabled\r\n- XATransactions: Boolean indicating if XA (eXtended Architecture) transactions are enabled", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaMsdtc -ComputerName srv0042\nGet DTC status for the server srv0042\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$Computers = (Get-Content D:\\configfiles\\SQL\\MySQLInstances.txt | % {$_.split(\u0027\\\u0027)[0]})\nPS C:\\\u003e $Computers | Get-DbaMsdtc\nGet DTC status for all the computers in a .txt file\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaMsdtc -Computername $Computers | Where-Object { $_.dtcservicestate -ne \u0027running\u0027 }\nGet DTC status for all the computers where the MSDTC Service is not running\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaMsdtc -ComputerName srv0042 | Out-Gridview\nGet DTC status for the computer srv0042 and show in a grid view", "Description": "Returns comprehensive MSDTC information including service state, security settings, and component identifiers (CIDs) from target servers. MSDTC is essential for SQL Server distributed transactions, linked server operations, and cross-database transactions that span multiple servers or instances.\n\nThis function helps DBAs troubleshoot distributed transaction failures, verify MSDTC configuration for linked servers, and audit security settings across multiple servers. It queries both the Windows service status and registry settings to provide a complete picture of the MSDTC configuration.\n\nRequires: Windows administrator access on target servers", "Links": "https://dbatools.io/Get-DbaMsdtc", "Synopsis": "Retrieves Microsoft Distributed Transaction Coordinator (MSDTC) service status and configuration details", "Availability": "Windows only", "Params": [ [ "ComputerName", "Specifies the server or computer names where MSDTC information should be retrieved. Accepts multiple values and supports pipeline input.\r\nUse this when checking MSDTC configuration across multiple SQL Server hosts, especially when troubleshooting distributed transactions or linked server issues.", "cn,host,Server", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Alternative credential", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Server", "Management", "Network" ], "CommandName": "Get-DbaNetworkActivity", "Name": "Get-DbaNetworkActivity", "Author": "Klaas Vandenberghe (@PowerDBAKlaas)", "Syntax": "Get-DbaNetworkActivity [[-ComputerName] \u003cString[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Win32_PerfFormattedData_Tcpip_NetworkInterface\nReturns one object per network interface found on the target computer(s).\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The name of the computer containing the network interface\r\n- NIC: The name of the network interface (alias for Name property)\r\n- BytesReceivedPersec: Bytes received per second on this interface (numeric value)\r\n- BytesSentPersec: Bytes sent per second on this interface (numeric value)\r\n- BytesTotalPersec: Total bytes per second (received + sent) on this interface (numeric value)\r\n- Bandwidth: Human-readable interface bandwidth capacity (10Gb, 1Gb, 100Mb, 10Mb, 1Mb, 100Kb, or Low)\nAdditional properties available (from Win32_PerfFormattedData_Tcpip_NetworkInterface):\r\n- CurrentBandwidth: Numeric bandwidth in bits per second (used to calculate display Bandwidth)\r\n- OutputQueueLength: Queue length for outbound data\r\n- PacketsReceivedPersec: Number of packets received per second\r\n- PacketsSentPersec: Number of packets sent per second\r\n- PacketsOutboundErrors: Number of transmission errors\r\n- PacketsReceivedErrors: Number of receive errors\r\n- PacketsReceivedDiscarded: Number of received packets discarded\r\n- PacketsOutboundDiscarded: Number of transmitted packets discarded\nAll properties from the base WMI object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaNetworkActivity -ComputerName sqlserver2014a\nGets the Current traffic on every Network Interface on computer sqlserver2014a.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027sql1\u0027,\u0027sql2\u0027,\u0027sql3\u0027 | Get-DbaNetworkActivity\nGets the Current traffic on every Network Interface on computers sql1, sql2 and sql3.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaNetworkActivity -ComputerName sql1,sql2\nGets the Current traffic on every Network Interface on computers sql1 and sql2.", "Description": "Retrieves current network activity metrics including bytes received, sent, and total throughput per second for every network interface on target computers. This function helps DBAs monitor network performance and identify bandwidth bottlenecks that could impact SQL Server performance, especially during large data transfers, backup operations, or heavy replication traffic.\n\nThe function queries Windows performance counters via CIM/WMI and displays bandwidth utilization alongside interface capacity (10Gb, 1Gb, 100Mb, etc.) to quickly identify saturated network links. Essential for troubleshooting connectivity issues, monitoring backup network performance, or validating network capacity before major data migration operations.\n\nRequires Local Admin rights on destination computer(s).", "Links": "https://dbatools.io/Get-DbaNetworkActivity", "Synopsis": "Retrieves real-time network traffic statistics for all network interfaces on SQL Server host computers.", "Availability": "Windows only", "Params": [ [ "ComputerName", "Specifies the computer names or SQL Server instances to monitor network activity.\r\nFunction extracts the computer name from full instance names and resolves them to fully qualified domain names.\r\nDefaults to the local computer when not specified.", "cn,host,Server", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Credential object used to connect to the computer as a different user.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Certificate", "Encryption", "Security" ], "CommandName": "Get-DbaNetworkCertificate", "Name": "Get-DbaNetworkCertificate", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaNetworkCertificate [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance that has a certificate configured for network encryption. Instances without certificates are filtered out and will not appear in the results.\nProperties:\r\n- ComputerName: The name of the computer hosting the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance format)\r\n- VSName: Virtual Server Name if applicable (for clustered instances)\r\n- ServiceAccount: The Windows service account running SQL Server\r\n- ForceEncryption: Boolean indicating if encryption is forced for all connections\r\n- FriendlyName: Human-readable certificate name from the certificate store\r\n- DnsNameList: Array of DNS names in the certificate\u0027s Subject Alternative Names\r\n- Thumbprint: SHA-1 hash thumbprint of the certificate\r\n- Generated: DateTime when the certificate becomes valid (NotBefore)\r\n- Expires: DateTime when the certificate expires (NotAfter)\r\n- IssuedTo: Certificate subject (who it was issued to)\r\n- IssuedBy: Certificate issuer name\r\n- Certificate: The full X509Certificate2 object with complete certificate information", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaNetworkCertificate -SqlInstance sql2016\nGets computer certificate for the standard instance on sql2016 that is being used for SQL Server network encryption\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaNetworkCertificate -SqlInstance server1\\sql2017\nGets computer certificate for the named instance sql2017 on server1 that is being used for SQL Server network encryption", "Description": "Retrieves the specific computer certificate that SQL Server is configured to use for network encryption and SSL connections. This shows you which certificate from the local certificate store is actively being used by the SQL Server instance for encrypting client connections. Only returns instances that actually have a certificate configured - instances without certificates won\u0027t appear in the results. Useful for auditing SSL configurations, troubleshooting encrypted connection issues, and verifying certificate assignments across multiple instances.", "Links": "https://dbatools.io/Get-DbaNetworkCertificate", "Synopsis": "Retrieves the certificate currently configured for SQL Server network encryption.", "Availability": "Windows only", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. Defaults to standard instance on localhost. If target is a cluster, you must specify the distinct nodes.", "ComputerName", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Alternate credential object to use for accessing the target computer(s).", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Connection", "SQLWMI" ], "CommandName": "Get-DbaNetworkConfiguration", "Name": "Get-DbaNetworkConfiguration", "Author": "Andreas Jordan (@JordanOrdix), ordix.de", "Syntax": "Get-DbaNetworkConfiguration [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-Credential] \u003cPSCredential\u003e] [[-OutputType] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nDefault (-OutputType Full) returns a PSCustomObject with the following properties:\r\n- ComputerName: Computer name of the SQL Server instance\r\n- InstanceName: SQL Server instance name\r\n- SqlInstance: Full SQL Server instance name (computer\\instance format)\r\n- SharedMemoryEnabled: Boolean indicating if Shared Memory protocol is enabled\r\n- NamedPipesEnabled: Boolean indicating if Named Pipes protocol is enabled\r\n- TcpIpEnabled: Boolean indicating if TCP/IP protocol is enabled\r\n- TcpIpProperties: Nested object containing Enabled, KeepAlive, and ListenAll properties for TCP/IP configuration\r\n- TcpIpAddresses: Array of objects representing IP address configurations with properties like Name, Active, Enabled, IpAddress, TcpDynamicPorts, and TcpPort\r\n- Certificate: Nested object containing SSL certificate information (FriendlyName, DnsNameList, Thumbprint, Generated, Expires, IssuedTo, IssuedBy, Certificate object)\r\n- SuitableCertificate: Array of certificates from the local machine store that are suitable for SQL Server encryption based on key usage, signature algorithm, validity, and DNS names\r\n- Advanced: Nested object containing advanced settings (ForceEncryption, HideInstance, AcceptedSPNs, ExtendedProtection)\nWhen -OutputType ServerProtocols is specified:\r\n- ComputerName: Computer name of the SQL Server instance\r\n- InstanceName: SQL Server instance name\r\n- SqlInstance: Full SQL Server instance name (computer\\instance format)\r\n- SharedMemoryEnabled: Boolean indicating if Shared Memory protocol is enabled\r\n- NamedPipesEnabled: Boolean indicating if Named Pipes protocol is enabled\r\n- TcpIpEnabled: Boolean indicating if TCP/IP protocol is enabled\nWhen -OutputType TcpIpProperties is specified:\r\n- ComputerName: Computer name of the SQL Server instance\r\n- InstanceName: SQL Server instance name\r\n- SqlInstance: Full SQL Server instance name (computer\\instance format)\r\n- Enabled: Value indicating if TCP/IP protocol is enabled\r\n- KeepAlive: TCP KeepAlive timeout setting value\r\n- ListenAll: Value indicating if instance listens on all IP addresses\nWhen -OutputType TcpIpAddresses is specified:\r\nIf ListenAll is True, returns one object for IPAll:\r\n- ComputerName: Computer name of the SQL Server instance\r\n- InstanceName: SQL Server instance name\r\n- SqlInstance: Full SQL Server instance name (computer\\instance format)\r\n- Name: IP configuration name (IPAll)\r\n- TcpDynamicPorts: Dynamic port configuration (empty or port number)\r\n- TcpPort: Static port number configuration\nIf ListenAll is False, returns one object per configured IP address:\r\n- ComputerName: Computer name of the SQL Server instance\r\n- InstanceName: SQL Server instance name\r\n- SqlInstance: Full SQL Server instance name (computer\\instance format)\r\n- Name: IP configuration name (e.g., IP1, IP2, IPV6)\r\n- Active: Value indicating if this IP configuration is active\r\n- Enabled: Value indicating if this IP configuration is enabled\r\n- IpAddress: The IP address (IPv4 or IPv6)\r\n- TcpDynamicPorts: Dynamic port configuration (empty or port number)\r\n- TcpPort: Static port number configuration\nWhen -OutputType Certificate is specified:\r\n- ComputerName: Computer name of the SQL Server instance\r\n- InstanceName: SQL Server instance name\r\n- SqlInstance: Full SQL Server instance name (computer\\instance format)\r\n- VSName: Virtual Server Name (if applicable; omitted if not present)\r\n- ServiceAccount: Service account running SQL Server\r\n- ForceEncryption: Boolean indicating if encryption is forced for all connections\r\n- FriendlyName: Human-readable certificate name\r\n- DnsNameList: Array of DNS names in the certificate\u0027s Subject Alternative Names\r\n- Thumbprint: SHA-1 hash thumbprint of the certificate\r\n- Generated: DateTime when the certificate becomes valid (NotBefore)\r\n- Expires: DateTime when the certificate expires (NotAfter)\r\n- IssuedTo: Certificate subject (who it was issued to)\r\n- IssuedBy: Certificate issuer name\r\n- Certificate: The full X509Certificate2 object with complete certificate information", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaNetworkConfiguration -SqlInstance sqlserver2014a\nReturns the network configuration for the default instance on sqlserver2014a.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaNetworkConfiguration -SqlInstance winserver\\sqlexpress, sql2016 -OutputType ServerProtocols\nReturns information about the server protocols for the sqlexpress on winserver and the default instance on sql2016.", "Description": "Collects comprehensive network configuration details for SQL Server instances, providing the same information visible in SQL Server Configuration Manager but in a scriptable PowerShell format. This function is essential for network connectivity troubleshooting, security audits, and compliance reporting across multiple SQL Server environments.\n\nThe function retrieves protocol status for Shared Memory, Named Pipes, and TCP/IP, along with detailed TCP/IP properties including port configurations, IP address bindings, and dynamic port settings. It also extracts SSL certificate information, encryption settings, and advanced security properties like SPNs and extended protection settings.\n\nSince the function accesses SQL WMI and Windows registry data, it uses PowerShell remoting to execute on the target machine, requiring appropriate permissions on both the local and remote systems.\n\nFor a detailed explanation of the different properties see the documentation at:\nhttps://docs.microsoft.com/en-us/sql/tools/configuration-manager/sql-server-network-configuration", "Links": "https://dbatools.io/Get-DbaNetworkConfiguration", "Synopsis": "Retrieves SQL Server network protocols, TCP/IP settings, and SSL certificate configuration from SQL Server Configuration Manager", "Availability": "Windows only", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "Credential", "Credential object used to connect to the Computer as a different user.", "", false, "false", "", "" ], [ "OutputType", "Controls which network configuration details are returned from SQL Server Configuration Manager.\r\nUse this to focus on specific troubleshooting areas or reduce output when checking multiple instances.\r\nValid options: Full, ServerProtocols, TcpIpProperties, TcpIpAddresses, Certificate (defaults to Full).\nFull provides complete network configuration including all protocols, TCP/IP settings, IP bindings, and SSL certificate details.\r\nServerProtocols shows only whether Shared Memory, Named Pipes, and TCP/IP protocols are enabled.\r\nTcpIpProperties returns TCP/IP protocol settings like KeepAlive timeout and whether the instance listens on all IP addresses.\r\nTcpIpAddresses displays port configurations and IP address bindings for connection troubleshooting.\r\nCertificate outputs SSL certificate information and encryption enforcement settings for security audits.", "", false, "false", "Full", "Full,ServerProtocols,TcpIpProperties,TcpIpAddresses,Certificate" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Certificate", "Encryption", "Security", "Network" ], "CommandName": "Get-DbaNetworkEncryption", "Name": "Get-DbaNetworkEncryption", "Author": "the dbatools team + Claude", "Syntax": "Get-DbaNetworkEncryption [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance that successfully presents a TLS certificate.\nProperties:\r\n- ComputerName: The hostname of the SQL Server\r\n- InstanceName: The SQL Server instance name (MSSQLSERVER for default)\r\n- SqlInstance: The full SQL Server instance identifier\r\n- Subject: The certificate subject (Common Name)\r\n- Issuer: The certificate issuer\r\n- Thumbprint: SHA-1 hash thumbprint of the certificate\r\n- NotBefore: DateTime when the certificate becomes valid\r\n- Expires: DateTime when the certificate expires\r\n- DnsNameList: Array of DNS names from the Subject Alternative Names extension\r\n- SerialNumber: Certificate serial number\r\n- Certificate: The full X509Certificate2 object", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaNetworkEncryption -SqlInstance sql2016\nRetrieves the TLS certificate presented by the default SQL Server instance on sql2016.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaNetworkEncryption -SqlInstance sql2016\\sqlexpress\nRetrieves the TLS certificate presented by the named instance sqlexpress on sql2016.\r\nQueries the SQL Browser service to determine the port.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaNetworkEncryption -SqlInstance sql2016, sql2017, sql2019 | Select-Object SqlInstance, Subject, Expires, Thumbprint\nRetrieves certificates from multiple SQL Server instances and shows key certificate details.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$servers | Get-DbaNetworkEncryption | Where-Object { $_.Expires -lt (Get-Date).AddDays(30) }\nFinds SQL Server instances whose TLS certificates expire within the next 30 days.", "Description": "Connects directly to a SQL Server instance\u0027s TCP port and retrieves the TLS/SSL certificate\nthat the server presents during the TLS handshake. This does not require Windows host access\nor WinRM - it works purely over the network like a client connecting to SQL Server.\n\nThis complements Get-DbaNetworkCertificate, which reads the configured certificate from the\nWindows registry (requires WinRM). This command instead shows what certificate is actually\nbeing presented to clients over the network, without requiring any host-level access.\n\nFor named instances, the SQL Browser service is queried on UDP port 1434 to determine the\nTCP port number. For default instances, port 1433 is used unless overridden.", "Links": "https://dbatools.io/Get-DbaNetworkEncryption", "Synopsis": "Retrieves the TLS/SSL certificate presented by a SQL Server instance over the network.", "Availability": "Windows only", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. Accepts pipeline input.", "", true, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "General", "OLEDB" ], "CommandName": "Get-DbaOleDbProvider", "Name": "Get-DbaOleDbProvider", "Author": "Chrissy LeMaire (@cl)", "Syntax": "Get-DbaOleDbProvider [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Provider] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.OleDbProviderSettings\nReturns one OleDbProviderSettings object per OLE DB provider configured on the SQL Server instance.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: Computer name of the SQL Server instance\r\n- InstanceName: SQL Server instance name\r\n- SqlInstance: Full SQL Server instance name (computer\\instance format)\r\n- Name: OLE DB provider name (e.g., SQLNCLI11, MSDASQL, SSISOLEDB)\r\n- Description: Human-readable description of the provider\r\n- AllowInProcess: Boolean indicating if the provider is allowed to run in-process with SQL Server\r\n- DisallowAdHocAccess: Boolean indicating if ad hoc access (OPENROWSET, OPENDATASOURCE) is disallowed\r\n- DynamicParameters: Boolean indicating if the provider supports dynamic parameters\r\n- IndexAsAccessPath: Boolean indicating if the provider supports indexes as access paths\r\n- LevelZeroOnly: Boolean indicating if only level zero (table-level) operations are allowed\r\n- NestedQueries: Boolean indicating if the provider supports nested queries\r\n- NonTransactedUpdates: Boolean indicating if the provider supports non-transacted updates\nAdditional properties available (from SMO OleDbProviderSettings object):\r\n- Parent: Reference to the parent Server object\r\n- Urn: The Uniform Resource Name of the provider object\r\n- Properties: Collection of property objects\r\n- State: Current state of the SMO object (Existing, Creating, Deleting, etc.)\r\n- Uid: Unique identifier for the provider setting\nAll properties from the base SMO OleDbProviderSettings object are accessible using Select-Object * even though only the default properties are displayed without it.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaOleDbProvider -SqlInstance SqlBox1\\Instance2\nReturns a list of all OleDb providers on SqlBox1\\Instance2\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaOleDbProvider -SqlInstance SqlBox1\\Instance2 -Provider SSISOLEDB\nReturns the SSISOLEDB provider on SqlBox1\\Instance2", "Description": "Returns the OLE DB providers that SQL Server knows about and can use for external data connections like linked servers, distributed queries, and OPENROWSET operations. This is essential for auditing your server\u0027s connectivity capabilities and troubleshooting linked server connection issues. The function shows provider details including security settings like AllowInProcess and DisallowAdHocAccess, which control how SQL Server can use each provider. Use this when setting up linked servers or diagnosing why certain external data sources aren\u0027t accessible.", "Links": "https://dbatools.io/Get-DbaOleDbProvider", "Synopsis": "Retrieves OLE DB provider configurations registered with SQL Server for linked servers and distributed queries", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Provider", "Filters results to specific OLE DB provider names. Accepts an array of provider names for targeting multiple providers.\r\nUse this when you need to check configuration for specific providers like SQLNCLI11 or MSDASQL instead of listing all available providers.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Diagnostic", "Process", "Session", "ActivityMonitor" ], "CommandName": "Get-DbaOpenTransaction", "Name": "Get-DbaOpenTransaction", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaOpenTransaction [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.Management.Automation.PSCustomObject\nReturns one object per open transaction found on the specified instance(s). If no open transactions exist, nothing is returned.\nProperties:\r\n- ComputerName: The name of the computer hosting the SQL Server instance\r\n- InstanceName: The SQL Server instance name (defaults to \u0027MSSQLSERVER\u0027 for default instances)\r\n- SqlInstance: The full SQL Server instance name as registered on the server\r\n- Spid: The session ID (process ID) of the session holding the open transaction\r\n- Login: The login name associated with the session\r\n- Database: The name of the database in which the transaction is open\r\n- BeginTime: DateTime when the transaction began\r\n- LogBytesUsed: Number of bytes of transaction log space currently used by this transaction\r\n- LogBytesReserved: Number of bytes of transaction log space reserved by this transaction\r\n- LastQuery: The text of the most recently executed SQL command in the session\r\n- LastPlan: The execution plan XML for the most recently executed query (can be NULL if not available)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaOpenTransaction -SqlInstance sqlserver2014a\nReturns open transactions for sqlserver2014a\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaOpenTransaction -SqlInstance sqlserver2014a -SqlCredential sqladmin\nLogs into sqlserver2014a using the login \"sqladmin\"", "Description": "Queries SQL Server dynamic management views to identify open transactions that may be causing blocking, consuming transaction log space, or impacting performance. Returns comprehensive details including session information, database context, transaction duration, log space usage, and the last executed query with its execution plan.\n\nThis is particularly useful when troubleshooting blocking issues, investigating long-running transactions, or monitoring transaction log growth. The function helps DBAs quickly identify which sessions are holding transactions open and assess their potential impact on system performance.\n\nThis command is based on the open transaction monitoring script published by Paul Randal.\nReference: https://www.sqlskills.com/blogs/paul/script-open-transactions-with-text-and-plans/", "Links": "https://dbatools.io/Get-DbaOpenTransaction", "Synopsis": "Retrieves detailed information about open database transactions across SQL Server instances.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The SQL Server instance", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Management", "OS", "OperatingSystem" ], "CommandName": "Get-DbaOperatingSystem", "Name": "Get-DbaOperatingSystem", "Author": "Shawn Melton (@wsmelton), wsmelton.github.io", "Syntax": "Get-DbaOperatingSystem [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per computer containing comprehensive Windows operating system details.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The name of the computer\r\n- Manufacturer: The manufacturer of the computer hardware (e.g., Dell, HP, VMware)\r\n- Organization: The organization assigned to the computer\r\n- Architecture: The processor architecture (x64 or x86)\r\n- Version: The Windows version identifier\r\n- OSVersion: The friendly operating system version name (e.g., Windows Server 2019 Standard)\r\n- LastBootTime: DateTime of the most recent system boot\r\n- LocalDateTime: Current DateTime on the system\r\n- PowerShellVersion: The installed PowerShell version (e.g., 5.1)\r\n- TimeZone: The current time zone of the system\r\n- TotalVisibleMemory: Total physical RAM available (dbasize object with unit conversion)\r\n- ActivePowerPlan: The active Windows power plan (e.g., High Performance)\r\n- LanguageNative: The native name of the configured OS language\nAdditional properties available (use Select-Object *):\r\n- Build: The Windows build number\r\n- SPVersion: Service Pack version number\r\n- InstallDate: DateTime when the operating system was installed\r\n- BootDevice: The device from which the system boots\r\n- SystemDevice: The device containing the operating system files\r\n- SystemDrive: The drive letter of the system drive\r\n- WindowsDirectory: The full path to the Windows directory\r\n- PagingFileSize: Current paging file size in KB\r\n- FreePhysicalMemory: Currently available physical RAM (dbasize object)\r\n- TotalVirtualMemory: Total virtual memory available (dbasize object)\r\n- FreeVirtualMemory: Currently available virtual memory (dbasize object)\r\n- Status: Current system status\r\n- Language: The Display name of the configured OS language\r\n- LanguageId: The LCID (Locale ID) of the OS language\r\n- LanguageKeyboardLayoutId: The keyboard layout ID\r\n- LanguageTwoLetter: Two-letter ISO language code\r\n- LanguageThreeLetter: Three-letter ISO language code\r\n- LanguageAlias: Language alias name\r\n- CodeSet: The code set character encoding\r\n- CountryCode: The country code\r\n- Locale: The locale identifier\r\n- IsWsfc: Boolean indicating if Windows Server Failover Clustering service is installed", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaOperatingSystem\nReturns information about the local computer\u0027s operating system\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaOperatingSystem -ComputerName sql2016\nReturns information about the sql2016\u0027s operating system\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$wincred = Get-Credential ad\\sqladmin\nPS C:\\\u003e \u0027sql2016\u0027, \u0027sql2017\u0027 | Get-DbaOperatingSystem -Credential $wincred\nReturns information about the sql2016 and sql2017 operating systems using alternative Windows credentials\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-Content .\\servers.txt | Get-DbaOperatingSystem\nReturns information about all the servers operating system that are stored in the file. Every line in the file can only contain one hostname for a server.", "Description": "Collects detailed operating system information from local or remote Windows computers hosting SQL Server instances. Returns comprehensive system details including OS version, memory configuration, power plans, time zones, and Windows Server Failover Clustering status. This information is essential for SQL Server environment assessments, capacity planning, and troubleshooting performance issues that may be related to the underlying OS configuration.", "Links": "https://dbatools.io/Get-DbaOperatingSystem", "Synopsis": "Retrieves comprehensive Windows operating system details from SQL Server host machines.", "Availability": "Windows only", "Params": [ [ "ComputerName", "Specifies the computer names of SQL Server host machines to query for operating system information. Accepts multiple computer names, IP addresses, or SQL Server instance names.\r\nUse this when you need to collect OS details from remote servers for environment assessments, capacity planning, or troubleshooting. Defaults to the local computer if not specified.", "cn,host,Server", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Alternate credential object to use for accessing the target computer(s).", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Management", "OS", "PageFile" ], "CommandName": "Get-DbaPageFileSetting", "Name": "Get-DbaPageFileSetting", "Author": "Klaas Vandenberghe (@PowerDBAKlaas)", "Syntax": "Get-DbaPageFileSetting [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Dataplat.Dbatools.Computer.PageFileSetting\nReturns one object per page file on the target computer, unless page files are automatically managed by Windows, in which case one object is returned with all file-specific properties set to null.\nProperties:\r\n- ComputerName: The name of the target computer\r\n- AutoPageFile: Boolean indicating if page file is automatically managed by Windows\r\n- FileName: Logical name of the page file (null for auto-managed)\r\n- Status: Status of the page file from WMI (typically \"OK\", null for auto-managed)\r\n- SystemManaged: Boolean indicating if both InitialSize and MaximumSize are zero (null for auto-managed)\r\n- LastModified: DateTime of last page file modification (null for auto-managed)\r\n- LastAccessed: DateTime of last page file access (null for auto-managed)\r\n- AllocatedBaseSize: Current allocated size in megabytes between Initial and Maximum sizes (null for auto-managed)\r\n- InitialSize: Initial page file size in megabytes (null for auto-managed)\r\n- MaximumSize: Maximum page file size in megabytes (null for auto-managed)\r\n- PeakUsage: Peak page file usage in megabytes since system startup (null for auto-managed)\r\n- CurrentUsage: Current page file usage in megabytes (null for auto-managed)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaPageFileSetting -ComputerName ServerA,ServerB\nReturns a custom object displaying ComputerName, AutoPageFile, FileName, Status, LastModified, LastAccessed, AllocatedBaseSize, InitialSize, MaximumSize, PeakUsage, CurrentUsage for ServerA and \r\nServerB\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027ServerA\u0027 | Get-DbaPageFileSetting\nReturns a custom object displaying ComputerName, AutoPageFile, FileName, Status, LastModified, LastAccessed, AllocatedBaseSize, InitialSize, MaximumSize, PeakUsage, CurrentUsage for ServerA", "Description": "This command uses CIM to retrieve detailed Windows page file configuration from SQL Server host computers. Page file settings directly impact SQL Server performance during memory pressure scenarios, making this essential for capacity planning and troubleshooting performance issues.\n\nThe function returns comprehensive details including current usage, peak usage, initial and maximum sizes, and whether page files are automatically managed by Windows. This information helps DBAs identify potential memory bottlenecks and validate that page file configurations align with SQL Server best practices.\n\nNote that this may require local administrator privileges for the relevant computers.", "Links": "https://dbatools.io/Get-DbaPageFileSetting", "Synopsis": "Retrieves Windows page file configuration from SQL Server host computers for performance analysis.", "Availability": "Windows only", "Params": [ [ "ComputerName", "Specifies the target SQL Server host computers to retrieve page file settings from. Accepts computer names, IP addresses, or SQL Server instance names.\r\nUse this to analyze page file configurations across your SQL Server infrastructure for capacity planning and performance troubleshooting.\r\nDefaults to the local computer if not specified.", "", false, "true (ByValue, ByPropertyName)", "$env:COMPUTERNAME", "" ], [ "Credential", "Credential object used to connect to the Computer as a different user", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Policy", "PolicyBasedManagement", "PBM" ], "CommandName": "Get-DbaPbmCategory", "Name": "Get-DbaPbmCategory", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaPbmCategory [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Category] \u003cString[]\u003e] [[-InputObject] \u003cPSObject[]\u003e] [-ExcludeSystemObject] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Sdk.Sfc.ISfcInstance\nReturns one policy category object per category found on the target PBM store(s). Each category object includes connection context properties and policy category metadata.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Id: The unique identifier for the policy category\r\n- Name: The name of the policy category\r\n- MandateDatabaseSubscriptions: Boolean indicating if databases must be subscribed to this category for automatic policy evaluation", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaPbmCategory -SqlInstance sql2016\nReturns all policy categories from the sql2016 PBM server\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaPbmCategory -SqlInstance sql2016 -SqlCredential $cred\nUses a credential $cred to connect and return all policy categories from the sql2016 PBM server", "Description": "Retrieves all policy categories configured in SQL Server\u0027s Policy-Based Management (PBM) feature. Policy categories help organize and group related policies for easier management and selective enforcement across database environments. This function allows DBAs to inventory existing categories, audit category assignments, and understand which categories mandate database subscriptions for automatic policy evaluation.", "Links": "https://dbatools.io/Get-DbaPbmCategory", "Synopsis": "Retrieves Policy-Based Management categories from SQL Server instances for governance and compliance management.", "Availability": "Windows only", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Category", "Filters results to only show specific policy categories by name. Accepts multiple category names for targeted retrieval.\r\nUse this when you need to check specific categories rather than retrieving all configured PBM categories.", "", false, "false", "", "" ], [ "InputObject", "Accepts Policy-Based Management store objects from Get-DbaPbmStore for processing categories from specific stores.\r\nUse this when you need to work with categories from a pre-filtered set of PBM stores or when chaining multiple PBM commands together.", "", false, "true (ByValue)", "", "" ], [ "ExcludeSystemObject", "Excludes built-in system policy categories from the results, showing only user-created categories.\r\nUse this when you want to focus on custom categories that you or your team have created, filtering out SQL Server\u0027s default categories.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Policy", "PolicyBasedManagement", "PBM" ], "CommandName": "Get-DbaPbmCategorySubscription", "Name": "Get-DbaPbmCategorySubscription", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaPbmCategorySubscription [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-InputObject] \u003cPSObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Dmf.PolicyCategorySubscription\nReturns one subscription object for each database or object subscribed to a policy category. These subscriptions define which objects are subject to automatic policy evaluation for specific policy \r\ncategories.\nDefault display properties (via Select-DefaultView, excluding Properties, Urn, and Parent):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- PolicyCategory: The name of the policy category this subscription applies to\r\n- Target: The target object (database or other SQL Server object) subscribed to this category\r\n- TargetType: The type of the target object being subscribed\r\n- ID: Unique identifier for the subscription\r\n- State: Current state of the subscription object (Existing, Creating, Pending, etc.)\r\n- IdentityKey: Identity key of the subscription object\r\n- Metadata: Metadata information for the subscription\r\n- KeyChain: Identity path of the subscription object\nAdditional properties available via Select-Object *:\r\n- Properties: Properties collection for the subscription\r\n- Urn: Uniform Resource Name (URN) for the subscription object\r\n- Parent: Reference to the parent PolicyStore object", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaPbmCategorySubscription -SqlInstance sql2016\nReturns all policy category subscriptions from the sql2016 PBM server\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaPbmCategorySubscription -SqlInstance sql2016 -SqlCredential $cred\nUses a credential $cred to connect and return all policy category subscriptions from the sql2016 PBM server", "Description": "Retrieves all database subscriptions to policy categories from SQL Server\u0027s Policy-Based Management feature. These subscriptions determine which databases are subject to automatic policy evaluation for specific policy categories. When a database subscribes to a category (either voluntarily or through mandatory subscription), all policies in that category will be automatically evaluated against the database. This is essential for auditing policy compliance, troubleshooting evaluation failures, and understanding which databases are governed by which policy sets.", "Links": "https://dbatools.io/Get-DbaPbmCategorySubscription", "Synopsis": "Retrieves database subscriptions to Policy-Based Management categories that control automatic policy evaluation.", "Availability": "Windows only", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "InputObject", "Accepts Policy-Based Management store objects from Get-DbaPbmStore for pipeline processing.\r\nUse this when you need to query category subscriptions from an already retrieved PBM store object, improving performance when working with multiple PBM operations on the same instance.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Policy", "PolicyBasedManagement", "PBM" ], "CommandName": "Get-DbaPbmCondition", "Name": "Get-DbaPbmCondition", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaPbmCondition [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Condition] \u003cString[]\u003e] [[-InputObject] \u003cPSObject[]\u003e] [-IncludeSystemObject] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Dmf.Condition\nReturns one condition object for each policy condition found on the specified PBM store. Conditions define the rules and criteria used to evaluate database objects for compliance with policies.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Id: Unique identifier for the condition\r\n- Name: The name of the condition\r\n- CreateDate: DateTime when the condition was created\r\n- CreatedBy: User who created the condition\r\n- DateModified: DateTime when the condition was last modified\r\n- Description: Description of the condition\r\n- ExpressionNode: The expression tree that defines the condition logic\r\n- Facet: The facet that the condition applies to (management area such as Database, Server, Table, etc.)\r\n- HasScript: Boolean indicating if the condition contains a dynamic script expression\r\n- IsSystemObject: Boolean indicating if this is a system-provided condition or user-created\r\n- ModifiedBy: User who last modified the condition\nAdditional properties available via Select-Object *:\r\n- IsEnumerable: Boolean indicating if the condition can be used as a target set level filter\r\n- Parent: Reference to the parent PolicyStore object\r\n- State: Current state of the condition object (Existing, Creating, Pending, etc.)\r\n- Urn: Uniform Resource Name (URN) for the condition object\r\n- IdentityKey: Identity key of the condition object\r\n- Metadata: Metadata information\r\n- KeyChain: Identity path of the condition object\r\n- Properties: Properties collection for the condition", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaPbmCondition -SqlInstance sql2016\nReturns all conditions from the sql2016 PBM server\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaPbmCondition -SqlInstance sql2016 -SqlCredential $cred\nUses a credential $cred to connect and return all conditions from the sql2016 PBM server", "Description": "Retrieves Policy-Based Management (PBM) conditions from SQL Server instances, which define the rules and criteria used to evaluate database objects for compliance. These conditions form the building blocks of PBM policies and specify what to check (like database settings, table properties, or server configurations) and what values are acceptable. Use this to audit existing conditions, troubleshoot policy failures, or inventory your compliance framework across multiple instances.", "Links": "https://dbatools.io/Get-DbaPbmCondition", "Synopsis": "Retrieves Policy-Based Management conditions from SQL Server instances for compliance monitoring and policy evaluation.", "Availability": "Windows only", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Condition", "Filters results to only return conditions that match the specified names. Accepts multiple condition names and supports wildcards.\r\nUse this when you need to examine specific PBM conditions rather than retrieving all conditions from the instance.", "", false, "false", "", "" ], [ "InputObject", "Accepts Policy-Based Management store objects from Get-DbaPbmStore via pipeline input. This allows you to chain commands and work with multiple PBM stores efficiently.\r\nUse this when processing conditions from multiple instances or when working with previously retrieved PBM store objects.", "", false, "true (ByValue)", "", "" ], [ "IncludeSystemObject", "Includes built-in system conditions in the results, which are filtered out by default. System conditions are predefined by SQL Server for common compliance scenarios.\r\nUse this when you need to see all available conditions including Microsoft\u0027s built-in templates for policy creation.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Policy", "PolicyBasedManagement", "PBM" ], "CommandName": "Get-DbaPbmObjectSet", "Name": "Get-DbaPbmObjectSet", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaPbmObjectSet [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-ObjectSet] \u003cString[]\u003e] [[-InputObject] \u003cPSObject[]\u003e] [-IncludeSystemObject] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Dmf.ObjectSet\nReturns one ObjectSet object per object set found on the specified SQL Server instance(s).\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- ID: Unique identifier for the object set\r\n- Name: Name of the object set\r\n- Facet: The facet that this object set targets (e.g., Server, Database, Table)\r\n- TargetSets: Collection of target sets that define the objects included in this set\r\n- IsSystemObject: Boolean indicating if this is a Microsoft system object set\nAdditional properties available (from SMO ObjectSet object):\r\n- Parent: Reference to the parent PolicyStore object\r\n- IdentityKey: The identity key for the object\r\n- Urn: The Uniform Resource Name\r\n- State: The current state of the SMO object (Existing, Creating, Pending, Dropping, etc.)\r\n- Metadata: The object metadata\nAll properties from the base SMO ObjectSet object are accessible using Select-Object * even though only default properties are displayed by default.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaPbmObjectSet -SqlInstance sql2016\nReturns all object sets from the sql2016 PBM instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaPbmObjectSet -SqlInstance sql2016 -SqlCredential $cred\nUses a credential $cred to connect and return all object sets from the sql2016 PBM instance", "Description": "Retrieves object sets from SQL Server\u0027s Policy-Based Management (PBM) feature, which define collections of SQL Server objects that policies can target for compliance monitoring. Object sets group related database objects like tables, stored procedures, or views based on specific criteria, allowing you to apply policies consistently across similar objects. This is essential for DBAs implementing standardized configurations and compliance rules across multiple databases and instances.", "Links": "https://dbatools.io/Get-DbaPbmObjectSet", "Synopsis": "Retrieves Policy-Based Management object sets from SQL Server instances", "Availability": "Windows only", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "ObjectSet", "Specifies the name(s) of specific Policy-Based Management object sets to retrieve. Accepts multiple values and supports wildcards.\r\nUse this when you need to examine particular object sets rather than retrieving all available sets from the instance.", "", false, "false", "", "" ], [ "InputObject", "Accepts Policy-Based Management store objects from Get-DbaPbmStore via pipeline input for processing multiple stores.\r\nUse this when you need to process object sets from multiple SQL Server instances or when chaining PBM commands together.", "", false, "true (ByValue)", "", "" ], [ "IncludeSystemObject", "Includes SQL Server system object sets in the results, which are excluded by default to focus on user-defined sets.\r\nUse this when you need to audit or examine Microsoft\u0027s built-in Policy-Based Management object sets for compliance or educational purposes.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Policy", "PolicyBasedManagement", "PBM" ], "CommandName": "Get-DbaPbmPolicy", "Name": "Get-DbaPbmPolicy", "Author": "Stephen Bennett, sqlnotesfromtheunderground.wordpress.com", "Syntax": "Get-DbaPbmPolicy [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Policy] \u003cString[]\u003e] [[-Category] \u003cString[]\u003e] [[-InputObject] \u003cPSObject[]\u003e] [-IncludeSystemObject] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Dmf.Policy\nReturns one Policy object per policy found on the specified SQL Server instance(s).\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- ID: Unique identifier for the policy\r\n- Name: Name of the policy\r\n- Enabled: Boolean indicating if the policy is enabled\r\n- Description: Text description of the policy\u0027s purpose\r\n- PolicyCategory: The category or group the policy belongs to\r\n- AutomatedPolicyEvaluationMode: The mode used for automated evaluation (On Demand, On Schedule, On Change, None)\r\n- Condition: The condition that the policy enforces\r\n- CreateDate: DateTime when the policy was created\r\n- CreatedBy: User who created the policy\r\n- DateModified: DateTime when the policy was last modified\r\n- ModifiedBy: User who last modified the policy\r\n- IsSystemObject: Boolean indicating if this is a Microsoft system policy\r\n- ObjectSet: The object set targeted by this policy\r\n- RootCondition: The root condition evaluated by the policy\r\n- ScheduleUid: The schedule identifier if policy uses scheduled evaluation\nProperties excluded from default display (accessible with Select-Object *):\r\n- HelpText: Help documentation text for the policy\r\n- HelpLink: URL link to additional help documentation\r\n- Urn: The Uniform Resource Name\r\n- Properties: The SMO object properties collection\r\n- Metadata: The object metadata\r\n- Parent: Reference to parent PolicyStore object\r\n- IdentityKey: The identity key for the object\r\n- HasScript: Boolean indicating if policy conditions reference T-SQL or WQL scripts\r\n- PolicyEvaluationStarted: Indicates if evaluation has started\r\n- ConnectionProcessingStarted: Indicates if connection processing started\r\n- TargetProcessed: Indicates if targets have been processed\r\n- ConnectionProcessingFinished: Indicates if connection processing is complete\r\n- PolicyEvaluationFinished: Indicates if policy evaluation is complete\r\n- PropertyMetadataChanged: Indicates if metadata has changed\r\n- PropertyChanged: Indicates if properties have changed\nAll properties from the base SMO Policy object are accessible using Select-Object * even though only default properties are displayed by default.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaPbmPolicy -SqlInstance sql2016\nReturns all policies from sql2016 server\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaPbmPolicy -SqlInstance sql2016 -SqlCredential $cred\nUses a credential $cred to connect and return all policies from sql2016 instance\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaPbmPolicy -SqlInstance sql2016 -Category MorningCheck\nReturns all policies from sql2016 server that part of the PolicyCategory MorningCheck", "Description": "Retrieves all Policy-Based Management policies configured on SQL Server instances, allowing DBAs to audit compliance configurations and review policy settings across their environment. This function connects to the PBM store and returns policy details including categories, conditions, and evaluation modes. Use this when you need to document existing policies, troubleshoot policy evaluations, or verify compliance configurations without manually navigating through SQL Server Management Studio\u0027s Policy-Based Management node.", "Links": "https://dbatools.io/Get-DbaPbmPolicy", "Synopsis": "Retrieves Policy-Based Management policies from SQL Server instances for compliance auditing and configuration review.", "Availability": "Windows only", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.", "", false, "false", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Policy", "Specifies one or more policy names to retrieve, filtering the results to only those policies. Supports exact name matching for targeted policy retrieval.\r\nUse this when you need to examine specific policies rather than all policies on the instance.", "", false, "false", "", "" ], [ "Category", "Filters results to show only policies belonging to specific policy categories. Categories help organize policies by function or compliance framework.\r\nUse this to focus on policies related to specific areas like security, performance, or maintenance checks.", "", false, "false", "", "" ], [ "InputObject", "Accepts PBM store objects from Get-DbaPbmStore via pipeline, allowing efficient processing of multiple instances. Enables chaining PBM commands together.\r\nUse this when building complex PBM workflows or when you already have PBM store objects from previous commands.", "", false, "true (ByValue)", "", "" ], [ "IncludeSystemObject", "Includes Microsoft\u0027s built-in system policies in the results, which are excluded by default. System policies cover standard SQL Server best practices.\r\nUse this when you need to review or document all policies including Microsoft\u0027s predefined compliance policies.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Policy", "PolicyBasedManagement", "PBM" ], "CommandName": "Get-DbaPbmStore", "Name": "Get-DbaPbmStore", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaPbmStore [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.DMF.PolicyStore\nReturns one PolicyStore object per instance, which serves as the root container for managing Policy-Based Management (PBM) policies, conditions, and facets.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\nAll other SMO PolicyStore properties are available and can be accessed using Select-Object *. The following properties are excluded from the default view and should be accessed via Select-Object if \r\nneeded:\r\n- SqlStoreConnection: The underlying SQL Store connection object\r\n- ConnectionContext: The SQL connection context\r\n- Properties: The SMO object properties collection\r\n- Urn: The Uniform Resource Name of the store\r\n- Parent: The parent object reference\r\n- DomainInstanceName: The domain instance name\r\n- Metadata: Metadata information\r\n- IdentityKey: The identity key for the object\r\n- Name: The name property of the store object", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaPbmStore -SqlInstance sql2016\nReturn the policy store from the sql2016 instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaPbmStore -SqlInstance sql2016 -SqlCredential $cred\nUses a credential $cred to connect and return the policy store from the sql2016 instance", "Description": "Retrieves the Policy-Based Management (PBM) store object, which serves as the foundation for managing SQL Server policies, conditions, and categories. This store object is required for accessing and manipulating Policy-Based Management components programmatically. The function connects to the DMF (Declarative Management Framework) policy store and returns it with additional instance identification properties for easier scripting and automation.", "Links": "https://dbatools.io/Get-DbaPbmStore", "Synopsis": "Retrieves the Policy-Based Management store object from SQL Server instances.", "Availability": "Windows only", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Permissions", "Instance", "Database", "Security" ], "CommandName": "Get-DbaPermission", "Name": "Get-DbaPermission", "Author": "Klaas Vandenberghe (@PowerDBAKlaas)", "Syntax": "Get-DbaPermission [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-IncludeServerLevel] [-ExcludeSystemObjects] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.Data.DataRow\nReturns one object per permission found across the specified instances and databases. Each permission object represents either an explicit permission from sys.server_permissions or \r\nsys.database_permissions, or an implicit permission from fixed roles, schema owners, or the database owner (dbo).\nProperties:\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name (MSSQLSERVER for default instance)\r\n- SqlInstance: The full SQL Server instance name (computer\\instance format)\r\n- Database: The database name; empty string for server-level permissions\r\n- PermState: The permission state - \u0027GRANT\u0027, \u0027DENY\u0027, or \u0027REVOKE\u0027 (empty string for implicit permissions from roles)\r\n- PermissionName: The name of the permission (e.g., SELECT, CONTROL, CONNECT, ADMINISTER BULK OPERATIONS)\r\n- SecurableType: The type of securable being protected (e.g., DATABASE, OBJECT, SCHEMA, SERVER, ENDPOINT, AVAILABILITY GROUP, LOGIN)\r\n- Securable: The name or identifier of the securable being protected (e.g., database name, object name, schema name, server name, login name)\r\n- Grantee: The name of the principal (login, user, or role) that has the permission (server-level) or the user/role in the database (database-level)\r\n- GranteeType: The type of principal - \u0027LOGIN\u0027, \u0027USER\u0027, \u0027APPLICATION ROLE\u0027, \u0027ROLE\u0027, \u0027DATABASE OWNER (dbo user)\u0027, \u0027DATABASE OWNER (db_owner role)\u0027, \u0027SCHEMA OWNER\u0027, or fixed role type\r\n- RevokeStatement: T-SQL REVOKE statement that can be used to revoke this permission; empty string for implicit permissions\r\n- GrantStatement: T-SQL GRANT or GRANT WITH GRANT OPTION statement that can be used to grant this permission; empty string for implicit permissions and fixed role permissions\nOutput Conditions:\r\n- Server-level permissions: Only included when -IncludeServerLevel switch is specified; Database column is empty\r\n- Database-level permissions: Always included; one object per explicit permission from sys.database_permissions\r\n- Fixed role permissions: One object per built-in fixed role (db_owner, db_datareader, db_ddladmin, etc.); PermState is empty\r\n- Implicit CONTROL permissions: Included for dbo users, db_owner role members, and schema owners; PermState is empty\r\n- ExcludeSystemObjects: When specified, filters results to exclude permissions with major_id = 0 (system objects) in T-SQL WHERE clause", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaPermission -SqlInstance ServerA\\sql987\nReturns a custom object with Server name, Database name, permission state, permission type, grantee and securable.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaPermission -SqlInstance ServerA\\sql987 | Format-Table -AutoSize\nReturns a formatted table displaying Server, Database, permission state, permission type, grantee, granteetype, securable and securabletype.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaPermission -SqlInstance ServerA\\sql987 -ExcludeSystemObjects -IncludeServerLevel\nReturns a custom object with Server name, Database name, permission state, permission type, grantee and securable\r\nin all databases and on the server level, but not on system securables.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaPermission -SqlInstance sql2016 -Database master\nReturns a custom object with permissions for the master database.", "Description": "Retrieves comprehensive permission information from SQL Server instances and databases, including both explicit permissions and implicit permissions from fixed roles.\n\nThis function queries sys.server_permissions and sys.database_permissions to capture all granted, denied, and revoked permissions across server and database levels.\nPerfect for security audits, compliance reporting, troubleshooting access issues, and planning permission migrations between environments.\n\nThe output includes permission state (GRANT/DENY/REVOKE), permission type (SELECT, CONNECT, EXECUTE, etc.), grantee information, and the specific securable being protected.\nAlso captures implicit CONTROL permissions for dbo users, db_owner role members, and schema owners that aren\u0027t explicitly stored in system tables.\nEach result includes ready-to-use GRANT and REVOKE statements for easy permission replication or cleanup.\n\nPermissions link principals (logins, users, roles) to securables (servers, databases, schemas, objects).\nPrincipals exist at Windows, instance, and database levels, while securables exist at instance and database levels.\n\nSee https://msdn.microsoft.com/en-us/library/ms191291.aspx for more information about SQL Server permissions", "Links": "https://dbatools.io/Get-DbaPermission", "Synopsis": "Retrieves explicit and implicit permissions across SQL Server instances and databases for security auditing", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. Defaults to localhost.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to analyze for permissions. Accepts wildcards and multiple database names.\r\nWhen omitted, all accessible databases on the instance are processed, which is useful for comprehensive security audits.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific databases from permission analysis. Accepts wildcards and multiple database names.\r\nCommonly used to skip system databases like TempDB or exclude sensitive databases from security reports.", "", false, "false", "", "" ], [ "IncludeServerLevel", "Includes server-level permissions in the output, such as CONTROL SERVER, VIEW SERVER STATE, and fixed server roles like sysadmin.\r\nEssential for complete security audits as it captures instance-wide permissions that affect all databases.", "", false, "false", "False", "" ], [ "ExcludeSystemObjects", "Excludes permissions on system objects like system tables, views, and stored procedures from the output.\r\nUse this when focusing on user-created objects to reduce noise in permission reports and compliance audits.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Performance", "DataCollector", "PerfCounter" ], "CommandName": "Get-DbaPfAvailableCounter", "Name": "Get-DbaPfAvailableCounter", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaPfAvailableCounter [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-Pattern] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per available Windows performance counter found on the specified computers.\nDefault display properties:\r\n- ComputerName: The name of the computer where the counter is available\r\n- Name: The performance counter name\nAdditional properties available (via Select-Object *):\r\n- Credential: The PSCredential object used for connecting to the computer; useful for piping to other dbatools commands like Add-DbaPfDataCollectorCounter", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaPfAvailableCounter\nGets all available counters on the local machine.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaPfAvailableCounter -Pattern *sql*\nGets all counters matching sql on the local machine.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaPfAvailableCounter -ComputerName sql2017 -Pattern *sql*\nGets all counters matching sql on the remote server sql2017.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaPfAvailableCounter -Pattern *sql*\nGets all counters matching sql on the local machine.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaPfAvailableCounter -Pattern *sql* | Add-DbaPfDataCollectorCounter -CollectorSet \u0027Test Collector Set\u0027 -Collector DataCollector01\nAdds all counters matching \"sql\" to the DataCollector01 within the \u0027Test Collector Set\u0027 CollectorSet.", "Description": "Retrieves all Windows performance counters available on specified machines by reading directly from the registry for fast enumeration. This is essential when setting up SQL Server monitoring because you need to know which specific counters are available before configuring data collectors or performance monitoring solutions. The function uses a registry-based approach that\u0027s much faster than traditional Get-Counter methods, making it practical for discovering hundreds of available counters across multiple servers. When credentials are provided, they\u0027re included in the output for easy piping to other dbatools commands like Add-DbaPfDataCollectorCounter.\n\nThanks to Daniel Streefkerk for this super fast way of counters\nhttps://daniel.streefkerkonline.com/2016/02/18/use-powershell-to-list-all-windows-performance-counters-and-their-numeric-ids", "Links": "https://dbatools.io/Get-DbaPfAvailableCounter", "Synopsis": "Retrieves all Windows performance counters available on local or remote machines for monitoring setup.", "Availability": "Windows only", "Params": [ [ "ComputerName", "Specifies the target computers to query for available performance counters. Defaults to localhost.\r\nUse this when you need to discover counters on remote SQL Server instances or other servers in your environment before setting up monitoring.", "", false, "false", "$env:ComputerName", "" ], [ "Credential", "Allows you to login to servers using alternative credentials. To use:\n$scred = Get-Credential, then pass $scred object to the -Credential parameter.", "", false, "false", "", "" ], [ "Pattern", "Filters counter names using wildcard pattern matching (supports * and ? wildcards).\r\nUse this to find specific SQL Server counters like \"*sql*\" or \"*buffer*\" when you need to identify relevant performance metrics for monitoring setup.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Performance", "DataCollector", "PerfCounter" ], "CommandName": "Get-DbaPfDataCollector", "Name": "Get-DbaPfDataCollector", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaPfDataCollector [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-CollectorSet] \u003cString[]\u003e] [[-Collector] \u003cString[]\u003e] [[-InputObject] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per data collector found within the specified collector sets. Each object represents a single Performance Monitor data collector configuration.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The name of the computer where the collector set is configured\r\n- DataCollectorSet: The name of the parent data collector set containing this collector\r\n- Name: The logical name of the data collector within the collector set\r\n- DataCollectorType: The type of data collector (e.g., PerformanceCounterDataCollector)\r\n- DataSourceName: The name of the performance counter data source being collected\r\n- FileName: The base file name where performance counter data is written\r\n- FileNameFormat: Format specification for the output file naming (e.g., monddyy)\r\n- FileNameFormatPattern: The file naming pattern used for sequential file naming\r\n- LatestOutputLocation: The full path where the most recent collector output is stored\r\n- LogAppend: Boolean indicating if new data is appended to existing log files\r\n- LogCircular: Boolean indicating if the log uses circular buffering (overwrites when full)\r\n- LogFileFormat: The format of the log file (e.g., csv, binary, sql)\r\n- LogOverwrite: Boolean indicating if existing log data is overwritten\r\n- SampleInterval: The sampling interval in milliseconds between performance counter samples\r\n- SegmentMaxRecords: The maximum number of records per log segment\r\n- Counters: The collection of performance counters being collected by this collector\nAdditional properties available (not shown by default):\r\n- CounterDisplayNames: Display names for the performance counters\r\n- RemoteLatestOutputLocation: UNC path for accessing the latest output location remotely\r\n- DataCollectorSetXml: The raw XML configuration of the parent data collector set\r\n- CollectorXml: The raw XML configuration of this specific data collector\r\n- DataCollectorObject: Flag indicating this is a data collector object\r\n- Credential: The credential object used for remote access (if applicable)\nUse Select-Object * to access all properties available in the object.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollector\nGets all Collectors on localhost.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollector -ComputerName sql2017\nGets all Collectors on sql2017.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollector -ComputerName sql2017, sql2016 -Credential ad\\sqldba -CollectorSet \u0027System Correlation\u0027\nGets all Collectors for the \u0027System Correlation\u0027 CollectorSet on sql2017 and sql2016 using alternative credentials.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorSet -CollectorSet \u0027System Correlation\u0027 | Get-DbaPfDataCollector\nGets all Collectors for the \u0027System Correlation\u0027 CollectorSet.", "Description": "Retrieves detailed information about Windows Performance Monitor data collectors within collector sets, commonly used by DBAs to monitor SQL Server performance counters. This function parses the XML configuration of existing data collectors to show their settings, file locations, sample intervals, and the specific performance counters they collect.\n\nUse this when you need to audit existing performance monitoring setups, verify collector configurations, or identify which performance counters are being captured for SQL Server baseline analysis and troubleshooting. The function works across multiple computers and integrates with Get-DbaPfDataCollectorSet for filtering specific collector sets.", "Links": "https://dbatools.io/Get-DbaPfDataCollector", "Synopsis": "Retrieves Windows Performance Monitor data collectors and their configuration details from local or remote computers.", "Availability": "Windows only", "Params": [ [ "ComputerName", "Specifies the target computer(s) to retrieve performance data collectors from. Defaults to localhost.\r\nUse this to monitor performance collectors across multiple SQL Server environments or remote systems where SQL Server performance monitoring is configured.", "", false, "false", "$env:COMPUTERNAME", "" ], [ "Credential", "Allows you to login to servers using alternative credentials. To use:\n$scred = Get-Credential, then pass $scred object to the -Credential parameter.", "", false, "false", "", "" ], [ "CollectorSet", "Filters results to data collectors within specific collector sets by name. Accepts wildcards for pattern matching.\r\nUse this when you want to examine collectors in a particular performance monitoring setup, such as \u0027System Correlation\u0027 or custom SQL Server baseline collector sets.", "DataCollectorSet", false, "false", "", "" ], [ "Collector", "Filters results to specific data collectors by name within the collector sets. Accepts wildcards for pattern matching.\r\nUse this when you need to examine a particular collector\u0027s configuration, such as one focused on SQL Server counters or system resource monitoring.", "DataCollector", false, "false", "", "" ], [ "InputObject", "Accepts collector set objects from Get-DbaPfDataCollectorSet via the pipeline to retrieve their individual data collectors.\r\nUse this for pipeline operations when you want to drill down from collector sets to examine the specific performance counters and configuration details of their data collectors.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Performance", "DataCollector", "PerfCounter" ], "CommandName": "Get-DbaPfDataCollectorCounter", "Name": "Get-DbaPfDataCollectorCounter", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaPfDataCollectorCounter [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-CollectorSet] \u003cString[]\u003e] [[-Collector] \u003cString[]\u003e] [[-Counter] \u003cString[]\u003e] [[-InputObject] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per counter added to the Data Collector Set.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- DataCollectorSet: The name of the parent Data Collector Set containing the collector\r\n- DataCollector: The name of the specific Data Collector within the Collector Set\r\n- Name: The full path of the performance counter (e.g., \u0027\\Processor(_Total)\\% Processor Time\u0027)\r\n- FileName: The output file name where performance counter data will be stored\nAdditional properties available:\r\n- DataCollectorSetXml: XML configuration of the Data Collector Set\r\n- Credential: The credential object used for authentication", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorCounter\nGets all counters for all Collector Sets on localhost.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorCounter -ComputerName sql2017\nGets all counters for all Collector Sets on on sql2017.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorCounter -ComputerName sql2017 -Counter \u0027\\Processor(_Total)\\% Processor Time\u0027\nGets the \u0027\\Processor(_Total)\\% Processor Time\u0027 counter on sql2017.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorCounter -ComputerName sql2017, sql2016 -Credential ad\\sqldba -CollectorSet \u0027System Correlation\u0027\nGets all counters for the \u0027System Correlation\u0027 CollectorSet on sql2017 and sql2016 using alternative credentials.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorSet -CollectorSet \u0027System Correlation\u0027 | Get-DbaPfDataCollector | Get-DbaPfDataCollectorCounter\nGets all counters for the \u0027System Correlation\u0027 CollectorSet.", "Description": "Retrieves the list of performance counters that are configured within Windows Performance Monitor Data Collector Sets. This is useful for auditing performance monitoring configurations, verifying which SQL Server and system counters are being collected, and understanding your performance data collection setup. The function extracts counter details from existing Data Collector objects, showing you exactly which performance metrics are being tracked for troubleshooting and capacity planning.", "Links": "https://dbatools.io/Get-DbaPfDataCollectorCounter", "Synopsis": "Retrieves performance counter configurations from Windows Performance Monitor Data Collector Sets.", "Availability": "Windows only", "Params": [ [ "ComputerName", "Specifies the target server(s) where Performance Monitor Data Collector Sets are configured.\r\nUse this to audit performance counters on remote SQL Server instances or retrieve counter configurations from multiple servers at once.", "", false, "false", "$env:COMPUTERNAME", "" ], [ "Credential", "Allows you to login to servers using alternative credentials. To use:\n$scred = Get-Credential, then pass $scred object to the -Credential parameter.", "", false, "false", "", "" ], [ "CollectorSet", "Filters results to specific Data Collector Set names such as \u0027System Correlation\u0027 or custom SQL performance monitoring sets.\r\nUse this when you need to examine counters for particular monitoring scenarios rather than reviewing all configured performance data collection.", "DataCollectorSet", false, "false", "", "" ], [ "Collector", "Filters results to specific Data Collector names within a Collector Set.\r\nUse this to narrow down results when a Collector Set contains multiple data collectors and you only need counter details from specific ones.", "DataCollector", false, "false", "", "" ], [ "Counter", "Searches for specific performance counter names using the exact Windows Performance Monitor format like \u0027\\SQLServer:Buffer Manager\\Page life expectancy\u0027 or \u0027\\Processor(_Total)\\% Processor Time\u0027.\r\nUse this to verify if critical SQL Server or system performance counters are being monitored in your data collection setup.", "", false, "false", "", "" ], [ "InputObject", "Accepts Data Collector objects from Get-DbaPfDataCollector via the pipeline to extract counter configurations.\r\nUse this for chaining commands when you want to drill down from Collector Sets to specific Data Collectors and then to their individual performance counters.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Performance", "DataCollector", "PerfCounter" ], "CommandName": "Get-DbaPfDataCollectorCounterSample", "Name": "Get-DbaPfDataCollectorCounterSample", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaPfDataCollectorCounterSample [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-CollectorSet] \u003cString[]\u003e] [[-Collector] \u003cString[]\u003e] [[-Counter] \u003cString[]\u003e] [-Continuous] [[-ListSet]] [[-MaxSamples] \u003cInt32\u003e] [[-SampleInterval] \u003cInt32\u003e] [[-InputObject] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject (when -Continuous is not specified)\nReturns one object per counter sample collected from Performance Monitor.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- DataCollectorSet: The name of the parent Data Collector Set\r\n- DataCollector: The name of the Data Collector\r\n- Name: The counter name/path\r\n- Timestamp: DateTime of the counter collection\r\n- Path: The counter path in standard Performance Monitor format\r\n- InstanceName: The instance name from the counter sample\r\n- CookedValue: The processed/calculated counter value (double)\r\n- RawValue: The raw counter value before processing (long)\r\n- SecondValue: The secondary value for certain counter types (long)\r\n- MultipleCount: Multiple count value for the sample (int)\r\n- CounterType: The type of performance counter (PerformanceCounterType)\r\n- SampleTimestamp: The timestamp of the individual sample (datetime)\r\n- SampleTimestamp100NSec: Timestamp in 100-nanosecond intervals (long)\r\n- Status: Status of the sample (PerformanceCounterSampleStatus)\r\n- DefaultScale: Default scaling factor for the counter (int)\r\n- TimeBase: Time base value for the counter (long)\nAdditional properties available:\r\n- Sample: Collection of counter samples (excluded from default view)\nSystem.Diagnostics.PerformanceCounterSampleData (when -Continuous is specified)\nWhen -Continuous is specified, returns raw output from PowerShell\u0027s Get-Counter cmdlet providing continuous real-time counter samples until interrupted with CTRL+C.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorCounterSample\nGets a single sample for all counters for all Collector Sets on localhost.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorCounterSample -Counter \u0027\\Processor(_Total)\\% Processor Time\u0027\nGets a single sample for all counters for all Collector Sets on localhost.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorCounter -ComputerName sql2017, sql2016 | Out-GridView -PassThru | Get-DbaPfDataCollectorCounterSample -MaxSamples 10\nGets 10 samples for all counters for all Collector Sets for servers sql2016 and sql2017.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorCounterSample -ComputerName sql2017\nGets a single sample for all counters for all Collector Sets on sql2017.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorCounterSample -ComputerName sql2017, sql2016 -Credential ad\\sqldba -CollectorSet \u0027System Correlation\u0027\nGets a single sample for all counters for the \u0027System Correlation\u0027 CollectorSet on sql2017 and sql2016 using alternative credentials.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorCounterSample -CollectorSet \u0027System Correlation\u0027\nGets a single sample for all counters for the \u0027System Correlation\u0027 CollectorSet.", "Description": "Collects performance counter data from Windows Performance Monitor collector sets and individual counters on SQL Server systems. This function wraps PowerShell\u0027s Get-Counter cmdlet to provide structured performance data that DBAs use for monitoring CPU, memory, disk I/O, and SQL Server-specific metrics. You can capture single snapshots for quick checks or continuous samples for ongoing monitoring during troubleshooting sessions. The output integrates seamlessly with Get-DbaPfDataCollectorCounter to build comprehensive performance monitoring workflows.", "Links": "https://dbatools.io/Get-DbaPfDataCollectorCounterSample", "Synopsis": "Retrieves real-time performance counter samples from SQL Server systems for monitoring and troubleshooting.", "Availability": "Windows only", "Params": [ [ "ComputerName", "The target computer where performance counters will be collected. Defaults to localhost.\r\nUse this when monitoring remote SQL Server systems or collecting performance data from multiple servers simultaneously.", "", false, "false", "$env:COMPUTERNAME", "" ], [ "Credential", "Allows you to login to servers using alternative credentials. To use:\n$scred = Get-Credential, then pass $scred object to the -Credential parameter.", "", false, "false", "", "" ], [ "CollectorSet", "Specifies which Performance Monitor Data Collector Set to sample counters from. Accepts wildcard patterns for matching multiple sets.\r\nUse this to focus on specific pre-configured collector sets like \u0027System Performance\u0027 or custom SQL Server monitoring sets instead of sampling all available counters.", "DataCollectorSet", false, "false", "", "" ], [ "Collector", "Specifies which individual Data Collector within a Collector Set to sample from. Accepts wildcard patterns.\r\nUse this when you need samples from specific collectors rather than all collectors in a set, such as targeting only SQL Server-related collectors.", "DataCollector", false, "false", "", "" ], [ "Counter", "Specifies individual performance counter paths to sample in the standard format like \u0027\\Processor(_Total)\\% Processor Time\u0027 or \u0027\\SQLServer:Buffer Manager\\Page life expectancy\u0027.\r\nUse this when you need specific counters for targeted troubleshooting rather than sampling all available counters from collector sets.", "", false, "false", "", "" ], [ "Continuous", "Enables continuous sampling until you press CTRL+C instead of taking a single snapshot. Combine with SampleInterval to control timing between samples.\r\nUse this during active troubleshooting sessions when you need to monitor performance trends in real-time, such as during query execution or system load events.", "", false, "false", "False", "" ], [ "ListSet", "Lists available performance counter sets on the target computers without collecting samples. Supports wildcard patterns for filtering.\r\nUse this to discover what counter sets are available before running collection commands, especially useful when working with unfamiliar systems or custom monitoring configurations.", "", false, "false", "", "" ], [ "MaxSamples", "Specifies the maximum number of samples to collect from each counter before stopping. Default is 1 sample.\r\nUse this when you need a specific number of data points for analysis, such as collecting 60 samples at 1-second intervals to get one minute of baseline performance data.", "", false, "false", "0", "" ], [ "SampleInterval", "Sets the time interval between samples in seconds with a minimum and default of 1 second.\r\nUse this to control sampling frequency based on your monitoring needs - shorter intervals for active troubleshooting or longer intervals for baseline collection to reduce overhead.", "", false, "false", "0", "" ], [ "InputObject", "Accepts the object output by Get-DbaPfDataCollectorCounter via the pipeline.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Performance", "DataCollector", "PerfCounter" ], "CommandName": "Get-DbaPfDataCollectorSet", "Name": "Get-DbaPfDataCollectorSet", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaPfDataCollectorSet [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-CollectorSet] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per Data Collector Set found on the target computer(s).\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The name of the computer where the Data Collector Set is configured\r\n- Name: The name of the Data Collector Set\r\n- DisplayName: The user-friendly display name of the collector set\r\n- Description: Text description of what the collector set monitors\r\n- State: Current state (Unknown, Disabled, Queued, Ready, Running)\r\n- Duration: Duration in seconds for which the collector set will run\r\n- OutputLocation: File system path where collected data is stored\r\n- LatestOutputLocation: Path to the most recently collected output files\r\n- RootPath: Root directory path for the collector set configuration\r\n- SchedulesEnabled: Boolean indicating if schedules are enabled\r\n- Segment: Segment configuration value for data collection\r\n- SegmentMaxDuration: Maximum duration in seconds for a collection segment\r\n- SegmentMaxSize: Maximum size in MB for a collection segment\r\n- SerialNumber: Serial number or identifier for the collector set\r\n- Server: Name of the server hosting the collector set\r\n- StopOnCompletion: Boolean indicating if the collector set stops automatically when complete\r\n- Subdirectory: Subdirectory path for organizing collector set output\r\n- SubdirectoryFormat: Format pattern for subdirectory naming\r\n- SubdirectoryFormatPattern: Detailed format pattern specification\r\n- Task: Name of the Windows Task Scheduler task associated with the collector set\r\n- TaskArguments: Command-line arguments passed to the collector set task\r\n- TaskRunAsSelf: Boolean indicating if the task runs under the specified user account\r\n- TaskUserTextArguments: User-specified text arguments for the task\r\n- UserAccount: Windows user account under which the collector set runs\nAdditional properties available (via Select-Object *):\r\n- Keywords: Keywords associated with the collector set for searching/categorizing\r\n- DescriptionUnresolved: Raw description text before localization/resolution\r\n- DisplayNameUnresolved: Raw display name before localization/resolution\r\n- Schedules: Collection of schedule objects for the collector set\r\n- Xml: Raw XML configuration of the collector set\r\n- Security: Security descriptor for the collector set\r\n- DataCollectorSetObject: Boolean indicating the object came from a Data Collector Set COM object\r\n- TaskObject: Reference to the underlying Task Scheduler COM object\r\n- Credential: The credentials used to retrieve this collector set", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorSet\nGets all Collector Sets on localhost.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorSet -ComputerName sql2017\nGets all Collector Sets on sql2017.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorSet -ComputerName sql2017 -Credential ad\\sqldba -CollectorSet \u0027System Correlation\u0027\nGets the \u0027System Correlation\u0027 CollectorSet on sql2017 using alternative credentials.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorSet | Select-Object *\nDisplays extra columns and also exposes the original COM object in DataCollectorSetObject.", "Description": "Retrieves detailed information about Windows Performance Monitor Data Collector Sets, which are used to collect performance counters for SQL Server monitoring and troubleshooting. Data Collector Sets define what performance counters to collect, when to collect them, and where to store the collected data. This function helps DBAs inventory existing collector sets, check their status (running, stopped, scheduled), and review their configuration including output locations and schedules. Particularly useful when inheriting a SQL Server environment or auditing existing performance monitoring setup.", "Links": "https://dbatools.io/Get-DbaPfDataCollectorSet", "Synopsis": "Retrieves Windows Performance Monitor Data Collector Sets and their configuration details.", "Availability": "Windows only", "Params": [ [ "ComputerName", "Specifies the Windows server(s) where you want to inventory Performance Monitor Data Collector Sets.\r\nUse this when checking collector sets across multiple SQL Server hosts or when managing performance monitoring from a central location.\r\nAccepts multiple computer names and defaults to the local computer.", "", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Allows you to login to servers using alternative credentials. To use:\n$scred = Get-Credential, then pass $scred object to the -Credential parameter.", "", false, "false", "", "" ], [ "CollectorSet", "Specifies the name(s) of specific Data Collector Sets to retrieve instead of returning all collector sets.\r\nUse this when you need to check the status or configuration of specific performance monitoring setups like \u0027SQL Server Default\u0027 or custom collector sets.\r\nAccepts wildcards and multiple collector set names for targeted monitoring inventory.", "DataCollectorSet", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Performance", "DataCollector", "PerfCounter" ], "CommandName": "Get-DbaPfDataCollectorSetTemplate", "Name": "Get-DbaPfDataCollectorSetTemplate", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaPfDataCollectorSetTemplate [[-Path] \u003cString[]\u003e] [[-Pattern] \u003cString\u003e] [[-Template] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per template found in the specified template directory (default: dbatools built-in repository).\nDefault display properties (via Select-DefaultView):\r\n- Name: The name of the Performance Monitor template\r\n- Source: The source or origin of the template (from the metadata XML file)\r\n- UserAccount: The user account under which the template will run when deployed\r\n- Description: Description of what performance counters and scenarios the template monitors\nAdditional properties available (via Select-Object *):\r\n- Path: Full file system path to the template XML file\r\n- File: The template XML file name", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorSetTemplate\nReturns information about all the templates in the local dbatools repository.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorSetTemplate | Out-GridView -PassThru | Import-DbaPfDataCollectorSetTemplate -ComputerName sql2017 | Start-DbaPfDataCollectorSet\nAllows you to select a template, then deploys it to sql2017 and immediately starts the DataCollectorSet.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorSetTemplate | Select-Object *\nReturns more information about the template, including the full path/filename.", "Description": "Retrieves information about predefined Windows Performance Monitor (PerfMon) templates specifically created for SQL Server performance analysis. These templates include counter sets for monitoring long-running queries, PAL (Performance Analysis of Logs) configurations for different SQL Server versions, and other SQL Server-focused performance scenarios.\n\nThe function parses XML template files and returns details like template names, descriptions, sources, and file paths. Use this to discover available monitoring templates before deploying them with Import-DbaPfDataCollectorSetTemplate, eliminating the need to manually browse template directories or guess what counters to collect for specific performance issues.", "Links": "https://dbatools.io/Get-DbaPfDataCollectorSetTemplate", "Synopsis": "Retrieves Windows Performance Monitor templates designed for SQL Server monitoring and troubleshooting.", "Availability": "Windows only", "Params": [ [ "Path", "Specifies the directory path containing Performance Monitor template XML files. Defaults to the dbatools built-in template repository (\\bin\\perfmontemplates\\collectorsets).\r\nUse this when you have custom template files stored in a different location or want to load templates from a network share.", "", false, "false", "\"$script:PSModuleRoot\\bin\\perfmontemplates\\collectorsets\"", "" ], [ "Pattern", "Filters templates by matching text patterns against template names and descriptions using regex syntax. Supports wildcards (* becomes .*).\r\nUse this to find templates for specific scenarios like \"long.*query\" to locate long-running query monitoring templates.", "", false, "false", "", "" ], [ "Template", "Specifies one or more template names to retrieve by exact match. Accepts multiple values and supports tab completion to browse available templates.\r\nUse this when you know the specific template names you need rather than browsing all available templates.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Diagnostic", "Cache", "Memory" ], "CommandName": "Get-DbaPlanCache", "Name": "Get-DbaPlanCache", "Author": "Tracy Boggiano, databasesuperhero.com", "Syntax": "Get-DbaPlanCache [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance queried, providing aggregate single-use plan cache statistics.\nProperties:\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Size: Total size of single-use adhoc and prepared statement plans; dbasize object convertible to Bytes, Kilobytes, Megabytes, Gigabytes, Terabytes\r\n- UseCount: Count of single-use adhoc and prepared statement plans found in the plan cache", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaPlanCache -SqlInstance sql2017\nReturns the single use plan cache usage information for SQL Server instance 2017\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaPlanCache -SqlInstance sql2017 -SqlCredential sqladmin\nReturns the single use plan cache usage information for SQL Server instance 2017 using login \u0027sqladmin\u0027", "Description": "Analyzes the plan cache to identify memory consumed by single-use adhoc and prepared statements that are unlikely to be reused. These plans accumulate over time and can consume significant memory without providing performance benefits.\n\nWhen applications generate dynamic SQL without proper parameterization, each unique statement creates its own execution plan. These single-use plans waste memory and can cause plan cache pressure, leading to performance issues and increased compilation overhead.\n\nThe function queries sys.dm_exec_cached_plans to calculate the total size and count of single-use plans. If the results show over 100 MB of single-use plans, consider enabling \"optimize for adhoc workloads\" (SQL Server 2008+) or use Remove-DbaQueryPlan to clear the cache during maintenance windows.\n\nReferences: https://www.sqlskills.com/blogs/kimberly/plan-cache-adhoc-workloads-and-clearing-the-single-use-plan-cache-bloat/\n\nNote: This command returns results from all SQL server instances on the destination server but the process column is specific to -SqlInstance passed.", "Links": "https://dbatools.io/Get-DbaPlanCache", "Synopsis": "Retrieves single-use plan cache usage to identify memory waste from adhoc and prepared statements", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "PowerPlan", "Utility" ], "CommandName": "Get-DbaPowerPlan", "Name": "Get-DbaPowerPlan", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaPowerPlan [-ComputerName] \u003cDbaInstanceParameter[]\u003e [[-Credential] \u003cPSCredential\u003e] [-List] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nDefault output (when -List is not specified):\nReturns one object per computer queried, showing the currently active power plan.\nProperties:\r\n- ComputerName: The SQL Server host computer name\r\n- PowerPlan: Name of the currently active power plan (e.g., \"High Performance\", \"Balanced\", \"Power saver\"); shows \"Unknown\" if detection fails\nWhen -List is specified:\nReturns one object per available power plan on each computer, showing all power plans and which one is active.\nProperties:\r\n- ComputerName: The SQL Server host computer name\r\n- PowerPlan: Name of the power plan\r\n- IsActive: Boolean indicating if this power plan is currently active (True or False)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaPowerPlan -ComputerName sql2017\nGets the Power Plan settings for sql2017\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaPowerPlan -ComputerName sql2017 -Credential ad\\admin\nGets the Power Plan settings for sql2017 using an alternative credential\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaPowerPlan -ComputerName sql2017 -List\nGets all available Power Plans on sql2017", "Description": "Checks the active Windows Power Plan configuration on SQL Server host computers to ensure they follow performance best practices. SQL Server performance can be significantly impacted by power management settings that throttle CPU frequency or put processors to sleep during idle periods.\n\nBy default, returns the currently active power plan for each specified computer. Use the -List parameter to view all available power plans and their status. Microsoft recommends using the \"High Performance\" power plan for SQL Server hosts to prevent CPU throttling and ensure consistent database performance.", "Links": "https://dbatools.io/Get-DbaPowerPlan", "Synopsis": "Retrieves Windows Power Plan configuration from SQL Server hosts to verify High Performance settings.", "Availability": "Windows only", "Params": [ [ "ComputerName", "Specifies the SQL Server host computer(s) to check for Windows Power Plan configuration. Accepts multiple server names for bulk power plan auditing.\r\nUse this to verify that your SQL Server hosts are configured with the recommended \"High Performance\" power plan instead of \"Balanced\" or \"Power Saver\" modes that can throttle CPU performance.", "", true, "true (ByValue)", "", "" ], [ "Credential", "Specifies a PSCredential object to use in authenticating to the server(s), instead of the current user account.", "", false, "false", "", "" ], [ "List", "Returns all available power plans on the target computers instead of just the currently active plan. Shows the status of each plan including which one is active.\r\nUse this when you need to see all power plan options available on a server before making configuration changes or to audit power plan availability across your environment.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Privilege", "OS", "Security" ], "CommandName": "Get-DbaPrivilege", "Name": "Get-DbaPrivilege", "Author": "Klaas Vandenberghe (@PowerDBAKlaas)", "Syntax": "Get-DbaPrivilege [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per unique user or group found across the six Windows security privileges being audited.\nProperties:\r\n- ComputerName: The name of the computer where the privilege audit was performed\r\n- User: The user or group account name; converted from SID to account name if applicable\r\n- LogonAsBatch: Boolean indicating if the user has SeBatchLogonRight privilege\r\n- InstantFileInitialization: Boolean indicating if the user has SeManageVolumePrivilege (Instant File Initialization)\r\n- LockPagesInMemory: Boolean indicating if the user has SeLockMemoryPrivilege\r\n- GenerateSecurityAudit: Boolean indicating if the user has SeAuditPrivilege\r\n- LogonAsAService: Boolean indicating if the user has SeServiceLogonRight privilege\r\n- CreateGlobalObjects: Boolean indicating if the user has SeCreateGlobalPrivilege (required by some backup agents)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaPrivilege -ComputerName sqlserver2014a\nGets the local privileges on computer sqlserver2014a.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027sql1\u0027,\u0027sql2\u0027,\u0027sql3\u0027 | Get-DbaPrivilege\nGets the local privileges on computers sql1, sql2 and sql3.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaPrivilege -ComputerName sql1,sql2 | Out-GridView\nGets the local privileges on computers sql1 and sql2, and shows them in a grid view.", "Description": "Audits six Windows privileges that directly impact SQL Server performance and functionality: Lock Pages in Memory, Instant File Initialization, Logon as Batch, Generate Security Audits, Logon as a Service, and Create Global Objects. These privileges are essential for SQL Server service accounts to achieve optimal performance and proper operation.\n\nUse this to verify that SQL Server service accounts have the necessary Windows privileges configured, troubleshoot performance issues related to missing privileges, or audit security configurations across your SQL Server environment. The function exports the local security policy using secedit and parses the results to show which users and groups hold these critical privileges.\n\nRequires Local Admin rights on destination computer(s).", "Links": "https://dbatools.io/Get-DbaPrivilege", "Synopsis": "Retrieves Windows security privileges critical for SQL Server performance from target computers.", "Availability": "Windows only", "Params": [ [ "ComputerName", "Specifies the target computer names where you want to audit Windows privileges. Accepts multiple computer names for bulk privilege auditing.\r\nUse this to check privilege configurations on SQL Server host machines, especially when troubleshooting performance issues related to missing Lock Pages in Memory or Instant File Initialization \r\nrights.", "cn,host,Server", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Credential object used to connect to the computer as a different user.", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Diagnostic", "Process", "Session", "ActivityMonitor" ], "CommandName": "Get-DbaProcess", "Name": "Get-DbaProcess", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaProcess [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Spid] \u003cInt32[]\u003e] [[-ExcludeSpid] \u003cInt32[]\u003e] [[-Database] \u003cString[]\u003e] [[-Login] \u003cString[]\u003e] [[-Hostname] \u003cString[]\u003e] [[-Program] \u003cString[]\u003e] [-ExcludeSystemSpids] [-EnableException] [-Intersect] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Agent.Job (SMO Process object)\nReturns one object per active SQL Server process/session matching the specified filter criteria.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Spid: Session ID number of the process\r\n- Login: SQL Server login or Windows authentication account name\r\n- LoginTime: DateTime when the session logged in\r\n- Host: Client machine name/hostname\r\n- Database: Database currently connected to the session\r\n- BlockingSpid: Session ID of the process blocking this session (if blocked)\r\n- Program: Client application name that initiated the session\r\n- Status: Current status of the session (sleeping, running, etc.)\r\n- Command: T-SQL command currently being executed\r\n- Cpu: CPU time consumed in milliseconds\r\n- MemUsage: Memory usage in pages (8 KB per page)\r\n- LastRequestStartTime: DateTime when the last request started\r\n- LastRequestEndTime: DateTime when the last request completed\r\n- MinutesAsleep: Minutes elapsed since last request ended\r\n- ClientNetAddress: Client IP address\r\n- NetTransport: Network transport protocol (Named Pipes, TCP, Shared Memory)\r\n- EncryptOption: Encryption setting (Off, On, Required, Login)\r\n- AuthScheme: Authentication scheme used (NTLM, Kerberos, SQL, etc.)\r\n- NetPacketSize: Network packet size in bytes\r\n- ClientVersion: Client library version number\r\n- HostProcessId: Operating system process ID on the client machine\r\n- IsSystem: Boolean indicating if this is a system session\r\n- EndpointName: Name of the endpoint the connection is using\r\n- IsDac: Boolean indicating if this is a Dedicated Admin Connection (DAC)\r\n- LastQuery: The last T-SQL statement executed in this session\nAdditional properties available (from SMO Process object):\r\n- Parent: Reference to the parent Server object\r\n- All other SMO process properties are accessible using Select-Object *", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaProcess -SqlInstance sqlserver2014a -Login base\\ctrlb, sa\nShows information about the processes for base\\ctrlb and sa on sqlserver2014a. Windows Authentication is used in connecting to sqlserver2014a.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaProcess -SqlInstance sqlserver2014a -SqlCredential $credential -Spid 56, 77\nShows information about the processes for spid 56 and 57. Uses alternative (SQL or Windows) credentials to authenticate to sqlserver2014a.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaProcess -SqlInstance sqlserver2014a -Program \u0027Microsoft SQL Server Management Studio\u0027\nShows information about the processes that were created in Microsoft SQL Server Management Studio.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaProcess -SqlInstance sqlserver2014a -Host workstationx, server100\nShows information about the processes that were initiated by hosts (computers/clients) workstationx and server 1000.", "Description": "Displays comprehensive information about SQL Server processes including session details, connection properties, timing data, and the last executed SQL statement. This function combines data from multiple system views to provide a complete picture of current database activity.\n\nUse this to monitor active connections, identify blocking processes, track application connections, troubleshoot performance issues, or audit database access patterns. The output includes connection timing, network transport details, authentication schemes, client information, and recent query activity.\n\nYou can filter results by login name, hostname, program name, database, or specific session IDs to focus on particular processes of interest. This is especially useful for identifying connection leaks, monitoring specific applications, or investigating security concerns.\n\nThanks to Michael J Swart at https://sqlperformance.com/2017/07/sql-performance/find-database-connection-leaks for the query to get the last executed SQL statement, minutesasleep and host process ID.", "Links": "https://dbatools.io/Get-DbaProcess", "Synopsis": "Retrieves active SQL Server processes and sessions with detailed connection and activity information.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Spid", "Filters results to specific process IDs (SPIDs) you want to monitor. Also includes any processes that are blocked by the specified SPIDs.\r\nUse this when investigating specific connections or troubleshooting blocking issues where you need to see both the blocker and blocked processes.", "", false, "false", "", "" ], [ "ExcludeSpid", "Excludes specific process IDs (SPIDs) from the results, even if they match other filter criteria.\r\nUse this to remove known processes like monitoring tools, maintenance jobs, or your own session from the output. This filter is applied last, overriding all other inclusion filters.", "", false, "false", "", "" ], [ "Database", "Filters results to sessions currently connected to specific databases.\r\nUse this when monitoring activity on particular databases, investigating database-specific performance issues, or auditing access to sensitive databases.", "", false, "false", "", "" ], [ "Login", "Filters results to sessions connected with specific SQL Server login names or Windows authentication accounts.\r\nUse this to monitor connections from specific applications, service accounts, or users when investigating security concerns or connection patterns.", "", false, "false", "", "" ], [ "Hostname", "Filters results to sessions originating from specific client machines or server names.\r\nUse this when tracking connections from particular workstations, application servers, or investigating connection leaks from specific hosts.", "", false, "false", "", "" ], [ "Program", "Filters results to sessions created by specific client applications such as \u0027Microsoft SQL Server Management Studio\u0027 or custom application names.\r\nUse this to monitor connections from particular applications, identify connection patterns, or troubleshoot application-specific database issues.", "", false, "false", "", "" ], [ "ExcludeSystemSpids", "Excludes system processes (SPIDs 1-50) from the results to focus only on user connections and application processes.\r\nUse this when you want to see only actual user sessions and application connections, filtering out SQL Server internal processes like checkpoints, log writers, and system tasks.", "", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "Intersect", "If this switch is enabled, take the intersection of Spid, Login, Hostname, Program, and Database rather than the union.", "", false, "false", "False", "" ] ] }, { "Tags": [ "ProductKey", "Utility" ], "CommandName": "Get-DbaProductKey", "Name": "Get-DbaProductKey", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaProductKey [-ComputerName] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance found on the target computer(s) with license key information.\nProperties:\r\n- ComputerName: The name of the computer hosting the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance format)\r\n- Version: The SQL Server version name (e.g., \"SQL Server 2019\", \"SQL Server 2016\")\r\n- Edition: The SQL Server edition (Enterprise, Standard, Express, Developer, etc.)\r\n- Key: The decoded product key in format XXXXX-XXXXX-XXXXX-XXXXX-XXXXX; returns \"SQL Server Express Edition\" for Express editions, or an error message if the key cannot be read or decoded from the \r\nregistry", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaProductKey -ComputerName winxp, sqlservera, sqlserver2014a, win2k8\nGets SQL Server versions, editions and product keys for all instances within each server or workstation.", "Description": "Decodes SQL Server product keys from registry DigitalProductID entries across all installed instances on target computers. This is essential for license compliance auditing, asset inventory during migrations, and generating compliance reports for auditors. The command handles different SQL Server versions (2005+), supports clustered instances, and automatically identifies Express editions that don\u0027t require product keys. Works by connecting to each SQL instance to determine version and edition, then accessing registry data remotely to decode the binary product key information.", "Links": "https://dbatools.io/Get-DbaProductKey", "Synopsis": "Retrieves SQL Server product keys from registry data for license compliance and inventory management.", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the SQL Server instances or computer names to retrieve product keys from. Accepts multiple values for bulk operations.\r\nUse this when you need to audit license compliance across multiple servers or gather product key inventory during migrations.", "SqlInstance", true, "true (ByValue)", "", "" ], [ "SqlCredential", "This command logs into the SQL instance to gather additional information.\nUse this parameter to connect to the discovered SQL instances using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)", "", false, "false", "", "" ], [ "Credential", "Login to the target Windows instance using alternative credentials. Windows Authentication supported. Accepts credential objects (Get-Credential)", "", false, "false", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Diagnostic", "Performance", "Query" ], "CommandName": "Get-DbaQueryExecutionTime", "Name": "Get-DbaQueryExecutionTime", "Author": "Brandon Abshire, netnerds.net", "Syntax": "Get-DbaQueryExecutionTime -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-MaxResultsPerDb \u003cInt32\u003e] [-MinExecs \u003cInt32\u003e] [[-MinExecMs] \u003cInt32\u003e] [[-ExcludeSystem]] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per stored procedure or SQL statement matching the specified execution time filters. Results are limited to the top N results per database based on average CPU worker time (highest \r\nfirst), where N is controlled by -MaxResultsPerDb (default 100).\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The name of the computer hosting the SQL Server instance\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance format)\r\n- Database: The name of the database containing the query\r\n- ProcName: The procedure or object name; empty string for ad hoc statements\r\n- ObjectID: The object ID from sys.dm_exec_procedure_stats or sys.dm_exec_query_stats\r\n- TypeDesc: The type description - \"PROCEDURE\" for stored procedures or \"STATEMENT\" for ad hoc queries\r\n- Executions: The execution_count - total number of times the query has been executed\r\n- AvgExecMs: Average execution time in milliseconds (total_worker_time / execution_count / 1000)\r\n- MaxExecMs: Maximum execution time in milliseconds (max_worker_time / 1000)\r\n- CachedTime: DateTime when the query plan was cached (1901-01-01 for ad hoc statements)\r\n- LastExecTime: DateTime when the query last executed\r\n- TotalWorkerTimeMs: Total CPU worker time in milliseconds across all executions\r\n- TotalElapsedTimeMs: Total elapsed time in milliseconds across all executions\r\n- SQLText: Truncated SQL text (first 50 characters for ad hoc statements, procedure name for stored procedures)\nAdditional properties (available with Select-Object *):\r\n- FullStatementText: Complete SQL statement text (full T-SQL for ad hoc statements, procedure name for stored procedures)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaQueryExecutionTime -SqlInstance sql2008, sqlserver2012\nReturn the top 100 slowest stored procedures or statements for servers sql2008 and sqlserver2012.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaQueryExecutionTime -SqlInstance sql2008 -Database TestDB\nReturn the top 100 slowest stored procedures or statements on server sql2008 for only the TestDB database.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaQueryExecutionTime -SqlInstance sql2008 -Database TestDB -MaxResultsPerDb 100 -MinExecs 200 -MinExecMs 1000\nReturn the top 100 slowest stored procedures or statements on server sql2008 for only the TestDB database, limiting results to queries with more than 200 total executions and an execution time over \r\n1000ms or higher.", "Description": "Analyzes SQL Server\u0027s query execution statistics to identify performance bottlenecks by examining CPU worker time data from dynamic management views. This function queries sys.dm_exec_procedure_stats for stored procedures and sys.dm_exec_query_stats for ad hoc statements, returning detailed execution metrics including average execution time, total executions, and maximum execution time.\n\nUse this when troubleshooting performance issues, identifying resource-intensive queries during peak hours, or conducting routine performance audits. The results help pinpoint which stored procedures or SQL statements are consuming the most CPU resources across your databases, so you don\u0027t have to manually query DMVs or run expensive profiler traces.\n\nBy default, returns the top 100 results per database for queries executed at least 100 times with an average execution time of 500ms or higher. Results include the full SQL text for ad hoc statements and procedure names for stored procedures, along with execution statistics and timing data.", "Links": "https://dbatools.io/Get-DbaQueryExecutionTime", "Synopsis": "Retrieves stored procedures and SQL statements with the highest CPU execution times from SQL Server instances.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to analyze for query execution statistics. Accepts wildcards for pattern matching.\r\nUse this when troubleshooting performance issues in specific databases instead of scanning all databases on the instance.\r\nHelpful for focusing on production databases or isolating performance analysis to databases experiencing issues.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies databases to skip during the execution time analysis. Accepts wildcards for pattern matching.\r\nUse this to avoid processing databases that are known to be performing well or contain only static reference data.\r\nCommon use case is excluding development or staging databases when analyzing production performance.", "", false, "false", "", "" ], [ "MaxResultsPerDb", "Limits the number of top execution time results returned per database. Defaults to 100 results.\r\nSpecify a lower number for quick performance overviews or higher numbers for comprehensive analysis.\r\nLarge values may impact query performance on busy systems with extensive plan cache data.", "", false, "false", "100", "" ], [ "MinExecs", "Filters results to queries that have executed at least this many times. Defaults to 100 executions.\r\nUse this to focus on frequently-run queries that have consistent performance patterns rather than one-time queries.\r\nHigher values help identify truly problematic queries that impact system performance regularly.", "", false, "false", "100", "" ], [ "MinExecMs", "Filters results to queries with an average execution time of at least this many milliseconds. Defaults to 500ms.\r\nUse this to focus on genuinely slow queries rather than fast queries that happen to consume CPU cycles.\r\nLowering this value shows more queries but may include acceptable performance levels.", "", false, "false", "500", "" ], [ "ExcludeSystem", "Skips analysis of system databases (master, model, msdb, tempdb).\r\nUse this when focusing performance analysis on user databases only, since system database queries are typically administrative.\r\nSystem database performance issues are usually infrastructure-related rather than application code problems.", "ExcludeSystemDatabases", false, "false", "False", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ] ] }, { "Tags": "DataGeneration", "CommandName": "Get-DbaRandomizedDataset", "Name": "Get-DbaRandomizedDataset", "Author": "Sander Stad (@sqlstad, sqlstad.nl)", "Syntax": "Get-DbaRandomizedDataset [[-Template] \u003cString[]\u003e] [[-TemplateFile] \u003cString[]\u003e] [[-Rows] \u003cInt32\u003e] [[-Locale] \u003cString\u003e] [[-InputObject] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one PSCustomObject per generated row. The properties of each object are dynamically defined by the columns array in the template JSON file.\nProperties depend on the template used:\r\n- Each property name corresponds to a column.Name value from the template file\r\n- Each property value is generated by Get-DbaRandomizedValue based on the column\u0027s Type and SubType\r\n- Property data types vary based on the semantic type specified (string, int, datetime, guid, etc.)\nExample with PersonalData template (typical properties):\r\n- FirstName: Generated first name (string)\r\n- LastName: Generated last name (string)\r\n- Email: Generated email address (string)\r\n- PhoneNumber: Generated phone number (string)\r\n- DateOfBirth: Generated birth date (datetime)\r\n- Address: Generated street address (string)\r\n- City: Generated city name (string)\r\n- ZipCode: Generated postal code (string)\r\n- Country: Generated country name (string)\nThe actual properties returned depend on the template specified via -Template or -TemplateFile parameter. Custom templates can define any column names and data types needed for your test data \r\nscenarios.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaRandomizedDataset -Template Personaldata\nGenerate a data set based on the default template PersonalData.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaRandomizedDataset -Template Personaldata -Rows 10\nGenerate a data set based on the default template PersonalData with 10 rows\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaRandomizedDataset -TemplateFile C:\\Dataset\\FinancialData.json\nGenerates data set based on a template file in another directory\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaRandomizedDataset -Template Personaldata, FinancialData\nGenerates multiple data sets\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaRandomizedDatasetTemplate -Template PersonalData | Get-DbaRandomizedDataset\nPipe the templates from Get-DbaRandomizedDatasetTemplate to Get-DbaRandomizedDataset and generate the data set", "Description": "Generates random test datasets using JSON templates that define column names and data types. This function creates realistic sample data for database development, testing, and training environments without exposing production data. Templates can specify SQL Server data types (varchar, int, datetime) or semantic data types (Name.FirstName, Address.City, Person.DateOfBirth) for more realistic datasets. Built-in templates include PersonalData with common PII fields, and you can create custom templates for specific business scenarios.", "Links": "https://dbatools.io/Get-DbaRandomizedDataset", "Synopsis": "Generates random test data using predefined templates for development and testing scenarios", "Availability": "Windows, Linux, macOS", "Params": [ [ "Template", "Specifies the name of one or more built-in templates to use for data generation.\r\nUse this when you want to generate data using predefined column structures like PersonalData which includes names, addresses, and birthdates.\r\nThe function searches through default templates in the module\u0027s bin\\randomizer\\templates directory to find matching names.", "", false, "false", "", "" ], [ "TemplateFile", "Specifies the full path to one or more custom JSON template files that define column structures and data types.\r\nUse this when you need to generate data based on your own custom templates rather than the built-in ones.\r\nTemplate files must be valid JSON with a Columns array defining Name, Type, and SubType properties for each column.", "", false, "false", "", "" ], [ "Rows", "Specifies how many rows of test data to generate for each template.\r\nUse this to control the size of your test dataset based on your development or testing needs.\r\nDefaults to 100 rows if not specified.", "", false, "false", "100", "" ], [ "Locale", "Specifies the locale for generating culture-specific data like names, addresses, and phone numbers.\r\nUse this when you need test data that matches a specific geographic region or language for realistic testing scenarios.\r\nDefaults to \u0027en\u0027 (English) if not specified.", "", false, "false", "en", "" ], [ "InputObject", "Accepts template objects piped from Get-DbaRandomizedDatasetTemplate.\r\nUse this in pipeline scenarios where you first retrieve templates and then generate data from them.\r\nEach input object should contain template information including the FullName path to the JSON template file.", "", false, "true (ByValue)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false,