[ { "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] [-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] [-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", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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, Linux, macOS", "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": "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, Linux, macOS", "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, Linux, macOS", "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, Linux, macOS", "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.", "", 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, Linux, macOS", "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": "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] [-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.", "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", "", "" ], [ "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] [-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:\\\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 and backup operation data into visual timeline reports for analysis and troubleshooting. Takes piped output from Get-DbaAgentJobHistory and Get-DbaDbBackupHistory and generates a complete HTML file with an interactive Google Charts timeline.\n\nPerfect for analyzing job schedules, identifying backup windows, 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 and backup history data", "Availability": "Windows, Linux, macOS", "Params": [ [ "InputObject", "Specifies the SQL Server data to convert into timeline visualization. Accepts piped output from Get-DbaAgentJobHistory or Get-DbaDbBackupHistory.\r\nUse this to transform job execution history or backup operation data 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", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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] [-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.", "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", "" ], [ "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, Linux, macOS", "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, Linux, macOS", "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", "This command requires access to the Windows OS via PowerShell remoting. Use this credential to connect to Windows using alternative credentials.", "", 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, Linux, macOS", "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 -Destination \u003cDbaInstanceParameter[]\u003e [-SourceSqlCredential \u003cPSCredential\u003e] [-DestinationSqlCredential \u003cPSCredential\u003e] [-ExcludePassword] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nCopy-DbaDbMail -Source \u003cDbaInstanceParameter\u003e -Destination \u003cDbaInstanceParameter[]\u003e [-Type \u003cString[]\u003e] [-SourceSqlCredential \u003cPSCredential\u003e] [-DestinationSqlCredential \u003cPSCredential\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", "", "" ], [ "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", "", "" ], [ "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" ], [ "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", "", "" ], [ "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", "", "" ], [ "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[[-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$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.", "", 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", "" ], [ "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] [[-InputObject] \u003cTableViewBase[]\u003e] [-EnableException] [-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", "" ], [ "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] [[-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\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, Linux, macOS", "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", "", "" ], [ "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] [-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] [-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] [-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] [-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] [-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", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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, 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, or policy that was processed\r\n- Type: The type of object being copied - one of \"Policy Category\", \"Policy Condition\", 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, 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 and conditions are copied. 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, Linux, macOS", "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)", "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": "None\nThis command performs migration operations and does not return any output objects. Check the Verbose stream for operation details, or use -WhatIf to preview what would be executed.", "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, Linux, macOS", "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, Linux, macOS", "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, Linux, macOS", "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, Linux, macOS", "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, Linux, macOS", "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, 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", "", "" ], [ "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, 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", "", "" ], [ "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, Linux, macOS", "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, Linux, macOS", "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, Linux, macOS", "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, Linux, macOS", "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, 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", "", "" ], [ "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, 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", "", "" ], [ "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] [[-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] [[-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.", "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", "" ], [ "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] [[-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, 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", "", "" ], [ "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] [[-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\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\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", "Exports database master keys from system databases and copies them to the export directory.\r\nCritical for environments using Transparent Data Encryption (TDE) or encrypted backups where master keys are required for restoration.", "", false, "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.", "", false, "false", "", "AgentServer,Audits,AvailabilityGroups,BackupDevices,CentralManagementServer,Credentials,CustomErrors,DatabaseMail,Databases,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, Linux, macOS", "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 linked servers. Accepts credential objects (Get-Credential)", "", 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] [-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", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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, Linux, macOS", "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, 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", "", "" ], [ "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] [[-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 -LastUsed 10\nReturns all agent job(s) that have not ran in 10 days\n-------------------------- EXAMPLE 4 --------------------------\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 5 --------------------------\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 6 --------------------------\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 7 --------------------------\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 8 --------------------------\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 9 --------------------------\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 10 --------------------------\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", "", "" ], [ "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 seconds (milliseconds converted to seconds)\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, Linux, macOS", "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": [ "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] [[-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-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", "", "" ], [ "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": [ "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- 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 9 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, Linux, macOS", "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, Linux, macOS", "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, Linux, macOS", "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, Linux, macOS", "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, Linux, macOS", "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, Linux, macOS", "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, 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", "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": "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\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\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 = \"\").", "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 table):\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- BackupFinishDate: Timestamp when the backup operation completed\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)\r\n- DataSpaceUsed: Space used by data for the table (in KB)\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, Linux, macOS", "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, 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", "", "" ], [ "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\")", "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) to help DBAs understand the security configuration and plan any necessary changes.", "Links": "https://dbatools.io/Get-DbaExtendedProtection", "Synopsis": "Retrieves Extended Protection authentication settings from SQL Server network configuration.", "Availability": "Windows, Linux, macOS", "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, Linux, macOS", "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, Linux, macOS", "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, 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", "", "" ], [ "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, Linux, macOS", "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, Linux, macOS", "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; null on SQL 2005 unless -ObjectName specified\r\n- StatsRowMods: Number of modifications to underlying data since last statistics update; empty for index rows; null on SQL 2005 unless -ObjectName specified\r\n- HistogramSteps: Number of steps in the statistics histogram; empty for index rows; null on SQL 2005 unless -ObjectName specified\r\n- StatsLastUpdated: DateTime when statistics were last updated; empty for index rows; null on SQL 2005 unless -ObjectName specified\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 2005 or later. For performance reasons, certain statistics details are limited in SQL Server 2005 unless you specify a specific table with the ObjectName parameter.\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 (not included in SQL Server 2005 unless ObjectName is specified)\n- StatsRowMods: the number of changes to the statistics since the last rebuild\n- HistogramSteps: the number of steps in the statistics histogram (not included in SQL Server 2005 unless ObjectName is specified)\n- StatsLastUpdated: when the statistics were last rebuilt (not included in SQL Server 2005 unless ObjectName is specified)", "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, Linux, macOS", "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, Linux, macOS", "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": [ "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, Linux, macOS", "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] [-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.", "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", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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, Linux, macOS", "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, Linux, macOS", "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, Linux, macOS", "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, Linux, macOS", "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, Linux, macOS", "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- 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, Linux, macOS", "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": [ "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, Linux, macOS", "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, Linux, macOS", "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, 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, "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, 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, "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, 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, "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, 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, "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, 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, "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, 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": [ "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, Linux, macOS", "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, Linux, macOS", "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, Linux, macOS", "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, Linux, macOS", "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, Linux, macOS", "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, Linux, macOS", "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, Linux, macOS", "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 five 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", "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 five Windows privileges that directly impact SQL Server performance and functionality: Lock Pages in Memory, Instant File Initialization, Logon as Batch, Generate Security Audits, and Logon as a Service. 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, Linux, macOS", "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, "false", "False", "" ] ] }, { "Tags": "DataGeneration", "CommandName": "Get-DbaRandomizedDatasetTemplate", "Name": "Get-DbaRandomizedDatasetTemplate", "Author": "Sander Stad (@sqlstad, sqlstad.nl)", "Syntax": "Get-DbaRandomizedDatasetTemplate [[-Template] \u003cString[]\u003e] [[-Path] \u003cString[]\u003e] [-ExcludeDefault] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per available template file. Each object contains information about a single template that can be used with Get-DbaRandomizedDataset to generate test data.\nProperties:\r\n- BaseName: The template name without the .json extension (string)\r\n- FullName: The complete file path to the JSON template file (string)\nWhen called without filters, returns all templates from the default dbatools templates directory. When -Path is specified, also includes templates from custom directories. The -Template parameter \r\nfilters results to only matching template names. The -ExcludeDefault switch excludes built-in templates and only returns custom templates from specified paths.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaRandomizedDatasetTemplate\nGet the templates from the default directory\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaRandomizedDatasetTemplate -Template Personaldata, Test\nGet the templates from thedefault directory and filter on PersonalData and Test\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaRandomizedDatasetTemplate -Path C:\\DatasetTemplates\nGet the templates from a custom directory", "Description": "Retrieves JSON template files from default and custom directories that define how to generate realistic test datasets. These templates specify column names, data types, and semantic subtypes (like Name.FirstName, Address.City) for creating structured sample data for development and testing environments. The default templates include PersonalData with common fields like names, addresses, and birthdates, and you can specify custom template directories to include organization-specific data patterns.", "Links": "https://dbatools.io/Get-DbaRandomizedDatasetTemplate", "Synopsis": "Retrieves JSON template files that define column structures for generating realistic test data", "Availability": "Windows, Linux, macOS", "Params": [ [ "Template", "Specifies which template files to retrieve by name (without the .json extension).\r\nUse this to filter results when you only need specific templates like \"PersonalData\" or custom templates.\r\nIf not specified, all available templates from the specified paths are returned.", "", false, "false", "", "" ], [ "Path", "Specifies one or more directory paths containing custom JSON template files for data generation.\r\nUse this when your organization has created custom templates beyond the default dbatools templates.\r\nTemplates from these paths are added to the default templates unless -ExcludeDefault is specified.", "", false, "false", "", "" ], [ "ExcludeDefault", "Excludes the built-in dbatools templates from the results.\r\nUse this when you only want to work with custom templates from specified paths.\r\nThe default templates include common data patterns like PersonalData with names, addresses, and dates.", "", 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-DbaRandomizedType", "Name": "Get-DbaRandomizedType", "Author": "Sander Stad (@sqlstad, sqlstad.nl)", "Syntax": "Get-DbaRandomizedType [[-RandomizedType] \u003cString[]\u003e] [[-RandomizedSubType] \u003cString[]\u003e] [[-Pattern] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per unique Type-SubType combination from the available randomizer types and subtypes.\nProperties:\r\n- Type: The main data category for generating test data (e.g., Address, Commerce, Person, Finance, Internet)\r\n- SubType: The specific data pattern within the main category (e.g., FirstName, LastName, ZipCode, CreditCardNumber)\nResults are always sorted by Type and SubType, with duplicate combinations removed using -Unique. Filters specified by -RandomizedType, -RandomizedSubType, or -Pattern parameters only affect which \r\ncombinations are returned, not the structure of the output objects.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaRandomizedType\nGet all the types and subtypes\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaRandomizedType -Pattern \"Addr\"\nFind all the types and sub types based on a pattern\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaRandomizedType -RandomizedType Person\nFind all the sub types for Person\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaRandomizedType -RandomizedSubType LastName\nGet all the types and subtypes that known by \"LastName\"", "Description": "Returns all available randomizer types and subtypes that can be used with Get-DbaRandomizedValue for data masking and test data generation. These types include realistic data patterns like Person names, Address components, Finance data, Internet values, and Random data types. This command helps you discover what fake data options are available when building data masking rules or generating test datasets for non-production environments.", "Links": "https://dbatools.io/Get-DbaRandomizedType", "Synopsis": "Lists available data types and subtypes for generating realistic test data during database masking operations", "Availability": "Windows, Linux, macOS", "Params": [ [ "RandomizedType", "Filters results to specific main data categories for realistic test data generation.\r\nUse this when you need to focus on particular data types like Person, Address, Finance, Internet, or Random data.\r\nAvailable types include Address, Commerce, Company, Database, Date, Finance, Hacker, Image, Internet, Lorem, Name, Person, Phone, Random, System, and more.", "", false, "false", "", "" ], [ "RandomizedSubType", "Filters results to specific data subtypes within the main categories for precise data masking scenarios.\r\nUse this when you need exact data patterns like FirstName, LastName, Email, CreditCardNumber, or ZipCode.\r\nSubtypes provide granular control over the fake data generation for targeted column masking.", "", false, "false", "", "" ], [ "Pattern", "Searches both main types and subtypes using pattern matching to find relevant data generators.\r\nUse this when you\u0027re unsure of exact type names or want to discover related options like searching \u0027Addr\u0027 to find Address-related types.\r\nSupports wildcard matching against both Type and SubType columns for flexible discovery.", "", 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": [ "DataMasking", "DataGeneration" ], "CommandName": "Get-DbaRandomizedValue", "Name": "Get-DbaRandomizedValue", "Author": "Sander Stad (@sqlstad, sqlstad.nl)", "Syntax": "Get-DbaRandomizedValue [[-DataType] \u003cString\u003e] [[-RandomizerType] \u003cString\u003e] [[-RandomizerSubType] \u003cString\u003e] [[-Min] \u003cObject\u003e] [[-Max] \u003cObject\u003e] [[-Precision] \u003cInt32\u003e] [[-CharacterString] \u003cString\u003e] [[-Format] \u003cString\u003e] [[-Symbol] \u003cString\u003e] [[-Separator] \u003cString\u003e] [[-Value] \u003cString\u003e] [[-Locale] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Scalar values with type determined by parameters (when using -DataType)\nSystem.Int64, System.Int32 (bigint, int, smallint, tinyint data types)\r\n- Returns a single integer value within the appropriate range for the specified data type\nSystem.Decimal, System.Single, System.Double (decimal, float, money, numeric, real data types)\r\n- Returns a single numeric value with optional symbol ($, %, etc.) and specified precision\nSystem.String (varchar, char, nvarchar, nchar, text, ntext data types)\r\n- Returns a string value with random characters from the specified CharacterString\r\n- Length controlled by Min and Max parameters (default 1-255 characters)\nSystem.String in date/time formats (date, datetime, datetime2, smalldatetime, time data types)\r\n- date: \"yyyy-MM-dd\" format\r\n- datetime: \"yyyy-MM-dd HH:mm:ss.fff\" format\r\n- datetime2: \"yyyy-MM-dd HH:mm:ss.fffffff\" format\r\n- smalldatetime: \"yyyy-MM-dd HH:mm:ss\" format\r\n- time: \"HH:mm:ss.fffffff\" format\r\n- uniqueidentifier/guid: GUID in standard format\nSystem.Int32 (bit, bool, userdefineddatatype)\r\n- Returns 0 or 1 for bit/bool types\r\n- Returns 0, 1, or $null for userdefineddatatype depending on Max parameter\nSpecialized Randomizer Types (when using -RandomizerType/-RandomizerSubType)\nVariable return types from the Bogus library:\r\n- Address types (Address, ZipCode, City, State, Country, BuildingNumber, StreetName, Latitude, Longitude): System.String or System.Double\r\n- Commerce types (Product, Department, ProductName, Price): System.String or numeric\r\n- Company types (CompanyName, CatchPhrase, Bs): System.String\r\n- Database types (Engine, Column, CollationName, Type): System.String\r\n- Date types (formatted dates or timestamps based on subtype specification): System.String\r\n- Finance types (Account, Amount, CreditCardNumber, Iban, Bic): System.String or numeric\r\n- Hacker types (Phrase, Abbreviation, Adjective, Noun, Verb): System.String\r\n- Image types (URLs or image data): System.String\r\n- Internet types (Email, UserName, Password, Url, IpAddress, Mac, DomainName): System.String\r\n- Lorem types (Word, Words, Sentence, Sentences, Paragraph, Paragraphs, Slug, Letter, Lines): System.String or array\r\n- Name types (FirstName, LastName, FullName, Prefix, Suffix): System.String\r\n- Person types (various personal information): System.String or other types\r\n- Phone types (PhoneNumber with optional formatting): System.String\r\n- Random types (Int, Long, Double, Float, Decimal, Guid, String, Bytes): System.Int32, System.Int64, System.Double, System.Single, System.Decimal, System.String, or byte array\r\n- Rant types (Review, Reviews): System.String\r\n- System types (FileName, DirectoryPath, CommonFileName, CommonFileExt, CommonUserAgent): System.String\nAll returned values are generated using the Bogus library which ensures realistic, contextually appropriate fake data rather than purely random values. The specific data type and format depends on \r\nthe selected RandomizerType and RandomizerSubType combination, as well as format and pattern parameters applied.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaRandomizedValue -DataType bit\nWill return either a 1 or 0\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaRandomizedValue -DataType int\nWill generate a number between -2147483648 and 2147483647\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaRandomizedValue -RandomizerType Address -RandomizerSubType Zipcode\nGenerates a random zipcode\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaRandomizedValue -RandomizerType Address -RandomizerSubType Zipcode -Format \"#### ##\"\nGenerates a random zipcode like \"1234 56\"\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaRandomizedValue -RandomizerSubType PhoneNumber -Format \"(###) #######\"\nGenerates a random phonenumber like \"(123) 4567890\"", "Description": "Creates realistic fake data by generating random values that match SQL Server data type constraints or using specialized data patterns like names, addresses, and phone numbers.\nThis function is essential for data masking in non-production environments, replacing sensitive production data with believable fake data while maintaining referential integrity and data patterns.\nSupports all major SQL Server data types (varchar, int, datetime, etc.) with proper ranges and formatting, plus hundreds of specialized randomizer types including personal information, financial data, and lorem ipsum text.\nUses the Bogus library to ensure generated data follows realistic patterns rather than simple random character generation.", "Links": "https://dbatools.io/Get-DbaRandomizedValue", "Synopsis": "Generates random data values for SQL Server data types or specialized data patterns for data masking and test data creation", "Availability": "Windows, Linux, macOS", "Params": [ [ "DataType", "Specifies the SQL Server data type for which to generate a random value that matches the type\u0027s constraints and range.\r\nUse this when you need to generate test data that exactly matches your column\u0027s data type, including proper ranges for numeric types and correct formatting for date/time types.\r\nSupported types include bigint, bit, bool, char, date, datetime, datetime2, decimal, int, float, guid, money, numeric, nchar, ntext, nvarchar, real, smalldatetime, smallint, text, time, tinyint, \r\nuniqueidentifier, userdefineddatatype, varchar.", "", false, "false", "", "" ], [ "RandomizerType", "Selects the category of realistic fake data to generate using the Bogus library instead of basic SQL data types.\r\nUse this when you need data that looks realistic for specific domains like names, addresses, or financial information rather than just type-appropriate random values.\r\nAvailable types include Address, Commerce, Company, Database, Date, Finance, Hacker, Hashids, Image, Internet, Lorem, Name, Person, Phone, Random, Rant, System.", "", false, "false", "", "" ], [ "RandomizerSubType", "Defines the specific type of data to generate within a RandomizerType category, such as \u0027FirstName\u0027 under Name or \u0027ZipCode\u0027 under Address.\r\nUse this to get precisely the kind of fake data you need, like generating just phone numbers from the Person category or specific address components.\r\nCan be used alone and the function will automatically determine the appropriate RandomizerType, or combined with RandomizerType for explicit control.", "", false, "false", "", "" ], [ "Min", "Sets the minimum value or length constraint for generated data, such as the shortest string length or smallest numeric value.\r\nUse this to ensure generated data meets your minimum requirements, like ensuring usernames are at least 3 characters or account balances are above zero.\r\nDefaults to 1 for most data types; automatically adjusted to data type limits for numeric types like int or smallint.", "", false, "false", "", "" ], [ "Max", "Sets the maximum value or length constraint for generated data, such as the longest string length or largest numeric value.\r\nUse this to prevent data from exceeding column limits or business rules, like keeping varchar fields under their defined length or amounts under spending limits.\r\nDefaults to 255 for most data types; automatically adjusted to data type limits for numeric types like int or smallint.", "", false, "false", "", "" ], [ "Precision", "Controls the number of decimal places for generated numeric values when using decimal, numeric, real, or float data types.\r\nUse this to match your column\u0027s precision requirements, ensuring generated monetary amounts or measurements have the correct decimal precision.\r\nDefaults to 2 decimal places, which works well for most currency and percentage values.", "", false, "false", "2", "" ], [ "CharacterString", "Defines the character set to use when generating random string data for varchar, char, and similar text data types.\r\nUse this to match specific requirements like alphanumeric-only strings for account codes or excluding certain characters that cause issues in your application.\r\nDefaults to all letters (upper and lower case) and numbers; customize for specific business rules or technical constraints.", "", false, "false", "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", "" ], [ "Format", "Applies custom formatting patterns to generated data, such as phone number formats like \"(###) ###-####\" or ZIP code patterns like \"##### ####\".\r\nUse this to ensure generated data matches your application\u0027s expected format, making masked data look consistent with production patterns.\r\nWorks with randomizer types that support formatting; use # as placeholders that will be replaced with appropriate random digits or characters.", "", false, "false", "", "" ], [ "Symbol", "Adds a prefix symbol to generated numeric values, such as \"$\" for currency amounts or \"%\" for percentages.\r\nUse this when you need formatted output that matches how values are displayed in reports or applications, like generating \"$1,234.56\" instead of just \"1234.56\".\r\nPrimarily used with Finance randomizer types for realistic monetary displays.", "", false, "false", "", "" ], [ "Separator", "Specifies the delimiter character to use in formatted data like MAC addresses, where you can choose between \":\" or \"-\" separators.\r\nUse this to match your network infrastructure\u0027s standard format, ensuring generated MAC addresses use the same separator style as your production environment.\r\nMost commonly used with Internet randomizer types that generate network-related identifiers.", "", false, "false", "", "" ], [ "Value", "Provides the source data for transformation-based randomization methods, particularly when using the \"Shuffle\" subtype to rearrange existing values.\r\nUse this when you want to mask data by scrambling rather than replacing it entirely, preserving some characteristics like character count while making it unrecognizable.\r\nRequired when using RandomizerSubType \"Shuffle\"; the function will randomize the order of characters while preserving commas and decimal points in their original positions.", "", false, "false", "", "" ], [ "Locale", "Controls the cultural context for generated data, affecting formats for names, addresses, phone numbers, and other locale-specific information.\r\nUse this when you need test data that matches your target region\u0027s conventions, such as generating European address formats or non-English names for international applications.\r\nDefaults to \u0027en\u0027 for English; change to other locale codes like \u0027de\u0027, \u0027fr\u0027, or \u0027es\u0027 to generate region-appropriate fake data.", "", false, "false", "en", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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", "Registry" ], "CommandName": "Get-DbaRegistryRoot", "Name": "Get-DbaRegistryRoot", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaRegistryRoot [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance found on the specified computer.\nProperties:\r\n- ComputerName: The computer name of the SQL Server host\r\n- InstanceName: The SQL Server instance name (e.g., \"MSSQLSERVER\" for default instance, or instance name for named instances)\r\n- SqlInstance: The full SQL Server instance name (computer\\instance format, or just computer name for default instance)\r\n- Hive: The Windows registry hive where the instance configuration is stored (always \"HKLM\" for SQL Server)\r\n- Path: The registry path within the hive where the instance stores its configuration (e.g., \"Software\\Microsoft\\Microsoft SQL Server\\MSSQL15.MSSQLSERVER\\Setup\")\r\n- RegistryRoot: The full registry path ready for use with PowerShell registry cmdlets (e.g., \"HKLM:\\Software\\Microsoft\\Microsoft SQL Server\\...\")", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaRegistryRoot\nGets the registry root for all instances on localhost\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaRegistryRoot -ComputerName server1\nGets the registry root for all instances on server1", "Description": "Queries SQL Server WMI to locate the exact Windows registry hive path where each SQL Server instance stores its configuration settings. This eliminates the guesswork when you need to manually edit registry keys for troubleshooting startup issues, modifying trace flags, or automating configuration changes that aren\u0027t exposed through T-SQL or SQL Server Configuration Manager. The function handles both standalone instances and failover cluster instances, returning PowerShell-ready registry paths you can immediately use with Get-ItemProperty or Set-ItemProperty commands.", "Links": "https://dbatools.io/Get-DbaRegistryRoot", "Synopsis": "Discovers Windows registry root paths for SQL Server instances to enable direct registry configuration access", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the target computer where SQL Server instances are installed. Accepts computer names, IP addresses, or SQL Server instance names which will be parsed to extract the computer name.\r\nUse this when you need registry root paths for SQL Server instances on remote servers for configuration troubleshooting or automated registry modifications.", "", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Allows you to login to $ComputerName 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": [ "RegisteredServer", "CMS" ], "CommandName": "Get-DbaRegServer", "Name": "Get-DbaRegServer", "Author": "Bryan Hamby (@galador) | Chrissy LeMaire (@cl)", "Syntax": "Get-DbaRegServer [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Name] \u003cString[]\u003e] [[-ServerName] \u003cString[]\u003e] [[-Pattern] \u003cString[]\u003e] [[-ExcludeServerName] \u003cString[]\u003e] [[-Group] \u003cString[]\u003e] [[-ExcludeGroup] \u003cString[]\u003e] [[-Id] \u003cInt32[]\u003e] [-IncludeSelf] [-ResolveNetworkName] [-IncludeLocal] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "Get-DbaRegisteredServer", "Outputs": "Microsoft.SqlServer.Management.RegisteredServers.RegisteredServer\nReturns one RegisteredServer object per registered SQL Server instance, sourced from Central Management Server, SSMS local registered servers, or Azure Data Studio. Server objects can be sourced from \r\none or more locations:\r\n- Central Management Server (CMS): When SqlInstance parameter is provided\r\n- Local SSMS Registered Servers: When no SqlInstance provided or -IncludeLocal is specified\r\n- Azure Data Studio connections: When no SqlInstance provided or -IncludeLocal is specified\r\n- CMS instance itself: When -IncludeSelf is specified with a CMS query\nDefault display properties (via Select-DefaultView):\r\n- Name: The display name of the registered server as shown in SSMS Registered Servers or Azure Data Studio\r\n- ServerName: The actual SQL Server connection string (computer name, IP address, or instance name)\r\n- Group: The CMS group path (hierarchical, using backslash separators) or null for root-level servers\r\n- Description: Text description of the registered server\r\n- Source: Source location of the registration - \"Central Management Servers\", \"Local Server Groups\", or \"Azure Data Studio\"\nWhen -ResolveNetworkName is specified, additional properties are included in default display:\r\n- ComputerName: NetBIOS computer name resolved via DNS\r\n- FQDN: Fully qualified domain name resolved via DNS\r\n- IPAddress: IP address resolved via DNS\nAdditional available properties from the RegisteredServer object:\r\n- ComputerName: NetBIOS computer name of the CMS instance (for CMS-sourced servers)\r\n- InstanceName: The SQL Server instance name of the CMS (for CMS-sourced servers)\r\n- SqlInstance: The full SQL Server instance name of the CMS (for CMS-sourced servers)\r\n- ParentServer: The parent CMS instance name (for CMS-sourced servers)\r\n- ConnectionString: The connection string with decrypted password if available\r\n- SecureConnectionString: The connection string as a SecureString object if password was decrypted\r\n- Id: Internal identifier for the registered server\r\n- ServerType: Type of server (DatabaseEngine, AnalysisServices, ReportingServices, etc.)\r\n- CredentialPersistenceType: Whether credentials are stored (mainly for Azure Data Studio sources)\nAll properties from the base RegisteredServer SMO object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaRegServer\nGets a list of servers from the local registered servers and azure data studio\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaRegServer -SqlInstance sqlserver2014a\nGets a list of servers from the CMS on sqlserver2014a, using Windows Credentials.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaRegServer -SqlInstance sqlserver2014a -IncludeSelf\nGets a list of servers from the CMS on sqlserver2014a and includes sqlserver2014a in the output results.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaRegServer -SqlInstance sqlserver2014a -SqlCredential $credential | Select-Object -Unique -ExpandProperty ServerName\nReturns only the server names from the CMS on sqlserver2014a, using SQL Authentication to authenticate to the server.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaRegServer -SqlInstance sqlserver2014a -Group HR, Accounting\nGets a list of servers in the HR and Accounting groups from the CMS on sqlserver2014a.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaRegServer -SqlInstance sqlserver2014a -Group HR\\Development\nReturns a list of servers in the HR and sub-group Development from the CMS on sqlserver2014a.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eGet-DbaRegServer -SqlInstance sqlserver2014a -Pattern \"^prod\"\nReturns all registered servers that match the regex pattern \"^prod\" (e.g., prod-server1, production-db) from the CMS on sqlserver2014a.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eGet-DbaRegServer -SqlInstance sqlserver2014a -Group Production -ExcludeServerName \"serverAlfa\", \"ServerBeta\"\nGets a list of servers in the Production group from the CMS on sqlserver2014a, excluding serverAlfa and ServerBeta. Useful when you need to skip specific servers during maintenance windows.", "Description": "Retrieves SQL Server instances from registered server configurations stored in SQL Server Management Studio (SSMS), Azure Data Studio, and Central Management Server (CMS). DBAs use registered servers to organize and quickly connect to multiple SQL Server instances across their environment.\n\nWhen no SqlInstance is specified, returns local registered servers from SSMS and Azure Data Studio. When SqlInstance is provided, connects to that Central Management Server to retrieve its registered server inventory. This is essential for discovering what SQL Server instances are documented and organized in your environment.\n\nLocal Registered Servers and Azure Data Studio support alternative authentication (excluding MFA) but Central Management Server does not.", "Links": "https://dbatools.io/Get-DbaRegServer", "Synopsis": "Retrieves registered SQL Server instances from SSMS, Azure Data Studio, and Central Management Server", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", false, "true (ByValue)", "(Get-DbatoolsConfigValue -FullName \u0027commands.get-dbaregserver.defaultcms\u0027)", "" ], [ "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", "Filters results to registered servers with specific display names as they appear in SSMS Registered Servers pane.\r\nUse this when you need to find servers by their friendly names rather than actual server names.", "", false, "false", "", "" ], [ "ServerName", "Filters results to registered servers with specific server instance names (the actual SQL Server connection strings).\r\nUse this when you need to find servers by their network names or instance names rather than display names.", "", false, "false", "", "" ], [ "Pattern", "Specifies a pattern for filtering registered servers using regular expressions.\r\nUse this when you need to match servers by pattern, such as \"^prod\" or \".*-db$\".\r\nThis parameter supports standard .NET regular expression syntax and matches against both Name and ServerName properties.", "", false, "false", "", "" ], [ "ExcludeServerName", "Excludes registered servers with specific server instance names (the actual SQL Server connection strings).\r\nUse this when you want to retrieve most servers but skip certain instances like those under maintenance or decommissioned.", "ExcludeServer", false, "false", "", "" ], [ "Group", "Filters results to registered servers within specific Central Management Server groups.\r\nSupports hierarchical paths using backslash notation (e.g., \"Production\\Database Servers\"). Use this to target servers organized by environment, department, or function.", "", false, "false", "", "" ], [ "ExcludeGroup", "Excludes registered servers from specific Central Management Server groups.\r\nUse this when you want to retrieve most servers but skip certain groups like \"Test\" or \"Decommissioned\" environments.", "", false, "false", "", "" ], [ "Id", "Filters results to registered servers with specific internal ID numbers.\r\nUse this when you need to retrieve specific servers by their unique identifiers, typically when working with programmatic scripts or automation.", "", false, "false", "", "" ], [ "IncludeSelf", "Includes the Central Management Server instance itself in the results along with all registered servers.\r\nUse this when you need to perform operations on both the CMS and its registered servers in the same workflow.", "", false, "false", "False", "" ], [ "ResolveNetworkName", "Performs DNS lookups to return NetBIOS names, FQDN, and IP addresses for each registered server.\r\nUse this when you need network information for servers, but be aware this adds processing time due to DNS queries.", "", false, "false", "False", "" ], [ "IncludeLocal", "Includes local SSMS and Azure Data Studio registered servers in addition to Central Management Server results.\r\nUse this when querying a CMS but also want to see servers registered locally on your workstation.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027commands.get-dbaregserver.includelocal\u0027)", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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": "Get-DbaRegServerGroup", "Name": "Get-DbaRegServerGroup", "Author": "Tony Wilhelm (@tonywsql)", "Syntax": "Get-DbaRegServerGroup [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Group] \u003cObject[]\u003e] [[-ExcludeGroup] \u003cObject[]\u003e] [[-Id] \u003cInt32[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.RegisteredServers.ServerGroup\nReturns one ServerGroup object for each server group retrieved from the Central Management Server. When querying multiple instances via -SqlInstance, returns one object per matching group per \r\ninstance.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the CMS host (when CMS is database-based)\r\n- InstanceName: The SQL Server instance name of the CMS\r\n- SqlInstance: The full SQL Server instance name in computer\\instance format (when CMS is database-based)\r\n- Name: The name of the server group\r\n- DisplayName: Display name of the server group for UI presentation\r\n- Description: Text description of the group\u0027s purpose or contents\r\n- ServerGroups: Collection of child server groups nested under this group\r\n- RegisteredServers: Collection of registered servers that belong to this group\nWhen querying the local file store (no -SqlInstance specified), ComputerName, InstanceName, and SqlInstance properties are not included in the default display, showing only Name, DisplayName, \r\nDescription, ServerGroups, and RegisteredServers.\nAll properties from the base SMO ServerGroup object are accessible using Select-Object *, including Urn, Parent, and other internal properties.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaRegServerGroup -SqlInstance sqlserver2014a\nGets the top level groups from the CMS on sqlserver2014a, using Windows Credentials.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaRegServerGroup -SqlInstance sqlserver2014a -SqlCredential $credential\nGets the top level groups from the CMS on sqlserver2014a, using alternative credentials to authenticate to the server.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaRegServerGroup -SqlInstance sqlserver2014a -Group HR, Accounting\nGets the HR and Accounting groups from the CMS on sqlserver2014a.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaRegServerGroup -SqlInstance sqlserver2014a -Group HR\\Development\nReturns the sub-group Development of the HR group from the CMS on sqlserver2014a.", "Description": "Returns server group objects from Central Management Server, which are organizational containers that help DBAs manage multiple SQL Server instances in a hierarchical structure. Server groups allow you to categorize registered servers by environment, function, or any logical grouping that makes sense for your infrastructure.\n\nThis function is essential for inventory management and automated administration across multiple SQL Server instances. Use it to discover existing server groups before adding new registered servers, or to build dynamic server lists for bulk operations based on your organizational structure.\n\nThe function supports targeting specific groups by name or path (including nested subgroups), excluding certain groups from results, or filtering by group ID. You can work with both local CMS stores and remote Central Management Server instances.", "Links": "https://dbatools.io/Get-DbaRegServerGroup", "Synopsis": "Retrieves server group objects from SQL Server Central Management Server (CMS) for organized server management.", "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", "", "" ], [ "Group", "Specifies one or more server group names to retrieve from Central Management Server. Supports hierarchical paths using backslash notation (e.g., \u0027Production\\WebServers\u0027).\r\nUse this when you need specific organizational groups rather than all groups, or when working with nested subgroups within your CMS structure.", "", false, "false", "", "" ], [ "ExcludeGroup", "Specifies one or more server group names to exclude from the results. Accepts the same hierarchical path format as the Group parameter.\r\nUse this when you want all groups except certain ones, such as excluding test environments from production operations or removing deprecated groups from inventory reports.", "", false, "false", "", "" ], [ "Id", "Retrieves server groups by their numeric identifier. Note that Id 1 always represents the root DatabaseEngineServerGroup, and this parameter only works for groups that contain registered servers.\r\nUse this when you need to target groups programmatically using their internal CMS identifiers, typically in automated scripts that reference groups by ID rather than 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": [ "RegisteredServer", "CMS" ], "CommandName": "Get-DbaRegServerStore", "Name": "Get-DbaRegServerStore", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaRegServerStore [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.RegisteredServers.RegisteredServersStore\nReturns one RegisteredServersStore object per specified instance. When no -SqlInstance is specified, returns the local file store containing your locally registered servers from SQL Server Management \r\nStudio.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance hosting the CMS\r\n- InstanceName: The SQL Server instance name hosting the CMS\r\n- SqlInstance: The full SQL Server instance name in computer\\instance format\r\n- DatabaseEngineServerGroup: The root server group containing all registered servers and subgroups\r\n- ServerGroups: Collection of top-level server groups\r\n- RegisteredServers: Collection of registered servers at the root level\nProperties excluded from default display (internal/technical properties):\r\n- ServerConnection, DomainInstanceName, DomainName, Urn, Properties, Metadata, Parent, ConnectionContext, PropertyMetadataChanged, PropertyChanged, ParentServer\nAll SMO RegisteredServersStore properties are accessible using Select-Object *, including the excluded properties if needed for advanced operations.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaRegServerStore -SqlInstance sqlserver2014a\nReturns a SQL Server Registered Server Store Object from sqlserver2014a\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaRegServerStore -SqlInstance sqlserver2014a -SqlCredential sqladmin\nReturns a SQL Server Registered Server Store Object from sqlserver2014a by logging in with the sqladmin login", "Description": "Creates a RegisteredServersStore object that serves as the foundation for working with SQL Server Central Management Server (CMS). This object provides access to server groups and registered servers stored in the CMS repository, allowing you to programmatically manage multiple SQL Server instances from a centralized location. When no SqlInstance is specified, it returns the local file store which contains your locally registered servers from SQL Server Management Studio. The returned object can be used with other dbatools CMS commands like Get-DbaRegServer and Get-DbaRegServerGroup to retrieve and manage your registered server configurations.", "Links": "https://dbatools.io/Get-DbaRegServerStore", "Synopsis": "Creates a RegisteredServersStore object for managing Central Management Server configurations", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "Specifies the SQL Server instance hosting the Central Management Server to retrieve the registered server store from.\r\nWhen omitted, returns the local file store containing your locally registered servers from SQL Server Management Studio.\r\nUse this when you need to access server groups and registered servers stored in a centralized CMS repository.", "", 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", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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": [ "repl", "Replication" ], "CommandName": "Get-DbaReplArticle", "Name": "Get-DbaReplArticle", "Author": "Cláudio Silva (@claudioessilva), claudioessilva.eu", "Syntax": "Get-DbaReplArticle [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-Publication] \u003cObject[]\u003e] [[-Schema] \u003cString[]\u003e] [[-Name] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Replication.Article\nReturns one Article object per article found across the specified publications and databases. Each object represents a single replicated object (table, view, or stored procedure) included in a \r\nreplication publication.\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- DatabaseName: The database containing the publication\r\n- PublicationName: The name of the publication containing this article\r\n- Name: The name of the article as it appears in the publication\r\n- Type: The type of object being replicated (Table, View, or StoredProcedure)\r\n- VerticalPartition: Boolean indicating if the article uses vertical partitioning (column filtering)\r\n- SourceObjectOwner: The schema name of the source object in the publisher database\r\n- SourceObjectName: The object name of the source table, view, or stored procedure\nAdditional properties available (use Select-Object * to access all):\r\nAll Microsoft.SqlServer.Replication.Article object properties are accessible, including:\r\n- Destination object properties (DestinationObjectOwner, DestinationObjectName)\r\n- Filter properties for horizontal and vertical partitioning\r\n- Resolver and conflict handling properties\r\n- Subscriber-specific properties and transforms\r\n- Replication-specific metadata about the article\nAll properties from the base SMO Article object are accessible even though only the 10 default properties are displayed without using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaReplArticle -SqlInstance mssql1\nRetrieve information of all articles from all publications on all databases for server mssql1.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaReplArticle -SqlInstance mssql1 -Database pubs\nRetrieve information of all articles from all publications on \u0027pubs\u0027 database for server mssql1.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaReplArticle -SqlInstance mssql1 -Database pubs -Publication PubName\nRetrieve information of all articles from \u0027PubName\u0027 on \u0027pubs\u0027 database for server mssql1.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaReplArticle -SqlInstance mssql1 -Database pubs -Schema sales\nRetrieve information of articles in the \u0027sales\u0027 schema on \u0027pubs\u0027 database for server mssql1.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaReplArticle -SqlInstance mssql1 -Database pubs -Publication PubName -Name sales\nRetrieve information of \u0027sales\u0027 article from \u0027PubName\u0027 on \u0027pubs\u0027 database for server mssql1.", "Description": "Retrieves comprehensive details about articles within SQL Server replication publications, helping DBAs audit and manage replication topology. Articles define which tables, views, or stored procedures are included in a publication for data distribution to subscribers.\n\nThis function examines all accessible databases on the specified instances and returns article properties including name, type, schema, source objects, and partitioning details. Use this when troubleshooting replication issues, documenting replication setup, or verifying which objects are being replicated across your environment.", "Links": "https://dbatools.io/Get-DbaReplArticle", "Synopsis": "Retrieves detailed information about replication articles from SQL Server publications.", "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 examine for replication articles. Only articles from publications in these databases will be returned.\r\nUse this when you need to focus on replication articles within specific databases rather than scanning all databases on the instance.", "", false, "false", "", "" ], [ "Publication", "Filters results to articles within specific replication publications. Only articles from these named publications will be returned.\r\nUse this when troubleshooting a specific publication or when you need to audit articles within particular publications rather than all publications in the database.", "", false, "false", "", "" ], [ "Schema", "Filters articles by the schema of their source objects (tables, views, or procedures). Only articles whose source objects belong to these schemas will be returned.\r\nUse this when you need to examine replication articles for objects within specific schemas, such as when troubleshooting schema-specific replication issues.", "", false, "false", "", "" ], [ "Name", "Filters results to articles with specific names. Only articles matching these exact names will be returned.\r\nUse this when you need to examine specific replication articles by name, such as when troubleshooting issues with particular replicated 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": [ "repl", "Replication" ], "CommandName": "Get-DbaReplArticleColumn", "Name": "Get-DbaReplArticleColumn", "Author": "Cláudio Silva (@claudioessilva), claudioessilva.eu", "Syntax": "Get-DbaReplArticleColumn [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-Publication] \u003cObject[]\u003e] [[-Article] \u003cString[]\u003e] [[-Column] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per column for each matched article, with detailed article and column information added via NoteProperties.\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 containing the publication\r\n- PublicationName: The publication name\r\n- ArticleName: The article name\r\n- ArticleId: The unique identifier for the article\r\n- ColumnName: The name of the column within the article\nAdditional properties available:\r\n- Description: Description of the article\r\n- Type: Type of the article (Table, View, Stored Procedure, etc.)\r\n- VerticalPartition: Boolean indicating if vertical partitioning is enabled\r\n- SourceObjectOwner: Schema owner of the source table\r\n- SourceObjectName: Name of the source table or view", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaReplArticleColumn -SqlInstance sqlserver2019\nRetrieve information of all replicated columns in any publications on server sqlserver2019.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaReplArticleColumn -SqlInstance sqlserver2019 -Database pubs\nRetrieve information of all replicated columns in any publications from the pubs database on server sqlserver2019.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaReplArticleColumn -SqlInstance sqlserver2019 -Publication test\nRetrieve information of all replicated columns in the test publication on server sqlserver2019.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaReplArticleColumn -SqlInstance sqlserver2019 -Database pubs -Publication PubName -Article sales\nRetrieve information of \u0027sales\u0027 article from \u0027PubName\u0027 on \u0027pubs\u0027 database for server sqlserver2019.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaReplArticleColumn -SqlInstance sqlserver2019 -Column state\nRetrieve information for the state column in any publication from any database on server sqlserver2019.", "Description": "Returns detailed information about which columns are included in replication articles, helping DBAs audit replication configurations and troubleshoot column-specific replication issues. This is particularly useful when working with vertical partitioning scenarios where only specific columns from source tables are replicated to subscribers, or when investigating why certain columns aren\u0027t appearing in replicated data.", "Links": "https://dbatools.io/Get-DbaReplArticleColumn", "Synopsis": "Retrieves column-level replication configuration details for SQL Server publication articles.", "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", "Filters results to specific database(s) containing publications. Accepts wildcards for pattern matching.\r\nUse this when you need to focus on replication columns from particular databases rather than scanning all databases on the instance.", "", false, "false", "", "" ], [ "Publication", "Filters results to specific publication(s) within the specified databases. Accepts wildcards for pattern matching.\r\nUse this when auditing column replication configuration for particular publications or troubleshooting column-level issues in specific publications.", "", false, "true (ByValue)", "", "" ], [ "Article", "Filters results to specific article(s) within the publications. Accepts wildcards for pattern matching.\r\nUse this when you need to examine column replication details for particular tables or views that are published as articles.", "", false, "false", "", "" ], [ "Column", "Filters results to specific column name(s) across all matched articles. Case-sensitive exact match.\r\nUse this when investigating whether specific columns are included in replication or troubleshooting missing columns in subscriber 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": "Replication", "CommandName": "Get-DbaReplDistributor", "Name": "Get-DbaReplDistributor", "Author": "William Durkin (@sql_williamd)", "Syntax": "Get-DbaReplDistributor [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "Get-DbaRepDistributor", "Outputs": "Microsoft.SqlServer.Replication.ReplicationServer\nReturns one ReplicationServer object per SQL Server instance with replication configuration and status information.\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- IsPublisher: Boolean indicating if the instance is configured as a replication publisher\r\n- IsDistributor: Boolean indicating if the instance is configured as a replication distributor\r\n- DistributionServer: The name of the server hosting the distribution database (null if not a distributor)\r\n- DistributionDatabase: The name of the distribution database (null if not a distributor)\r\n- DistributorInstalled: Boolean indicating if distributor components are installed on the instance\r\n- DistributorAvailable: Boolean indicating if the distributor is currently available and functional\r\n- HasRemotePublisher: Boolean indicating if the distributor has remote publishers configured\nAdditional properties available from the ReplicationServer object:\r\n- ReplicationDatabases: Collection of databases enabled for replication (not necessarily actively replicated)\r\n- DistributionDatabaseAvailable: Boolean indicating if the distribution database is accessible\r\n- HardwareBoundary: Indicates hardware boundary for replication\r\n- PublisherList: Collection of publishers using this distributor\nUse Select-Object * to access all available properties from the ReplicationServer object.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaReplDistributor -SqlInstance sql2008, sqlserver2012\nRetrieve distributor information for servers sql2008 and sqlserver2012.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eConnect-DbaInstance -SqlInstance mssql1 | Get-DbaReplDistributor\nPipe a SQL Server instance to Get-DbaReplDistributor to retrieve distributor information.", "Description": "Connects to SQL Server instances and retrieves detailed information about their replication distributor configuration, including distributor status, distribution database details, and publisher relationships. This is essential for DBAs managing replication topologies who need to quickly identify which servers act as distributors, where the distribution database is located, and whether remote publishers are configured. The function returns comprehensive distributor properties that help with replication troubleshooting, topology documentation, and configuration audits.", "Links": "https://dbatools.io/Get-DbaReplDistributor", "Synopsis": "Retrieves replication distributor configuration and status information from SQL Server instances.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances to check for replication distributor configuration.\r\nUse this to identify which servers in your environment are configured as distributors, where the distribution database is located, and whether they support remote publishers.", "", 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": [ "repl", "Replication" ], "CommandName": "Get-DbaReplPublication", "Name": "Get-DbaReplPublication", "Author": "Colin Douglas", "Syntax": "Get-DbaReplPublication [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-Name] \u003cString\u003e] [[-Type] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "Get-DbaRepPublication", "Outputs": "Microsoft.SqlServer.Replication.Publication\nReturns one Publication object for each publication found matching the filter criteria. Publications can be of type Transactional, Merge, or Snapshot, and each carries associated articles and \r\nsubscriptions.\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 SQL Server replication server object\r\n- DatabaseName: The name of the database containing the publication\r\n- Name: The name of the publication\r\n- Type: The publication type (Transactional, Merge, or Snapshot)\r\n- Articles: Collection of published articles for this publication\r\n- Subscriptions: Collection of subscriptions to this publication\nAdditional properties available (from SMO Publication object):\r\n- Description: Textual description of the publication\r\n- PubId: Unique identifier for the publication\r\n- Status: Current publication status\r\n- CompatibilityLevel: Earliest SQL Server version supported by this publication\r\n- RetentionPeriod: Number of days before subscription expires\r\n- SnapshotMethod: Data file format of the initial snapshot\r\n- ReplicateDdl: Whether DDL (schema changes) are replicated to subscribers\r\n- HasSubscription: Boolean indicating if the publication has subscriptions\r\n- FtpAddress, FtpPort, FtpSubdirectory: FTP settings for snapshot distribution\r\n- PreSnapshotScript, PostSnapshotScript: Custom scripts executed before/after snapshot application\nAll properties from the base SMO Publication object are accessible using Select-Object * even though only default properties are displayed by default.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaReplPublication -SqlInstance sql2008, sqlserver2012\nReturn all publications for servers sql2008 and sqlserver2012.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaReplPublication -SqlInstance sql2008 -Database TestDB\nReturn all publications on server sql2008 for only the TestDB database\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaReplPublication -SqlInstance sql2008 -Type Transactional\nReturn all transactional publications on server sql2008.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaReplPublication -SqlInstance mssql1 -Name Merge\nReturns the Mergey publications on server mssql1\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eConnect-DbaInstance -SqlInstance mssql1 | Get-DbaReplPublication\nReturns all publications on server mssql1 using the pipeline.", "Description": "Scans SQL Server instances to identify and return all replication publications configured as publishers. This function examines each database\u0027s replication options to locate published databases, then retrieves detailed information about their publications including associated articles and subscriptions. DBAs use this to audit replication topology, troubleshoot publication configuration issues, and document existing replication setup across their environment. Results can be filtered by specific databases, publication names, or publication types to focus on particular replication components.", "Links": "https://dbatools.io/Get-DbaReplPublication", "Synopsis": "Retrieves replication publications from SQL Server instances, including transactional, merge, and snapshot publications.", "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 examine for replication publications. Accepts wildcards and multiple database names.\r\nUse this when you need to focus on specific databases instead of scanning all published databases on the instance.\r\nOnly databases that have replication enabled will return publication information.", "", false, "false", "", "" ], [ "Name", "Filters results to publications with the specified name. Accepts multiple publication names for batch processing.\r\nUse this when you need to check the status or configuration of specific publications rather than viewing all publications in a database.", "", false, "false", "", "" ], [ "Type", "Limits results to specific publication types: Transactional, Merge, or Snapshot.\r\nUse this to focus on a particular replication methodology when troubleshooting or auditing specific replication scenarios.\r\nTransactional publications provide real-time data synchronization, while Merge publications handle bidirectional conflicts and Snapshot publications provide point-in-time data distribution.", "PublicationType", false, "false", "", "Transactional,Merge,Snapshot" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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": [ "repl", "Replication" ], "CommandName": "Get-DbaReplPublisher", "Name": "Get-DbaReplPublisher", "Author": "Mikey Bronowski (@MikeyBronowski), bronowski.it", "Syntax": "Get-DbaReplPublisher [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Replication.DistributionPublisher\nReturns one DistributionPublisher object for each Publisher configured on the distribution server instance. If no publishers are configured, nothing is 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- Status: The current status of the Publisher (e.g., Healthy, Unhealthy)\r\n- WorkingDirectory: Directory path where publication data and schema files are stored\r\n- DistributionDatabase: The name of the distribution database used for this Publisher\r\n- DistributionPublications: Number of transactional publications at the Publisher\r\n- PublisherType: The type of Publisher (e.g., MSSQLSERVER for SQL Server, or third-party identifier)\r\n- Name: The instance name of the Publisher\nAdditional properties available (from SMO DistributionPublisher object):\r\n- PublisherSecurity: Security context for replication agents connecting to the Publisher\r\n- RegisteredSubscribers: Collection of Subscribers registered for this Publisher\u0027s publications\r\n- TransPublications: Collection of transactional publications at the Publisher\r\n- ThirdParty: Boolean indicating if this is a non-SQL Server Publisher\r\n- TrustedDistributorConnection: Boolean indicating if the distributor connection is trusted\r\n- HeterogeneousLogReaderAgentExists: Boolean indicating if a Log Reader Agent job exists\r\n- ConnectionContext: The connection context to the SQL Server instance\r\n- IsExistingObject: Boolean indicating if the object exists on the server\nAll properties from the base SMO DistributionPublisher object are accessible using Select-Object * even though only default properties are displayed by default.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaReplPublisher -SqlInstance mssql1\nGets publisher for the mssql1 instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eConnect-DbaInstance -SqlInstance mssql1 | Get-DbaReplPublisher\nPipes a SQL Server object to get publisher information for the mssql1 instance.", "Description": "Retrieves detailed information about SQL Server replication publishers configured on distribution servers. This function connects to instances acting as distributors and returns publisher details including status, working directory, distribution database, and publication counts. Use this to audit replication topology, troubleshoot publisher connectivity issues, or verify publisher configurations across your replication environment.", "Links": "https://dbatools.io/Get-DbaReplPublisher", "Synopsis": "Retrieves SQL Server replication publisher configuration and status from distribution servers.", "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": "Replication", "CommandName": "Get-DbaReplServer", "Name": "Get-DbaReplServer", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaReplServer [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "Get-DbaRepServer", "Outputs": "Microsoft.SqlServer.Replication.ReplicationServer\nReturns one ReplicationServer object per SQL Server instance, providing information about the instance\u0027s role in the replication topology.\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 if the instance is configured as a Distributor\r\n- IsPublisher: Boolean indicating if the instance is configured as a Publisher\r\n- DistributionServer: The name of the Distributor server (if configured)\r\n- DistributionDatabase: The name of the distribution database (if configured)\nAdditional properties available (from SMO ReplicationServer object):\r\n- DistributorInstalled: Boolean indicating if a Distributor is installed\r\n- DistributorAvailable: Boolean indicating if the Distributor is accessible\r\n- WorkingDirectory: The Publisher\u0027s working directory location\r\n- DistributionDatabases: Collection of configured distribution databases\r\n- DistributionPublishers: Collection of Publishers using this Distributor\r\n- ReplicationDatabases: Collection of databases enabled for replication\r\n- RegisteredSubscribers: Collection of registered Subscriber instances\r\n- AgentCheckupInterval: The Distribution Agent checkup frequency setting\r\n- ConnectionContext: The SQL Server connection context object\nAll properties from the base SMO ReplicationServer object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaReplServer -SqlInstance sql2016\nGets the replication server object for sql2016 using Windows authentication\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaReplServer -SqlInstance sql2016 -SqlCredential repadmin\nGets the replication server object for sql2016 using SQL authentication", "Description": "Returns a ReplicationServer object that shows whether each SQL Server instance is configured as a distributor, publisher, or both in the replication topology. This helps DBAs quickly identify server roles and distribution database configurations when troubleshooting replication issues or documenting replication environments. The function reveals which databases are enabled for replication, though these may not necessarily be actively replicated.\n\nNote: The ReplicationDatabases property gets the databases enabled for replication in the connected instance of Microsoft SQL Server/.\nNot necessarily the databases that are actually replicated.", "Links": "https://dbatools.io/Get-DbaReplServer", "Synopsis": "Retrieves replication configuration and server role 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", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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": [ "repl", "Replication" ], "CommandName": "Get-DbaReplSubscription", "Name": "Get-DbaReplSubscription", "Author": "Jess Pomfret (@jpomfret), jesspomfret.com", "Syntax": "Get-DbaReplSubscription [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-PublicationName] \u003cString[]\u003e] [[-SubscriberName] \u003cDbaInstanceParameter[]\u003e] [[-SubscriptionDatabase] \u003cObject[]\u003e] [[-Type] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Replication.Subscription\nReturns one Subscription object per subscription found across all qualifying publications. Each object represents a replication relationship between a publisher and subscriber, showing subscription \r\ndetails, delivery method, and synchronization information.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance (publisher)\r\n- InstanceName: The SQL Server instance name (publisher)\r\n- SqlInstance: The full SQL Server instance name (computer\\instance) for the publisher\r\n- DatabaseName: The name of the publication database on the publisher\r\n- PublicationName: The name of the publication being subscribed to\r\n- Name: The name of the subscription\r\n- SubscriberName: The name of the Subscriber instance receiving replicated data\r\n- SubscriptionDBName: The name of the database on the Subscriber receiving the data\r\n- SubscriptionType: The type of subscription delivery (Push or Pull)\nAdditional properties available (from SMO Subscription object):\r\n- AgentJobId: The unique identifier of the agent job used for subscription synchronization\r\n- AgentSchedule: The schedule for the synchronization agent job execution\r\n- SynchronizationAgentName: The name of the synchronization agent job\r\n- Status: The current status of the subscription (Active, Inactive, Uninitialized, etc.)\r\n- SyncType: The manner in which the subscription is initialized (Automatic, None, Replicating)\r\n- SubscriberSecurity: The security context for Subscriber connections\r\n- SynchronizationAgentProcessSecurity: The Windows account credentials for the agent process\nAll properties from the base SMO Subscription object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaReplSubscription -SqlInstance mssql1\nReturn all subscriptions for all publications on server mssql1.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaReplSubscription -SqlInstance mssql1 -Database TestDB\nReturn all subscriptions for all publications on server mssql1 for only the TestDB database.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaReplSubscription -SqlInstance mssql1 -PublicationName Mergey\nReturn all subscriptions for the publication Mergey on server mssql1.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaReplSubscription -SqlInstance mssql1 -Type Push\nReturn all subscriptions for all transactional publications on server mssql1.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaReplSubscription -SqlInstance mssql1 -SubscriberName mssql2\nReturn all subscriptions for all publications on server mssql1 where the subscriber is mssql2.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaReplSubscription -SqlInstance mssql1 -SubscriptionDatabase TestDB\nReturn all subscriptions for all publications on server mssql1 where the subscription database is TestDB.", "Description": "Retrieves detailed information about replication subscriptions, showing which subscriber instances are receiving data from publications. This is essential for monitoring replication topology, troubleshooting subscription issues, and auditing data distribution across your SQL Server environment. You can filter results by database, publication name, subscriber instance, subscription database, or subscription type (Push/Pull) to focus on specific replication relationships.", "Links": "https://dbatools.io/Get-DbaReplSubscription", "Synopsis": "Retrieves SQL Server replication subscription details for publications across 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 publication databases to include when retrieving subscriptions. Accepts multiple database names and wildcards.\r\nUse this to focus on subscriptions from specific databases instead of checking all replicated databases on the instance.", "", false, "false", "", "" ], [ "PublicationName", "Filters results to subscriptions from specific publications by name. Accepts multiple publication names.\r\nUse this when you need to check subscription status for particular publications rather than all publications on the server.", "", false, "false", "", "" ], [ "SubscriberName", "Filters results to subscriptions where data is being delivered to specific subscriber instances. Accepts multiple instance names.\r\nUse this to monitor subscription health and activity for particular subscriber servers in your replication topology.", "", false, "false", "", "" ], [ "SubscriptionDatabase", "Filters results to subscriptions where data is being delivered to specific databases on subscriber instances. Accepts multiple database names.\r\nUse this to track how data flows to particular databases across your subscribers, especially when subscription databases have different names than source databases.", "", false, "false", "", "" ], [ "Type", "Filters results to subscriptions of a specific delivery method (Push or Pull). Push subscriptions are managed by the publisher, while Pull subscriptions are managed by the subscriber.\r\nUse this to separate subscription management tasks or troubleshoot issues specific to push or pull delivery mechanisms.", "PublicationType", false, "false", "", "Push,Pull" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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": "ResourceGovernor", "CommandName": "Get-DbaResourceGovernor", "Name": "Get-DbaResourceGovernor", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaResourceGovernor [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.ResourceGovernor\nReturns one ResourceGovernor object per instance. The object represents the Resource Governor configuration and includes properties for enabled status, classifier function configuration, and resource \r\npool management.\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- ClassifierFunction: The fully qualified name of the Resource Governor classifier function (e.g., [dbo].[fn_classifier])\r\n- Enabled: Boolean indicating if Resource Governor is enabled on the instance\r\n- MaxOutstandingIOPerVolume: Maximum number of outstanding I/O operations allowed per disk volume\r\n- ReconfigurePending: Boolean indicating if a Resource Governor configuration change is pending and requires ALTER RESOURCE GOVERNOR RECONFIGURE\r\n- ResourcePools: Collection of ResourcePool objects defined on the instance\r\n- ExternalResourcePools: Collection of ExternalResourcePool objects for machine learning workloads (SQL Server 2016+)\nAdditional properties available (from SMO ResourceGovernor object):\r\n- Parent: Reference to the parent Server object\r\n- State: Current state of the SMO object (Existing, Creating, Pending, etc.)\r\n- Urn: The unified resource name for the ResourceGovernor object\nAll properties from the base SMO ResourceGovernor object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaResourceGovernor -SqlInstance sql2016\nGets the resource governor object of the SqlInstance sql2016\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Get-DbaResourceGovernor\nGets the resource governor object on Sql1 and Sql2/sqlexpress instances", "Description": "Retrieves the Resource Governor object containing configuration details, enabled status, and associated resource pools. Resource Governor allows DBAs to manage SQL Server workload and resource consumption by setting limits on CPU, memory, and I/O usage for different workloads. This function helps you quickly check if Resource Governor is enabled, view classifier functions, and examine current resource pool configurations without writing custom T-SQL queries.", "Links": "https://dbatools.io/Get-DbaResourceGovernor", "Synopsis": "Retrieves Resource Governor configuration and status 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": [ "Migration", "ResourceGovernor" ], "CommandName": "Get-DbaRgClassifierFunction", "Name": "Get-DbaRgClassifierFunction", "Author": "Alessandro Alpi (@suxstellino), alessandroalpi.blog", "Syntax": "Get-DbaRgClassifierFunction [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-InputObject] \u003cResourceGovernor[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.UserDefinedFunction\nReturns one UserDefinedFunction object representing the Resource Governor classifier function. The classifier function is always stored in the master database and is used by Resource Governor to \r\nassign incoming connections to appropriate workload groups.\nIf no classifier function is configured on the instance, nothing is 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 the function (always \u0027master\u0027 for classifier functions)\r\n- Schema: The schema name containing the classifier function\r\n- CreateDate: DateTime when the classifier function was created\r\n- DateLastModified: DateTime when the classifier function was last modified\r\n- Name: The name of the classifier function\r\n- DataType: The return data type of the function (should be nvarchar for classifier functions)\nAdditional properties available (from SMO UserDefinedFunction object):\r\n- AssemblyName: Name of the CLR assembly if this is a CLR function\r\n- FunctionType: Type of function (Scalar, Table, or Inline)\r\n- ImplementationType: Implementation type (TransactSql or SqlClr)\r\n- IsBuiltIn: Boolean indicating if this is a system function\r\n- IsEditing: Boolean indicating if the function is being edited\r\n- IsSystemObject: Boolean indicating if the function is a system object\r\n- Urn: The unified resource name for the function object\r\n- State: Current state of the SMO object (Existing, Creating, Pending, etc.)\nAll properties from the base SMO UserDefinedFunction object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaRgClassifierFunction -SqlInstance sql2016\nGets the classifier function from sql2016\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Get-DbaResourceGovernor | Get-DbaRgClassifierFunction\nGets the classifier function object on Sql1 and Sql2/sqlexpress instances", "Description": "Retrieves the custom classifier function that Resource Governor uses to determine which workload group incoming connections are assigned to. The classifier function contains the business logic that evaluates connection properties (like login name, application name, or host name) and returns the appropriate workload group name. This function is always stored in the master database and is essential for understanding how Resource Governor categorizes and manages SQL Server workloads.", "Links": "https://dbatools.io/Get-DbaRgClassifierFunction", "Synopsis": "Retrieves the Resource Governor classifier function configured for workload group assignment", "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 Resource Governor objects piped from Get-DbaResourceGovernor.\r\nUse this when processing multiple instances or when you already have Resource Governor objects to work with, allowing for efficient pipeline 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": "ResourceGovernor", "CommandName": "Get-DbaRgResourcePool", "Name": "Get-DbaRgResourcePool", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaRgResourcePool [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Type] \u003cString\u003e] [[-InputObject] \u003cResourceGovernor[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.ResourcePool (Internal pools) or Microsoft.SqlServer.Management.Smo.ExternalResourcePool (External pools)\nReturns one ResourcePool or ExternalResourcePool object per resource pool found on the instance. The object type depends on the -Type parameter:\r\n- Type \"Internal\" (default): Returns Microsoft.SqlServer.Management.Smo.ResourcePool objects\r\n- Type \"External\": Returns Microsoft.SqlServer.Management.Smo.ExternalResourcePool 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\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Id: Unique identifier for the resource pool\r\n- Name: Name of the resource pool\r\n- CapCpuPercentage: CPU cap percentage (0-100 for External pools, always 0 for Internal pools)\r\n- IsSystemObject: Boolean indicating if this is a system-defined resource pool\r\n- MaximumCpuPercentage: Maximum CPU percentage allocated to this pool (0-100)\r\n- MaximumIopsPerVolume: Maximum I/O operations per second per volume (External pools only)\r\n- MaximumMemoryPercentage: Maximum memory percentage allocated to this pool (0-100)\r\n- MinimumCpuPercentage: Minimum CPU percentage reserved for this pool (0-100)\r\n- MinimumIopsPerVolume: Minimum I/O operations per second per volume (External pools only)\r\n- MinimumMemoryPercentage: Minimum memory percentage reserved for this pool (0-100)\r\n- WorkloadGroups: Collection of workload groups associated with this resource pool\nAdditional properties available (from SMO ResourcePool or ExternalResourcePool objects):\r\n- CreateDate: DateTime when the resource pool was created\r\n- ModifyDate: DateTime when the resource pool was last modified\r\n- Parent: Reference to the parent ResourceGovernor object\r\n- State: Current state of the resource pool object (Existing, Creating, Pending, etc.)\nAll properties from the base SMO object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaRgResourcePool -SqlInstance sql2016\nGets the internal resource pools on sql2016\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Get-DbaResourceGovernor | Get-DbaRgResourcePool\nGets the internal resource pools on Sql1 and Sql2/sqlexpress instances\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Get-DbaResourceGovernor | Get-DbaRgResourcePool -Type External\nGets the external resource pools on Sql1 and Sql2/sqlexpress instances", "Description": "Retrieves detailed information about SQL Server Resource Governor resource pools, including both internal (CPU/memory) and external (R/Python) pools. Shows current configuration settings for minimum and maximum CPU percentages, memory percentages, and IOPS limits per volume. Essential for monitoring resource allocation, troubleshooting performance bottlenecks, and auditing resource governance policies across your SQL Server instances.", "Links": "https://dbatools.io/Get-DbaRgResourcePool", "Synopsis": "Retrieves SQL Server Resource Governor resource pools with their CPU, memory, and IOPS configuration 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", "", "" ], [ "Type", "Specifies whether to retrieve Internal resource pools (CPU/memory) or External resource pools (R/Python services).\r\nInternal pools control SQL Server workloads, while External pools govern Machine Learning Services resource consumption.", "", false, "false", "Internal", "Internal,External" ], [ "InputObject", "Accepts Resource Governor objects from Get-DbaResourceGovernor for pipeline processing.\r\nUse this when you need to filter or process resource pools from multiple instances collected earlier in your script.", "", 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": "ResourceGovernor", "CommandName": "Get-DbaRgWorkloadGroup", "Name": "Get-DbaRgWorkloadGroup", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaRgWorkloadGroup [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-InputObject] \u003cResourcePool[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.WorkloadGroup\nReturns one WorkloadGroup object per workload group found in the specified resource pools. Each workload group object includes configuration settings for resource consumption limits and request \r\nhandling behavior.\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 workload group\r\n- Name: Name of the workload group\r\n- ExternalResourcePoolName: Name of the associated external resource pool (if applicable)\r\n- GroupMaximumRequests: Maximum number of concurrent requests allowed in the workload group (0 = unlimited)\r\n- Importance: Importance level of requests in this group (Low, Medium, High)\r\n- IsSystemObject: Boolean indicating if this is a system-defined workload group\r\n- MaximumDegreeOfParallelism: Maximum number of processors for parallel query execution (0 = unlimited)\r\n- RequestMaximumCpuTimeInSeconds: Maximum CPU time in seconds per request (0 = unlimited)\r\n- RequestMaximumMemoryGrantPercentage: Maximum memory grant as percentage of resource pool memory\r\n- RequestMemoryGrantTimeoutInSeconds: Timeout in seconds for memory grant requests\nAdditional properties available (from SMO WorkloadGroup object):\r\n- ClassifierFunction: Name of the scalar classifier function (if any)\r\n- CreateDate: DateTime when the workload group was created\r\n- ModifyDate: DateTime when the workload group was last modified\r\n- Parent: Reference to the parent ResourcePool object\r\n- State: Current state of the workload group object\nAll properties from the base SMO object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaRgWorkloadGroup -SqlInstance sql2017\nGets the workload groups on sql2017\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaResourceGovernor -SqlInstance sql2017 | Get-DbaRgResourcePool | Get-DbaRgWorkloadGroup\nGets the workload groups on sql2017", "Description": "Retrieves Resource Governor workload groups along with their configuration settings including CPU limits, memory grants, and parallelism controls. Workload groups define how resource requests are classified and managed within resource pools, allowing DBAs to control resource consumption for different types of workloads. This function is essential for monitoring and troubleshooting Resource Governor configurations to ensure optimal performance isolation between competing workloads.", "Links": "https://dbatools.io/Get-DbaRgWorkloadGroup", "Synopsis": "Retrieves Resource Governor workload groups from SQL Server instances", "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", "", "" ], [ "InputObject", "Accepts resource pool objects from Get-DbaRgResourcePool to retrieve workload groups from specific pools only.\r\nUse this to filter workload groups when you need to examine groups within particular resource pools instead of all workload groups across the 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": [ "Agent", "Job" ], "CommandName": "Get-DbaRunningJob", "Name": "Get-DbaRunningJob", "Author": "Stephen Bennett, sqlnotesfromtheunderground.wordpress.com", "Syntax": "Get-DbaRunningJob [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-InputObject] \u003cJob[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Agent.Job\nReturns one Job object for each SQL Server Agent job that is currently executing (not in Idle state).\r\nWhen no jobs are running, the command returns nothing.\nDefault display properties (via Get-DbaAgentJob with 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 format)\r\n- Name: The name of the Agent job\r\n- CurrentRunStatus: Current execution status (Executing, Idle, Suspended, etc.)\r\n- IsEnabled: Boolean indicating if the job is enabled\r\n- LastRunOutcome: Result of the most recent execution (Succeeded, Failed, Cancelled, etc.)\r\n- LastRunDate: DateTime of the most recent job execution\r\n- NextRunDate: DateTime scheduled for the next execution\r\n- Owner: The login that owns the job\r\n- CreateDate: DateTime when the job was created\r\n- Description: Text description of the job\u0027s purpose\nAdditional properties available from the base SMO Agent.Job object via Select-Object *:\r\n- JobID: Unique identifier (GUID) for the job\r\n- EventLogLevel: Logging level for event log (Never, OnSuccess, OnFailure, Always)\r\n- EmailLevel: Email notification level (Never, OnSuccess, OnFailure, Always)\r\n- NetSendLevel: Network send notification level (Never, OnSuccess, OnFailure, Always)\r\n- NetsendOperatorName: Name of operator for network send notifications\r\n- EmailOperatorName: Name of operator for email notifications\r\n- OperatorToNetSend: Operator configured for network send notifications\r\n- StartStepID: Step number where execution begins\r\n- Category: The category/classification of the job\r\n- DeleteLevel: When to delete job history (Never, OnSuccess, OnFailure, Always)\r\n- TargetServers: Collection of target servers for multi-server jobs\r\n- HasSchedule: Boolean indicating if the job has any schedules assigned\nAll properties from the base SMO Agent.Job object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaRunningJob -SqlInstance sql2017\nReturns any active jobs on sql2017\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgentJob -SqlInstance sql2017, sql2019 | Get-DbaRunningJob\nReturns all active jobs on multiple instances piped into the function.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$servers | Get-DbaRunningJob\nReturns all active jobs on multiple instances piped into the function.", "Description": "This function returns SQL Server Agent jobs that are actively running at the moment you call it, filtering out any jobs in idle state.\nUse this to monitor job execution during maintenance windows, troubleshoot performance issues by identifying resource-consuming jobs, or verify that no jobs are running before performing maintenance operations.\nThe function refreshes job status information to provide real-time execution details rather than cached data.", "Links": "https://dbatools.io/Get-DbaRunningJob", "Synopsis": "Retrieves SQL Server Agent jobs that are currently executing", "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", "", "" ], [ "InputObject", "Accepts SQL Server Agent job objects piped from Get-DbaAgentJob for filtering to only running jobs.\r\nUse this when you need to check execution status on a specific set of jobs rather than all jobs on an 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": [ "Trace", "Changes", "Database", "Utility" ], "CommandName": "Get-DbaSchemaChangeHistory", "Name": "Get-DbaSchemaChangeHistory", "Author": "Stuart Moore (@napalmgram), stuart-moore.com", "Syntax": "Get-DbaSchemaChangeHistory [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-Since] \u003cDbaDateTime\u003e] [[-Object] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per DDL change (CREATE, DROP, or ALTER operation) found in the SQL Server default system trace.\r\nWhen no schema changes are found matching the filter criteria, the command returns nothing.\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- DatabaseName: The database in which the schema change occurred\r\n- DateModified: DateTime when the DDL operation was executed\r\n- LoginName: The login name (SQL or Windows) that executed the change\r\n- UserName: The Windows user name (domain\\username format) if using Windows Authentication, or SQL login name\r\n- ApplicationName: The application or tool that executed the DDL (e.g., \"SQL Server Management Studio\", \"sqlcmd\")\r\n- DDLOperation: Type of operation performed - \u0027Create\u0027 for CREATE statements, \u0027Drop\u0027 for DROP statements, \u0027Alter\u0027 for ALTER statements\r\n- Object: The name of the database object that was created, dropped, or altered (table, procedure, view, etc.)\r\n- ObjectType: The type of database object affected (Table, StoredProcedure, View, Index, Trigger, UserDefinedFunction, etc.)\nAll properties are strings except DateModified which is DateTime. The ObjectType may be \"Unknown\" if the specific object type cannot be determined from the trace data.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaSchemaChangeHistory -SqlInstance localhost\nReturns all DDL changes made in all databases on the SQL Server instance localhost since the system trace began\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaSchemaChangeHistory -SqlInstance localhost -Since (Get-Date).AddDays(-7)\nReturns all DDL changes made in all databases on the SQL Server instance localhost in the last 7 days\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaSchemaChangeHistory -SqlInstance localhost -Database Finance, Prod -Since (Get-Date).AddDays(-7)\nReturns all DDL changes made in the Prod and Finance databases on the SQL Server instance localhost in the last 7 days\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaSchemaChangeHistory -SqlInstance localhost -Database Finance -Object AccountsTable -Since (Get-Date).AddDays(-7)\nReturns all DDL changes made to the AccountsTable object in the Finance database on the SQL Server instance localhost in the last 7 days", "Description": "Queries the default system trace to track CREATE, DROP, and ALTER operations performed on database objects, providing a complete audit trail of schema modifications. This helps DBAs identify who made changes, when they occurred, and which objects were affected without needing to manually parse trace files or enable custom auditing. Returns detailed information including login names, timestamps, application sources, and operation types for compliance reporting and troubleshooting. Only works with SQL Server 2005 and later, as the system trace didn\u0027t exist before then.", "Links": "https://dbatools.io/Get-DbaSchemaChangeHistory", "Synopsis": "Retrieves DDL change history from the SQL Server default system 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 include when searching for schema changes. Accepts multiple database names and 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 schema change search. Accepts multiple database names for filtering out unwanted databases.\r\nUse this to skip system databases, test databases, or any databases you don\u0027t want included in the change history results.", "", false, "false", "", "" ], [ "Since", "Filters results to show only DDL changes that occurred after the specified date and time. Accepts standard PowerShell date formats.\r\nUse this to focus on recent changes or changes within a specific time period, especially helpful for troubleshooting recent issues or compliance reporting.", "", false, "false", "", "" ], [ "Object", "Specifies the names of specific database objects to search for in the change history. Accepts multiple object names for targeted searches.\r\nUse this when investigating changes to particular tables, views, stored procedures, or other database objects rather than reviewing all schema changes.", "", 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": "Role", "CommandName": "Get-DbaServerRole", "Name": "Get-DbaServerRole", "Author": "Shawn Melton (@wsmelton)", "Syntax": "Get-DbaServerRole [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-ServerRole] \u003cString[]\u003e] [[-ExcludeServerRole] \u003cString[]\u003e] [-ExcludeFixedRole] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.ServerRole\nReturns one ServerRole object per server-level role on the specified SQL Server instance. For example, querying a standard SQL Server instance returns multiple objects - one for each fixed role \r\n(sysadmin, serveradmin, dbcreator, etc.) plus any custom user-defined server roles.\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- Role: The name of the server role (same as Name property)\r\n- Login: Array of login names that are members of this role\r\n- Owner: The principal that owns the server role\r\n- IsFixedRole: Boolean indicating if this is a built-in fixed role (sysadmin, serveradmin, etc.) or a custom user-defined role\r\n- DateCreated: DateTime when the role was created\r\n- DateModified: DateTime when the role was last modified\nAdditional properties available (from SMO ServerRole object):\r\n- Name: The name of the server role\r\n- Urn: The Uniform Resource Name of the server role object\r\n- Properties: Collection of property objects for the role\r\n- State: Current state of the SMO object (Existing, Creating, Pending, etc.)\nAll properties from the base SMO ServerRole object are accessible using Select-Object * even though only default properties are displayed without using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaServerRole -SqlInstance sql2016a\nOutputs list of server-level roles for sql2016a instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaServerRole -SqlInstance sql2017a -ExcludeFixedRole\nOutputs the server-level role(s) that are not fixed roles on sql2017a instance.", "Description": "Retrieves all server-level security roles from SQL Server instances, including role members, creation dates, and ownership details. This function helps DBAs audit server-level permissions, identify role membership for compliance reporting, and distinguish between built-in fixed roles (like sysadmin, serveradmin) and custom user-defined roles. Supports filtering to specific roles or excluding fixed roles to focus on custom security configurations.", "Links": "https://dbatools.io/Get-DbaServerRole", "Synopsis": "Retrieves server-level security roles and their members from SQL Server instances.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. 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", "", "" ], [ "ServerRole", "Specifies one or more server-level roles to include in the results. Accepts role names like \u0027sysadmin\u0027, \u0027dbcreator\u0027, or custom role names.\r\nUse this when you need to audit specific roles rather than retrieving all server roles from the instance.", "", false, "false", "", "" ], [ "ExcludeServerRole", "Specifies one or more server-level roles to exclude from the results. Useful for filtering out roles you don\u0027t need to audit.\r\nCommonly used to exclude built-in roles like \u0027public\u0027 when focusing on administrative roles with elevated permissions.", "", false, "false", "", "" ], [ "ExcludeFixedRole", "Excludes built-in fixed server roles from the results, showing only custom user-defined server roles.\r\nUse this when auditing custom security configurations or identifying roles created by your organization rather than SQL Server\u0027s default roles.", "", 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": [ "Role", "Login" ], "CommandName": "Get-DbaServerRoleMember", "Name": "Get-DbaServerRoleMember", "Author": "Klaas Vandenberghe (@PowerDBAKlaas)", "Syntax": "Get-DbaServerRoleMember [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-ServerRole] \u003cString[]\u003e] [[-ExcludeServerRole] \u003cString[]\u003e] [[-Login] \u003cObject[]\u003e] [-ExcludeFixedRole] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per login that is a member of server-level roles on the specified SQL Server instance(s). For example, if the sysadmin role has three member logins and the dbcreator role has two \r\nmember logins, four objects are returned total (one for each unique role-login combination when filtering by -Login parameter, or multiple objects per member if they belong to multiple roles).\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- Role: The name of the server role (sysadmin, dbcreator, securityadmin, or custom role name)\r\n- Name: The login name that is a member of the role\r\n- SmoRole: The SMO ServerRole object representing the role - allows access to all ServerRole properties and methods for further analysis\r\n- SmoLogin: The SMO Login object representing the login - allows access to all Login properties and methods for further analysis\nOutput quantity note:\r\nWhen a login is a member of multiple roles, one object is returned per role-login combination. For example, if \u0027sa\u0027 is a member of both sysadmin and securityadmin roles, two objects are returned - \r\none for each role membership.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaServerRoleMember -SqlInstance localhost\nReturns all members of all server roles on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaServerRoleMember -SqlInstance localhost, sql2016\nReturns all members of all server 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-DbaServerRoleMember\nReturns all members of all server roles for every server in C:\\servers.txt\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaServerRoleMember -SqlInstance localhost -ServerRole \u0027sysadmin\u0027, \u0027dbcreator\u0027\nReturns all members of the sysadmin or dbcreator roles on localhost.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaServerRoleMember -SqlInstance localhost -ExcludeServerRole \u0027sysadmin\u0027\nReturns all members of server-level roles other than sysadmin.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaServerRoleMember -SqlInstance sql2017a -ExcludeFixedRole\nReturns all members of server-level role(s) that are not fixed roles on sql2017a instance.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eGet-DbaServerRoleMember -SqlInstance localhost -Login \u0027MyFriendlyDeveloper\u0027\nReturns all server-level role(s) for the MyFriendlyDeveloper login on localhost.", "Description": "Returns detailed information about which logins are members of server-level roles like sysadmin, dbcreator, and securityadmin. Essential for security audits, compliance reviews, and troubleshooting permission issues. Shows both the role assignments and provides access to the underlying SMO objects for further analysis. Supports filtering by specific roles or logins to focus on particular security concerns.", "Links": "https://dbatools.io/Get-DbaServerRoleMember", "Synopsis": "Retrieves server-level role memberships for security auditing 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.", "Credential", false, "false", "", "" ], [ "ServerRole", "Specifies which server roles to check for membership. Accepts role names like \u0027sysadmin\u0027, \u0027dbcreator\u0027, \u0027securityadmin\u0027, or custom server roles.\r\nUse this when you need to focus your audit on specific high-privilege roles or investigate particular security concerns.", "", false, "false", "", "" ], [ "ExcludeServerRole", "Excludes specified server roles from the membership report. Useful when you want to see all role memberships except certain roles.\r\nCommonly used to exclude low-privilege roles like \u0027public\u0027 when focusing on elevated permissions during security reviews.", "", false, "false", "", "" ], [ "Login", "Filters results to show only server role memberships for specific logins. Accepts login names including Windows accounts, SQL logins, and service accounts.\r\nUse this when investigating permissions for particular users or troubleshooting access issues for specific accounts.", "", false, "false", "", "" ], [ "ExcludeFixedRole", "Excludes built-in server roles like sysadmin, securityadmin, and dbcreator, showing only custom server roles created by your organization.\r\nOnly available on SQL Server 2017 and later which supports user-defined server roles. Use this to audit custom role assignments in environments with specialized security models.", "", 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", "SqlServer", "Instance", "Connect" ], "CommandName": "Get-DbaService", "Name": "Get-DbaService", "Author": "Klaas Vandenberghe (@PowerDbaKlaas)", "Syntax": "Get-DbaService [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [-InstanceName \u003cString[]\u003e] [-SqlInstance \u003cDbaInstanceParameter[]\u003e] [-Credential \u003cPSCredential\u003e] [-Type \u003cString[]\u003e] [-AdvancedProperties] [-EnableException] [\u003cCommonParameters\u003e]\nGet-DbaService [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [-Credential \u003cPSCredential\u003e] [-ServiceName \u003cString[]\u003e] [-AdvancedProperties] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Wmi.SqlService\nReturns one service object per SQL Server-related Windows service found on the target computer(s). Each service object includes properties for service name, status, startup mode, and service account \r\ninformation.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The name of the computer hosting the service\r\n- ServiceName: The Windows service name (e.g., MSSQLSERVER, SQLSERVERAGENT)\r\n- ServiceType: The type of SQL Server service (Engine, Agent, FullText, SSIS, SSAS, SSRS, Browser, PolyBase, Launchpad, Unknown)\r\n- InstanceName: The SQL Server instance name associated with the service\r\n- DisplayName: The friendly display name of the service\r\n- StartName: The user account under which the service runs\r\n- State: The current state of the service (Stopped, Start Pending, Stop Pending, Running)\r\n- StartMode: The startup mode of the service (Unknown, Automatic, Manual, Disabled)\nWhen -AdvancedProperties is specified, additional properties are included:\r\n- Version: The SQL Server version number of the service\r\n- SPLevel: The service pack level installed on the service\r\n- SkuName: The SQL Server edition/SKU name (e.g., Enterprise, Standard)\r\n- Clustered: Boolean (as numeric or empty) indicating if the service is part of a cluster\r\n- VSName: The virtual server name if the service is clustered\r\n- SqlInstance: The full SQL instance name (including virtual server name if clustered) for engine services\nScriptMethods (callable on returned objects):\r\n- Stop([bool]$Force): Stops the service, with optional force parameter\r\n- Start(): Starts the service\r\n- Restart([bool]$Force): Restarts the service, with optional force parameter\r\n- ChangeStartMode([string]$Mode): Changes the startup mode (Automatic, Manual, Disabled)\nAll service objects support Get-Member to view additional properties from the underlying WMI SqlService class.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaService -ComputerName sqlserver2014a\nGets the SQL Server related services on computer sqlserver2014a.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027sql1\u0027,\u0027sql2\u0027,\u0027sql3\u0027 | Get-DbaService -AdvancedProperties\nGets the SQL Server related services on computers sql1, sql2 and sql3. Includes Advanced Properties from the SqlServiceAdvancedProperty Namespace\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$cred = Get-Credential WindowsUser\nPS C:\\\u003e Get-DbaService -ComputerName sql1,sql2 -Credential $cred | Out-GridView\nGets the SQL Server related services on computers sql1 and sql2 via the user WindowsUser, and shows them in a grid view.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaService -ComputerName sql1,sql2 -InstanceName MSSQLSERVER\nGets the SQL Server related services related to the default instance MSSQLSERVER on computers sql1 and sql2.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaService -SqlInstance sql1, sql1\\test, sql2\\test\nGets the SQL Server related services related to the default instance MSSQLSERVER on computers sql1, the named instances test on sql1 and sql2.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaService -ComputerName $MyServers -Type SSRS\nGets the SQL Server related services of type \"SSRS\" (Reporting Services) on computers in the variable MyServers.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003e$MyServers = Get-Content .\\servers.txt\nPS C:\\\u003e Get-DbaService -ComputerName $MyServers -ServiceName MSSQLSERVER,SQLSERVERAGENT\nGets the SQL Server related services with ServiceName MSSQLSERVER or SQLSERVERAGENT for all the servers that are stored in the file. Every line in the file can only contain one hostname for a server.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003e$services = Get-DbaService -ComputerName sql1 -Type Agent,Engine\nPS C:\\\u003e $services.ChangeStartMode(\u0027Manual\u0027)\nGets the SQL Server related services of types Sql Agent and DB Engine on computer sql1 and changes their startup mode to \u0027Manual\u0027.\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003e(Get-DbaService -ComputerName sql1 -Type Engine).Restart($true)\nCalls a Restart method for each Engine service on computer sql1.", "Description": "Retrieves detailed information about SQL Server-related Windows services across one or more computers, including Database Engine, SQL Agent, Reporting Services, Analysis Services, Integration Services, and other SQL Server components. This function replaces manual service management tasks by providing a unified view of service status, startup modes, and service accounts across your SQL Server environment.\n\nParticularly useful for inventory management, troubleshooting service issues, and performing bulk service operations across multiple servers. The function can filter by service type, instance name, or specific service names, and optionally includes advanced properties like SQL Server version and service pack levels.\n\nReturns service objects with built-in methods for common operations like Start(), Stop(), Restart(), and ChangeStartMode(), eliminating the need to use separate service management commands.\n\nRequires Local Admin rights on destination computer(s).", "Links": "https://dbatools.io/Get-DbaService", "Synopsis": "Retrieves SQL Server-related Windows services from local or remote computers.", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the target computer(s) to retrieve SQL Server services from. Accepts computer names, IP addresses, or FQDN.\r\nUse this when you need to check service status across multiple servers in your environment.", "cn,host,Server", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "InstanceName", "Filters results to show only services belonging to the specified SQL Server instance names.\r\nUse this when you need to focus on specific instances rather than all SQL Server services on the target computers.", "Instance", false, "false", "", "" ], [ "SqlInstance", "Use a combination of computername and instancename to get the SQL Server related services for specific instances on specific computers.\nParameters ComputerName and InstanceName will be ignored if SqlInstance is used.", "", false, "false", "", "" ], [ "Credential", "Credential object used to connect to the computer as a different user.", "", false, "false", "", "" ], [ "Type", "Filters results to specific SQL Server service types such as Database Engine, SQL Agent, or Reporting Services.\r\nUse this when troubleshooting specific service types or performing targeted service management operations. Can be one of the following: \"Agent\", \"Browser\", \"Engine\", \"FullText\", \"SSAS\", \"SSIS\", \r\n\"SSRS\", \"PolyBase\", \"Launchpad\"", "", false, "false", "", "Agent,Browser,Engine,FullText,SSAS,SSIS,SSRS,PolyBase,Launchpad" ], [ "ServiceName", "Specifies exact Windows service names to retrieve, bypassing automatic service discovery.\r\nUse this when you know the specific service names and want to avoid the overhead of scanning for all SQL Server services.", "", false, "false", "", "" ], [ "AdvancedProperties", "Includes additional service properties such as SQL Server version, service pack level, SKU name, and cluster information.\r\nUse this when you need detailed service information for inventory, compliance, or troubleshooting purposes. Note that this adds processing time to the command.\r\nThis will also output the additional property SqlInstance based on the Clustered and VSName properties for engine services.\r\nUse this property to connect to the correct SQL instance.", "", 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": [ "SpConfig", "Configure", "Configuration" ], "CommandName": "Get-DbaSpConfigure", "Name": "Get-DbaSpConfigure", "Author": "Nic Cain, sirsql.net", "Syntax": "Get-DbaSpConfigure [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Name] \u003cString[]\u003e] [[-ExcludeName] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per sp_configure setting, providing comprehensive configuration details and comparison against SQL Server defaults.\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 format)\r\n- Name: The SMO property name of the configuration setting (e.g., MaxServerMemory, CostThresholdForParallelism)\r\n- DisplayName: The sp_configure display name of the setting (e.g., \"max server memory (MB)\")\r\n- Description: Human-readable description of what the configuration setting controls\r\n- IsAdvanced: Boolean indicating if this is an advanced configuration setting (requires ShowAdvancedOptions enabled)\r\n- IsDynamic: Boolean indicating if the setting takes effect immediately (true) or requires restart (false)\r\n- MinValue: The minimum allowed value for this setting (int/numeric)\r\n- MaxValue: The maximum allowed value for this setting (int/numeric)\r\n- ConfiguredValue: The current configured value stored in sys.configurations (may require restart to take effect)\r\n- RunningValue: The currently running/active value in memory on the SQL Server instance\r\n- DefaultValue: The out-of-the-box default value for this setting from SQL Server\r\n- IsRunningDefaultValue: Boolean indicating if the running value matches the default value (true = using default, false = customized)\nHidden properties (accessible with Select-Object *):\r\n- ServerName: The server name (same as SqlInstance)\r\n- Parent: Reference to the SMO Server object\r\n- ConfigName: Alias for Name property\r\n- Property: Reference to the underlying SMO ConfigurationProperty object", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaSpConfigure -SqlInstance localhost\nReturns all system configuration information on the localhost.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027localhost\u0027,\u0027localhost\\namedinstance\u0027 | Get-DbaSpConfigure\nReturns system configuration information on multiple instances piped into the function\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaSpConfigure -SqlInstance sql2012 -Name \u0027max server memory (MB)\u0027\nReturns only the system configuration for MaxServerMemory on sql2012.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaSpConfigure -SqlInstance sql2012 -ExcludeName \u0027max server memory (MB)\u0027, RemoteAccess | Out-GridView\nReturns system configuration information on sql2012 but excludes for max server memory (MB) and remote access. Values returned in grid view\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$cred = Get-Credential SqlCredential\nPS C:\\\u003e \u0027sql2012\u0027 | Get-DbaSpConfigure -SqlCredential $cred -Name RemoteAccess, \u0027max server memory (MB)\u0027 -ExcludeName \u0027remote access\u0027 | Out-GridView\nReturns system configuration information on sql2012 using SQL Server Authentication. Only MaxServerMemory is returned as RemoteAccess was also excluded.", "Description": "Retrieves all SQL Server instance-level configuration settings accessible through sp_configure, using SMO to gather comprehensive details about each setting. This function compares current configured and running values against SQL Server defaults to quickly identify which settings have been customized from their out-of-box values.\n\nEssential for configuration auditing, compliance checks, and ensuring consistency across multiple SQL Server environments. The output includes advanced and basic settings, minimum/maximum allowed values, whether settings are dynamic (require restart), and flags non-default configurations for review.\n\nParticularly useful when documenting server configurations, troubleshooting performance issues related to memory or parallelism settings, or preparing for server migrations where you need to replicate custom configurations.", "Links": "https://dbatools.io/Get-DbaSpConfigure", "Synopsis": "Retrieves SQL Server sp_configure settings with default value comparisons for configuration auditing", "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", "", "" ], [ "Name", "Return only specific configuration settings instead of all sp_configure values. Accepts either display names from sp_configure (\u0027max server memory (MB)\u0027) or SMO property names (\u0027MaxServerMemory\u0027).\r\nUse this when you need to check specific settings like memory configuration, parallelism, or security options without retrieving the full list.", "Config,ConfigName", false, "false", "", "" ], [ "ExcludeName", "Exclude specific configuration settings from the results. Accepts either display names from sp_configure or SMO property names.\r\nUseful when generating reports or comparisons where you want to hide standard settings and focus on custom configurations.", "", 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", "SpinLockStatistics", "Waits" ], "CommandName": "Get-DbaSpinLockStatistic", "Name": "Get-DbaSpinLockStatistic", "Author": "Patrick Flynn (@sqllensman)", "Syntax": "Get-DbaSpinLockStatistic [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per spinlock type found on the SQL Server instance. Each object contains statistics about spinlock usage and contention for a specific spinlock type.\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- SpinLockName: The type of spinlock (e.g., LOCK_HASH, LOGCACHE_ACCESS)\r\n- Collisions: Number of times threads had to wait for the spinlock\r\n- Spins: Total number of spin cycles before acquiring the lock\r\n- SpinsPerCollision: Average spins per collision (efficiency indicator)\r\n- SleepTime: Total time spent sleeping when spins were exhausted (milliseconds)\r\n- Backoffs: Number of times the thread backed off before retrying", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaSpinLockStatistic -SqlInstance sql2008, sqlserver2012\nGet SpinLock Statistics for servers sql2008 and sqlserver2012.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$output = Get-DbaSpinLockStatistic -SqlInstance sql2008 | Select-Object * | ConvertTo-DbaDataTable\nCollects all SpinLock Statistics on server sql2008 into a Data Table.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e\u0027sql2008\u0027,\u0027sqlserver2012\u0027 | Get-DbaSpinLockStatistic\nGet SpinLock Statistics for servers sql2008 and sqlserver2012 via pipline\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Get-DbaSpinLockStatistic -SqlInstance sql2008 -SqlCredential $cred\nConnects using sqladmin credential and returns SpinLock Statistics from sql2008", "Description": "Queries sys.dm_os_spinlock_stats to return detailed statistics about SQL Server\u0027s spinlock usage and contention. Spinlocks are lightweight synchronization primitives that SQL Server uses internally for very brief waits when protecting critical code sections and memory structures.\n\nThis information helps diagnose severe performance issues caused by spinlock contention, which typically manifests as high CPU usage with poor throughput. Common spinlock contention scenarios include tempdb allocation bottlenecks, excessive concurrent activity on specific database objects, or issues with SQL Server\u0027s internal data structures.\n\nBased on Paul Randal\u0027s advanced performance troubleshooting methodology, this data is essential when wait statistics show SOS_SCHEDULER_YIELD or other CPU-related waits that might indicate spinlock pressure.\n\nReturns:\n SpinLockName - The type of spinlock (e.g., LOCK_HASH, LOGCACHE_ACCESS)\n Collisions - Number of times threads had to wait for the spinlock\n Spins - Total number of spin cycles before acquiring the lock\n SpinsPerCollision - Average spins per collision (efficiency indicator)\n SleepTime - Total time spent sleeping when spins were exhausted\n Backoffs - Number of times the thread backed off before retrying\n\nReference: https://www.sqlskills.com/blogs/paul/advanced-performance-troubleshooting-waits-latches-spinlocks/", "Links": "https://dbatools.io/Get-DbaSpinLockStatistic", "Synopsis": "Retrieves spinlock contention statistics from SQL Server\u0027s internal synchronization mechanisms", "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": "SPN", "CommandName": "Get-DbaSpn", "Name": "Get-DbaSpn", "Author": "Drew Furgiuele (@pittfurg), port1433.com", "Syntax": "Get-DbaSpn [[-ComputerName] \u003cString[]\u003e] [[-AccountName] \u003cString[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per Service Principal Name (SPN) found. The command supports two search modes that return the same object structure:\nProperties:\r\n- Input: The search term provided (computer name or account name)\r\n- AccountName: The Active Directory service account name\r\n- ServiceClass: Always \"MSSQLSvc\" for SQL Server SPNs\r\n- Port: The port number if present in the SPN; null if no port is specified\r\n- SPN: The full Service Principal Name value", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaSpn -ComputerName SQLSERVERA -Credential ad\\sqldba\nReturns a custom object with SearchTerm (ServerName) and the SPNs that were found\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaSpn -AccountName domain\\account -Credential ad\\sqldba\nReturns a custom object with SearchTerm (domain account) and the SPNs that were found\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaSpn -ComputerName SQLSERVERA,SQLSERVERB -Credential ad\\sqldba\nReturns a custom object with SearchTerm (ServerName) and the SPNs that were found for multiple computers", "Description": "Queries Active Directory to return SPNs that are currently registered for SQL Server services on specified computers or service accounts. This is essential for troubleshooting Kerberos authentication issues, as missing or duplicate SPNs prevent clients from authenticating to SQL Server using integrated security. Use this command to audit your current SPN configuration before making changes with Set-DbaSpn or when investigating authentication failures. The function returns detailed information including the service class (MSSQLSvc), port numbers, and associated Active Directory accounts.", "Links": "https://dbatools.io/Get-DbaSpn", "Synopsis": "Retrieves existing Service Principal Names (SPNs) from Active Directory for SQL Server services", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the SQL Server computer names to retrieve registered SPNs for. Defaults to localhost if not specified.\r\nUse this when you need to audit SPN configuration on specific servers or when troubleshooting Kerberos authentication issues across multiple SQL instances.", "", false, "true (ByValue)", "", "" ], [ "AccountName", "Specifies the Active Directory service accounts to search for registered SQL Server SPNs. Accepts both user accounts and computer accounts ending with \u0027$\u0027.\r\nUse this when you need to audit which SPNs are registered under specific service accounts or when investigating authentication issues related to particular accounts.", "", false, "false", "", "" ], [ "Credential", "User credential to connect to the remote servers or active directory.", "", 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": [ "SSIS", "SSISDB", "Variable" ], "CommandName": "Get-DbaSsisEnvironmentVariable", "Name": "Get-DbaSsisEnvironmentVariable", "Author": "Bartosz Ratajczyk (@b_ratajczyk)", "Syntax": "Get-DbaSsisEnvironmentVariable [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Environment] \u003cObject[]\u003e] [[-EnvironmentExclude] \u003cObject[]\u003e] [[-Folder] \u003cObject[]\u003e] [[-FolderExclude] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SSIS environment variable found in the filtered environments and folders. Sensitive variable values are automatically decrypted and returned in plaintext.\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- Folder: The SSISDB catalog folder name containing the environment\r\n- Environment: The name of the SSIS environment containing the variable\r\n- Id: Unique identifier for the variable within the environment\r\n- Name: The logical name of the environment variable\r\n- Description: Text description of the variable\u0027s purpose\r\n- Type: The type of variable (typically \u0027String\u0027, \u0027Int32\u0027, etc.)\r\n- IsSensitive: Boolean indicating if the variable value is sensitive (encrypted in SSISDB)\r\n- BaseDataType: The base data type used for the variable value storage\r\n- Value: The actual variable value; automatically decrypted if sensitive, plaintext if not", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaSsisEnvironmentVariable -SqlInstance localhost -Environment DEV -Folder DWH_ETL\nGets variables of \u0027DEV\u0027 environment located in \u0027DWH_ETL\u0027 folder on \u0027localhost\u0027 Server\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaSsisEnvironmentVariable -SqlInstance localhost -Environment DEV -Folder DWH_ETL, DEV2, QA\nGets variables of \u0027DEV\u0027 environment(s) located in folders \u0027DWH_ETL\u0027, \u0027DEV2\u0027 and \u0027QA\u0027 on \u0027localhost\u0027 server\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaSsisEnvironmentVariable -SqlInstance localhost -Environment DEV -FolderExclude DWH_ETL, DEV2, QA\nGets variables of \u0027DEV\u0027 environments located in folders other than \u0027DWH_ETL\u0027, \u0027DEV2\u0027 and \u0027QA\u0027 on \u0027localhost\u0027 server\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaSsisEnvironmentVariable -SqlInstance localhost -Environment DEV, PROD -Folder DWH_ETL, DEV2, QA\nGets variables of \u0027DEV\u0027 and \u0027PROD\u0027 environment(s) located in folders \u0027DWH_ETL\u0027, \u0027DEV2\u0027 and \u0027QA\u0027 on \u0027localhost\u0027 server\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaSsisEnvironmentVariable -SqlInstance localhost -EnvironmentExclude DEV, PROD -Folder DWH_ETL, DEV2, QA\nGets variables of environments other than \u0027DEV\u0027 and \u0027PROD\u0027 located in folders \u0027DWH_ETL\u0027, \u0027DEV2\u0027 and \u0027QA\u0027 on \u0027localhost\u0027 server\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaSsisEnvironmentVariable -SqlInstance localhost -EnvironmentExclude DEV, PROD -FolderExclude DWH_ETL, DEV2, QA\nGets variables of environments other than \u0027DEV\u0027 and \u0027PROD\u0027 located in folders other than \u0027DWH_ETL\u0027, \u0027DEV2\u0027 and \u0027QA\u0027 on \u0027localhost\u0027 server\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003e\u0027localhost\u0027 | Get-DbaSsisEnvironmentVariable -EnvironmentExclude DEV, PROD\nGets all SSIS environments except \u0027DEV\u0027 and \u0027PROD\u0027 from \u0027localhost\u0027 server. The server name comes from pipeline\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003e\u0027SRV1\u0027, \u0027SRV3\u0027 | Get-DbaSsisEnvironmentVariable\nGets all SSIS environments from \u0027SRV1\u0027 and \u0027SRV3\u0027 servers. The server\u0027s names come from pipeline\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003e\u0027SRV1\u0027, \u0027SRV2\u0027 | Get-DbaSsisEnvironmentVariable DEV | Out-GridView\nGets all variables from \u0027DEV\u0027 Environment(s) on servers \u0027SRV1\u0027 and \u0027SRV2\u0027 and outputs it as the GridView.\r\nThe server names come from the pipeline.\n-------------------------- EXAMPLE 10 --------------------------\nPS C:\\\u003e\u0027localhost\u0027 | Get-DbaSsisEnvironmentVariable -EnvironmentExclude DEV, PROD | Select-Object -Property Name, Value | Where-Object {$_.Name -match \u0027^a\u0027} | Out-GridView\nGets all variables from Environments other than \u0027DEV\u0027 and \u0027PROD\u0027 on \u0027localhost\u0027 server,\r\nselects Name and Value properties for variables that names start with letter \u0027a\u0027 and outputs it as the GridView", "Description": "Retrieves all variables from specified SSIS environments stored in the SSISDB catalog database. All sensitive values are automatically decrypted and returned in plaintext for configuration management and troubleshooting purposes.\n\nThis function queries the SSISDB database directly using symmetric keys and certificates to decrypt sensitive variable values, bypassing the standard SMO limitations that only return encrypted values. This is essential for SSIS environment configuration audits, parameter validation, and deployment verification.\n\nThe function communicates directly with SSISDB database - the SQL Server Integration Services service isn\u0027t queried. Each parameter (besides SqlInstance and SqlCredential) acts as a filter to include or exclude specific environments or folders.", "Links": "https://dbatools.io/Get-DbaSsisEnvironmentVariable", "Synopsis": "Retrieves environment variables from SSIS Catalog with decrypted sensitive values", "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\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", "", "" ], [ "Environment", "Specifies one or more SSIS environment names to retrieve variables from within the SSISDB catalog.\r\nUse this when you need variables from specific environments like \u0027DEV\u0027, \u0027QA\u0027, or \u0027PROD\u0027 rather than all environments in a folder.", "", false, "false", "", "" ], [ "EnvironmentExclude", "Excludes specified SSIS environment names from the results when retrieving variables.\r\nMost effective when used without the Environment parameter to get all environments except those specified.\r\nHelpful when you want to audit all non-production environments or exclude specific environments from configuration reviews.", "", false, "false", "", "" ], [ "Folder", "Specifies one or more SSISDB catalog folder names that contain the environments you want to query.\r\nUse this to limit your search to specific project folders when you have environments organized by application or team.\r\nIf omitted, the function searches all folders in the SSISDB catalog.", "", false, "false", "", "" ], [ "FolderExclude", "Excludes specified SSISDB catalog folder names from the search when retrieving environment variables.\r\nMost effective when used without the Folder parameter to search all folders except those specified.\r\nUseful when you want to exclude test folders, archived projects, or specific application folders from your audit.", "", 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", "SSIS" ], "CommandName": "Get-DbaSsisExecutionHistory", "Name": "Get-DbaSsisExecutionHistory", "Author": "Chris Tucker (@ChrisTuc47368095)", "Syntax": "Get-DbaSsisExecutionHistory [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Since] \u003cDateTime\u003e] [[-Status] \u003cString[]\u003e] [[-Project] \u003cString[]\u003e] [[-Folder] \u003cString[]\u003e] [[-Environment] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SSIS package execution found in the SSISDB catalog matching the specified filters. Each execution record includes timing information, status, and project metadata from the \r\ncatalog.executions view.\nProperties:\r\n- ExecutionID: Unique identifier for the SSIS package execution instance\r\n- FolderName: The SSISDB catalog folder name containing the project\r\n- ProjectName: The name of the SSIS project that contains the executed package\r\n- PackageName: The name of the SSIS package that was executed\r\n- ProjectLsn: The project\u0027s Log Sequence Number indicating deployment version\r\n- Environment: The environment used during execution (folder\\environment format, empty string if no environment)\r\n- StatusCode: String representation of the execution status (Created, Running, Cancelled, Failed, Pending, Halted, Succeeded, Stopping, or Completed)\r\n- StartTime: dbadatetime object representing when the package execution started\r\n- EndTime: dbadatetime object representing when the package execution ended (NULL for running executions)\r\n- ElapsedMinutes: Integer number of minutes elapsed between start and end time\r\n- LoggingLevel: Integer value representing the logging level (0-5) used during execution", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaSsisExecutionHistory -SqlInstance SMTQ01 -Folder SMTQ_PRC\nGet all history items for SMTQ01 in folder SMTQ_PRC.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaSsisExecutionHistory -SqlInstance SMTQ01 -Status Failed,Cancelled\nGets all failed or canceled executions for SMTQ01.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaSsisExecutionHistory -SqlInstance SMTQ01,SMTQ02 -Status Failed,Cancelled\nShows what would happen if the command were executed and would return the SQL statement that would be executed per instance.", "Description": "Retrieves detailed execution history for SSIS packages from the SSIS catalog database, including execution status, timing, and environment details. This function queries the catalog.executions view in SSISDB to provide comprehensive execution information for troubleshooting failed packages, monitoring performance, and analyzing SSIS workloads.\n\nUseful for identifying failed or long-running packages, tracking execution patterns over time, and investigating SSIS deployment issues. Results can be filtered by project, folder, environment, execution status, or date range to focus on specific troubleshooting scenarios.", "Links": "https://dbatools.io/Get-DbaSsisExecutionHistory", "Synopsis": "Retrieves SSIS package execution history from the SSIS catalog database (SSISDB).", "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\r\nto 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", "", "" ], [ "Since", "Limits results to executions that started on or after the specified date and time. Accepts datetime objects or strings.\r\nUse this to focus on recent executions when analyzing current issues or to exclude older historical data from large catalogs.", "", false, "false", "", "" ], [ "Status", "Filters results to specific execution statuses such as Failed, Succeeded, or Running. Accepts multiple status values.\r\nCommonly used to find failed executions for troubleshooting or to monitor currently running packages during peak processing times.", "", false, "false", "", "Created,Running,Cancelled,Failed,Pending,Halted,Succeeded,Stopping,Completed" ], [ "Project", "Filters results to specific SSIS projects deployed to the catalog. Accepts an array of project names for multiple projects.\r\nUse this when troubleshooting issues within particular projects or analyzing execution patterns for specific deployments.", "", false, "false", "", "" ], [ "Folder", "Filters results to specific SSIS catalog folders that contain projects and packages. Accepts an array of folder names.\r\nUseful for focusing on executions within specific organizational folders or when troubleshooting deployments in particular environments.", "", false, "false", "", "" ], [ "Environment", "Filters results to specific SSIS environments that were used during package execution. Accepts an array of environment names.\r\nUse this to analyze executions that used particular environment variables or to troubleshoot environment-specific configuration 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": [ "WSMan", "SQLWMI", "Memory", "Startup" ], "CommandName": "Get-DbaStartupParameter", "Name": "Get-DbaStartupParameter", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaStartupParameter [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-Credential] \u003cPSCredential\u003e] [-Simple] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance containing startup parameter configuration.\nWhen -Simple is specified, returns 9 essential 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- MasterData: Path to the master database file\r\n- MasterLog: Path to the master transaction log file\r\n- ErrorLog: Path to the SQL Server error log file\r\n- TraceFlags: Array of trace flag integers, or \"None\" if no trace flags are configured\r\n- DebugFlags: Array of debug flag integers, or \"None\" if no debug flags are configured\r\n- ParameterString: The complete raw startup parameter string from Windows service configuration\nWhen -Simple is not specified (default), additional properties are included:\r\n- CommandPromptStart: Boolean indicating if -c parameter is set (startup without GUI)\r\n- MinimalStart: Boolean indicating if -f parameter is set (minimal configuration startup)\r\n- MemoryToReserve: Integer value of -g parameter in MB, or 0 if not set (memory reserved for SQL Server)\r\n- SingleUser: Boolean indicating if -m parameter is set (single-user mode enabled)\r\n- SingleUserName: Application name for single-user mode, or empty string if not applicable\r\n- NoLoggingToWinEvents: Boolean indicating if -n parameter is set (Windows event logging disabled)\r\n- StartAsNamedInstance: Boolean indicating if -s parameter is set (named instance startup)\r\n- DisableMonitoring: Boolean indicating if -x parameter is set (monitoring disabled)\r\n- IncreasedExtents: Boolean indicating if -E parameter is set (increased extents enabled)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaStartupParameter -SqlInstance sql2014\nLogs into SQL WMI as the current user then displays the values for numerous startup parameters.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$wincred = Get-Credential ad\\sqladmin\nPS C:\\\u003e Get-DbaStartupParameter -SqlInstance sql2014 -Credential $wincred -Simple\nLogs in to WMI using the ad\\sqladmin credential and gathers simplified information about the SQL Server Startup Parameters.", "Description": "Extracts and parses SQL Server startup parameters directly from the Windows service configuration using WMI. Returns detailed information about file paths (master database, transaction log, error log), trace flags, debug flags, and special startup modes like single-user or minimal start.\n\nUseful for troubleshooting startup issues, documenting server configurations, and verifying trace flag settings without connecting to SQL Server itself. Requires Windows credentials and WMI access to the target server.\n\nSee https://msdn.microsoft.com/en-us/library/ms190737.aspx for more information.", "Links": "https://dbatools.io/Get-DbaStartupParameter", "Synopsis": "Retrieves SQL Server startup parameters from the Windows service configuration", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "Credential", "Allows you to login to servers using alternate Windows credentials.\n$scred = Get-Credential, then pass $scred object to the -Credential parameter.", "SqlCredential", false, "false", "", "" ], [ "Simple", "Returns only essential startup information: file paths (master data, master log, error log), trace flags, and the complete parameter string.\r\nUse this when you need a quick overview without detailed startup mode flags like single-user, minimal start, or monitoring settings.", "", 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": [ "Procedure", "Startup", "StartupProcedure" ], "CommandName": "Get-DbaStartupProcedure", "Name": "Get-DbaStartupProcedure", "Author": "Patrick Flynn (@sqllensman)", "Syntax": "Get-DbaStartupProcedure [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-StartupProcedure] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.StoredProcedure\nReturns one StoredProcedure object for each stored procedure configured as a startup procedure in the master database. Connection context properties are added via NoteProperty.\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: Database name containing the stored procedure (always \"master\" for startup procedures)\r\n- Schema: The schema name containing the stored procedure\r\n- ObjectId: The object ID of the stored procedure within SQL Server\r\n- CreateDate: DateTime when the stored procedure was created\r\n- DateLastModified: DateTime when the stored procedure was last modified\r\n- Name: The name of the stored procedure\r\n- ImplementationType: The implementation type of the procedure (T-SQL or CLR)\r\n- Startup: Boolean indicating if the procedure is configured as a startup procedure\nAdditional properties available from the SMO StoredProcedure object (use Select-Object *):\r\n- Parent: Reference to the parent database object\r\n- Owner: The principal that owns the stored procedure\r\n- ExecutionContext: Execution context (Caller or Owner)\r\n- IsEncrypted: Boolean indicating if the procedure is encrypted\r\n- IsRecompiled: Boolean indicating if the procedure is recompiled on execution\r\n- IsSystemObject: Boolean indicating if this is a system object\r\n- Urn: The Unified Resource Name for the object\r\n- State: The current state of the SMO object (Existing, Creating, Pending, etc.)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaStartupProcedure -SqlInstance SqlBox1\\Instance2\nReturns an object with all startup procedures for the Instance2 instance on SqlBox1\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaStartupProcedure -SqlInstance SqlBox1\\Instance2 -StartupProcedure \u0027dbo.StartupProc\u0027\nReturns an object with a startup procedure named \u0027dbo.StartupProc\u0027 for the Instance2 instance on SqlBox1\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaRegServer -SqlInstance sql2014 | Get-DbaStartupProcedure\nReturns an object with all startup procedures for every server listed in the Central Management Server on sql2014", "Description": "This function returns stored procedures from the master database that are configured to execute automatically during SQL Server startup. Startup procedures are useful for initializing application settings, populating cache tables, or performing other tasks that need to run every time the SQL Server service starts. The function returns SMO StoredProcedure objects with details about each startup procedure, including creation dates, schemas, and implementation types. You can filter results to check if specific procedures are configured as startup procedures, which is helpful for auditing server configurations or troubleshooting startup issues.", "Links": "https://dbatools.io/Get-DbaStartupProcedure", "Synopsis": "Retrieves stored procedures configured to run automatically when SQL Server starts up.", "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", "Filters results to check if specific stored procedures are configured as startup procedures. Accepts procedure names in \u0027schema.procedurename\u0027 format or just \u0027procedurename\u0027 for dbo schema.\r\nUse this when auditing server configurations or verifying that critical initialization procedures are properly configured to run at startup.", "", 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": [ "Pages", "DBCC" ], "CommandName": "Get-DbaSuspectPage", "Name": "Get-DbaSuspectPage", "Author": "Garry Bargsley (@gbargsley), blog.garrybargsley.com", "Syntax": "Get-DbaSuspectPage [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-Database] \u003cObject\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per suspect page record found in the msdb.dbo.suspect_pages table. If no suspect pages 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: The name of the database containing the suspect page\r\n- FileId: The file ID where the corrupt page is located (integer)\r\n- PageId: The page ID of the suspect page (integer)\r\n- EventType: The type of corruption event (823 or 824 I/O error, Bad Checksum, Torn Page, Restored, Repaired (DBCC), or Deallocated (DBCC))\r\n- ErrorCount: The number of times this page has been encountered as suspect (integer)\r\n- LastUpdateDate: The date and time when the page was last detected as suspect (datetime)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaSuspectPage -SqlInstance sql2016\nRetrieve any records stored for Suspect Pages on the sql2016 SQL Server.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaSuspectPage -SqlInstance sql2016 -Database Test\nRetrieve any records stored for Suspect Pages on the sql2016 SQL Server and the Test database only.", "Description": "Queries the msdb.dbo.suspect_pages table to identify database pages that have experienced corruption events such as checksum failures, torn pages, or I/O errors. SQL Server automatically logs corrupt pages to this system table when encountered during read operations, making this function essential for proactive corruption monitoring and troubleshooting. Returns detailed information including the specific database, file, page location, error type, occurrence count, and last detection date to help DBAs prioritize remediation efforts.", "Links": "https://dbatools.io/Get-DbaSuspectPage", "Synopsis": "Retrieves suspect page records from msdb database for corruption detection and analysis", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances", "", true, "true (ByValue)", "", "" ], [ "Database", "Filters suspect page results to a specific database name. When omitted, returns suspect pages from all databases on the instance.\r\nUse this when investigating corruption issues in a particular database or when you need to focus troubleshooting efforts on a single database.", "", 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", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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", "TCP", "SQLWMI" ], "CommandName": "Get-DbaTcpPort", "Name": "Get-DbaTcpPort", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaTcpPort [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [-All] [-ExcludeIpv6] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nDefault output (without -All parameter):\r\nReturns one object per instance with basic connection 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- IPAddress: The IP address that SQL Server is listening on (IPv4 or IPv6)\r\n- Port: The TCP port number that SQL Server is using (integer)\nWhen -All parameter is specified:\r\nReturns one object per TCP/IP address configuration on the instance, with detailed network settings including both IPv4 and IPv6 addresses (unless -ExcludeIpv6 is used).\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- Name: The configuration name (IPAll, IP1, IP2, IP3, IP4, etc.)\r\n- Active: Boolean indicating if this IP address is currently active\r\n- Enabled: Boolean indicating if this IP address is enabled in the configuration\r\n- IpAddress: The IP address value (IPv4 or IPv6 notation)\r\n- TcpDynamicPorts: The dynamic port range if dynamic port assignment is configured\r\n- TcpPort: The static TCP port number if static port assignment is configured\r\n- IsUsed: Boolean indicating whether this IP/port combination is actually in use (based on ListenAll property and Enabled status)\nWhen -ExcludeIpv6 is specified with -All:\r\nReturns only IPv4 addresses, filtering out any IPv6 entries from the results.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaTcpPort -SqlInstance sqlserver2014a\nReturns just the port number for the default instance on sqlserver2014a.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaTcpPort -SqlInstance winserver\\sqlexpress, sql2016\nReturns an object with server name and port number for the sqlexpress on winserver and the default instance on sql2016.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaTcpPort -SqlInstance sqlserver2014a, sql2016 -All\nReturns an object with server name, IPAddress (ipv4 and ipv6), port and static ($true/$false) for sqlserver2014a and sql2016.\nRemote sqlwmi is used by default. If this doesn\u0027t work, then remoting is used. If neither work, it defaults to T-SQL which can provide only the port.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaRegServer -SqlInstance sql2014 | Get-DbaTcpPort -ExcludeIpv6 -All\nReturns an object with server name, IPAddress (just ipv4), port and static ($true/$false) for every server listed in the Central Management Server on sql2014.", "Description": "By default, this function returns just the TCP port used by the specified SQL Server.\n\nIf -All is specified, the server name, IPAddress (ipv4 and ipv6), port number and an indicator of whether or not the port assignment is static are returned.\n\nRemote sqlwmi is used by default. If this doesn\u0027t work, then remoting is used. If neither work, it defaults to T-SQL which can provide only the port.", "Links": "https://dbatools.io/Get-DbaTcpPort", "Synopsis": "Returns the TCP port used by the specified SQL Server.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Allows you to connect to servers using alternate Windows credentials\n$scred = Get-Credential, then pass $scred object to the -SqlCredential parameter.", "", false, "false", "", "" ], [ "Credential", "Credential object used to connect to the Computer as a different user", "", false, "false", "", "" ], [ "All", "Returns comprehensive network configuration details including server name, IP addresses (IPv4 and IPv6), port numbers, and whether the port assignment is static.\r\nUse this when troubleshooting connectivity issues or when you need complete network configuration information instead of just the port number.", "", false, "false", "False", "" ], [ "ExcludeIpv6", "Excludes IPv6 addresses from the output when used with the All parameter, showing only IPv4 network configurations.\r\nUse this in environments where IPv6 is disabled or when you only need to focus on IPv4 connectivity for troubleshooting.", "Ipv4", 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": "Tempdb", "CommandName": "Get-DbaTempdbUsage", "Name": "Get-DbaTempdbUsage", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaTempdbUsage [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per running session that has allocated or deallocated tempdb space. For sessions with no tempdb allocation activity, no object 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)\r\n- Spid: Session ID of the running query (int)\r\n- StatementCommand: The SQL command being executed (SELECT, INSERT, UPDATE, DELETE, etc.)\r\n- QueryText: The actual T-SQL statement text being executed\r\n- ProcedureName: Schema-qualified name of the stored procedure if applicable\r\n- StartTime: DateTime when the request started executing\r\n- CurrentUserAllocatedKB: Current user object allocation in KB for this session (int)\r\n- TotalUserAllocatedKB: Total user object allocation in KB (int)\r\n- UserDeallocatedKB: User object deallocation in KB (int)\r\n- TotalUserDeallocatedKB: Total user object deallocation in KB (int)\r\n- InternalAllocatedKB: Internal object allocation in KB (int)\r\n- TotalInternalAllocatedKB: Total internal object allocation in KB (int)\r\n- InternalDeallocatedKB: Internal object deallocation in KB (int)\r\n- TotalInternalDeallocatedKB: Total internal object deallocation in KB (int)\r\n- RequestedReads: Number of physical read operations performed by the request (int)\r\n- RequestedWrites: Number of write operations performed by the request (int)\r\n- RequestedLogicalReads: Number of logical read operations performed by the request (int)\r\n- RequestedCPUTime: CPU time in milliseconds used by the request (int)\r\n- IsUserProcess: Boolean indicating if the session is a user process (true) or system process (false)\r\n- Status: Current status of the session (running, sleeping, dormant, etc.)\r\n- Database: Name of the database being accessed\r\n- LoginName: SQL Server login name\r\n- OriginalLoginName: Original login name before impersonation if applicable\r\n- NTDomain: Windows domain name if Windows authentication is used\r\n- NTUserName: Windows username if Windows authentication is used\r\n- HostName: Client computer hostname\r\n- ProgramName: Name of the client application (e.g., SQL Server Management Studio, SSMS)\r\n- LoginTime: DateTime when the session logged in\r\n- LastRequestedStartTime: DateTime when the last request started\r\n- LastRequestedEndTime: DateTime when the last request ended", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaTempdbUsage -SqlInstance localhost\\SQLDEV2K14\nGets tempdb usage for localhost\\SQLDEV2K14", "Description": "This function queries DMVs for running sessions using tempdb and returns results if those sessions have user or internal space allocated or deallocated against them.", "Links": "https://dbatools.io/Get-DbaTempdbUsage", "Synopsis": "Gets Tempdb usage for running 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", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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", "ChangeLog" ], "CommandName": "Get-DbatoolsChangeLog", "Name": "Get-DbatoolsChangeLog", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbatoolsChangeLog [-Local] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "None\nThis command does not return any objects. It opens the dbatools release changelog in your default browser or displays a message for unsupported options.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbatoolsChangeLog\nOpens a browser to our online changelog", "Description": "Launches your default browser to view the dbatools release changelog on GitHub. This provides access to version history, new features, bug fixes, and breaking changes for the dbatools PowerShell module. Useful for staying current with module updates or troubleshooting issues that may be related to recent changes.", "Links": "https://dbatools.io/Get-DbatoolsChangeLog", "Synopsis": "Opens the dbatools release changelog in your default browser", "Availability": "Windows, Linux, macOS", "Params": [ [ "Local", "Attempts to display a local changelog file instead of opening the online version. This functionality has been deprecated and will display a warning message directing users to the online changelog.", "", 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": "Get-DbatoolsConfig", "Name": "Get-DbatoolsConfig", "Author": "Friedrich Weinmann (@FredWeinmann)", "Syntax": "Get-DbatoolsConfig [[-FullName] \u003cString\u003e] [-Force] [\u003cCommonParameters\u003e]\nGet-DbatoolsConfig [[-Name] \u003cString\u003e] [[-Module] \u003cString\u003e] [-Force] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Dataplat.Dbatools.Configuration.ConfigurationValue\nReturns one configuration value object per setting found in the dbatools configuration system that matches the specified filter criteria. Results are sorted alphabetically by module name, then by \r\nconfiguration name.\nProperties:\r\n- Module: The module name component (e.g., \"sql\", \"mail\", \"path\", \"logging\")\r\n- Name: The configuration setting name within the module (e.g., \"timeout\", \"smtpserver\")\r\n- Value: The current value stored in the configuration setting (can be any object type)\r\n- Description: Human-readable description of what the configuration controls\r\n- Hidden: Boolean indicating if this is a hidden configuration setting\nWhen multiple settings match the filter criteria, each returns a separate object. The full configuration key is in \"Module.Name\" format (e.g., \"sql.connection.timeout\"). Hidden settings are excluded \r\nby default unless -Force is specified.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbatoolsConfig \u0027Mail.To\u0027\nRetrieves the configuration element for the key \"Mail.To\"\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbatoolsConfig -Force\nRetrieve all configuration elements from all modules, even hidden ones.", "Description": "Retrieves dbatools module configuration settings that control how dbatools functions behave. These settings include connection timeouts, default paths, email configurations, and other module preferences that affect dbatools operations. Use this command to view current settings, troubleshoot dbatools behavior, or identify what configurations are available for customization with Set-DbatoolsConfig.", "Links": "https://dbatools.io/Get-DbatoolsConfig", "Synopsis": "Retrieves dbatools module configuration settings and preferences.", "Availability": "Windows, Linux, macOS", "Params": [ [ "FullName", "Default: \"*\"\r\nSpecifies the complete configuration key in Module.Name format to retrieve specific dbatools settings.\r\nUse this to find exact configuration values like \"sql.connection.timeout\" or \"mail.smtpserver\" without needing to specify module and name separately.\r\nSupports wildcards for pattern matching across all configuration keys.", "", false, "false", "*", "" ], [ "Name", "Default: \"*\"\r\nSpecifies the configuration name to search for within a specific module.\r\nUse this with the Module parameter to find settings like \"timeout\" within the \"sql\" module or \"smtpserver\" within the \"mail\" module.\r\nSupports wildcards for finding multiple related configuration names.", "", false, "false", "*", "" ], [ "Module", "Default: \"*\"\r\nSpecifies which dbatools module\u0027s configuration settings to retrieve.\r\nUse this to focus on specific areas like \"sql\" for connection settings, \"mail\" for email configurations, or \"path\" for default file locations.\r\nCommonly used modules include sql, mail, path, and logging.", "", false, "false", "*", "" ], [ "Force", "Includes hidden configuration values that are normally not displayed in the output.\r\nUse this when troubleshooting dbatools behavior or when you need to see internal configuration settings that control advanced module functionality.\r\nHidden settings often include debugging flags and internal module state information.", "", false, "false", "False", "" ] ] }, { "Tags": "Module", "CommandName": "Get-DbatoolsConfigValue", "Name": "Get-DbatoolsConfigValue", "Author": "Friedrich Weinmann (@FredWeinmann)", "Syntax": "Get-DbatoolsConfigValue [-FullName] \u003cString\u003e [[-Fallback] \u003cObject\u003e] [-NotNull] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "object\nReturns the value stored in the specified dbatools configuration setting. The return type depends on which configuration setting is retrieved - can be string, int, bool, datetime, or any object type \r\nstored in that configuration.\nReturn behavior:\r\n- If the configuration exists and has a value, returns that value\r\n- If the configuration doesn\u0027t exist or is null AND -Fallback is specified, returns the Fallback value\r\n- If the configuration doesn\u0027t exist or is null AND -NotNull is specified, throws an error\r\n- If the configuration doesn\u0027t exist or is null AND neither -Fallback nor -NotNull is specified, returns $null\nSpecial handling: String values of \"Mandatory\" are automatically converted to $true and \"Optional\" are converted to $false to prevent switch parameter parsing issues.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbatoolsConfigValue -Name \u0027System.MailServer\u0027\nReturns the configured value that was assigned to the key \u0027System.MailServer\u0027\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbatoolsConfigValue -Name \u0027Default.CoffeeMilk\u0027 -Fallback 0\nReturns the configured value for \u0027Default.CoffeeMilk\u0027. If no such value is configured, it returns \u00270\u0027 instead.", "Description": "Retrieves the actual value stored in a specific dbatools configuration setting using its full name (Module.Name format). This function is primarily used internally by dbatools functions to access their configuration settings, but can also be used by DBAs in custom scripts to retrieve specific module preferences like connection timeouts, default file paths, or email settings. Unlike Get-DbatoolsConfig which lists multiple configurations, this function returns the raw value of a single setting with optional fallback support.", "Links": "https://dbatools.io/Get-DbatoolsConfigValue", "Synopsis": "Retrieves a specific dbatools configuration value by its exact name.", "Availability": "Windows, Linux, macOS", "Params": [ [ "FullName", "Specifies the exact configuration setting name in Module.Name format (like \u0027sql.connection.timeout\u0027 or \u0027path.dbatoolsdata\u0027).\r\nUse this to retrieve specific dbatools module settings that control behavior like connection timeouts, default file paths, or email configurations.", "Name", true, "false", "", "" ], [ "Fallback", "Provides a default value to return when the specified configuration setting doesn\u0027t exist or is set to null.\r\nUse this in scripts when you need a reliable value even if the configuration hasn\u0027t been set, such as providing a default timeout of 30 seconds when no custom timeout is configured.", "", false, "false", "", "" ], [ "NotNull", "Forces the function to throw an error instead of returning null when no configuration value is found.\r\nUse this when your script requires a specific configuration setting to be present and should fail gracefully rather than continue with null values that could cause unexpected behavior.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Module", "Support" ], "CommandName": "Get-DbatoolsError", "Name": "Get-DbatoolsError", "Author": "Chrissy LeMaire (@cl)", "Syntax": "Get-DbatoolsError [[-First] \u003cInt32\u003e] [[-Last] \u003cInt32\u003e] [[-Skip] \u003cInt32\u003e] [-All] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.Management.Automation.ErrorRecord\nReturns one or more ErrorRecord objects from the PowerShell global error collection, filtered to show only dbatools-related errors based on the FullyQualifiedErrorId containing \"dbatools\".\nProperties (selected from ErrorRecord):\r\n- CategoryInfo: The error category classification (e.g., ConnectionError, PermissionDenied, SyntaxError)\r\n- ErrorDetails: Additional structured error information including message and recommendations\r\n- Exception: The underlying .NET exception that was thrown\r\n- FullyQualifiedErrorId: Fully qualified error identifier used to identify dbatools-related errors\r\n- InvocationInfo: Details about where and how the error occurred in the script (file, line, column, command name)\r\n- PipelineIterationInfo: Information about the position in the pipeline when the error occurred\r\n- PSMessageDetails: Additional PowerShell message details if available\r\n- ScriptStackTrace: Stack trace showing the call hierarchy at the point of the error\r\n- TargetObject: The object that was being processed when the error occurred\nAll properties from the full ErrorRecord object are available using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbatoolsError\nReturns detailed error information for the most recent dbatools error\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbatoolsError -All\nReturns detailed error information for all dbatools-related errors\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbatoolsError -Last 1\nReturns the oldest dbatools-related error in the pipeline", "Description": "Retrieves detailed error information specifically from dbatools command failures, filtering the PowerShell error collection to show only dbatools-related errors. This provides comprehensive diagnostic details including exception messages, stack traces, and invocation information that help troubleshoot SQL Server connection issues, permission problems, or command syntax errors. By default, it returns only the most recent dbatools error, but can retrieve all historical dbatools errors for pattern analysis or support requests.", "Links": "https://dbatools.io/Get-DbatoolsError", "Synopsis": "Retrieves detailed error information from failed dbatools commands for troubleshooting", "Availability": "Windows, Linux, macOS", "Params": [ [ "First", "Specifies the number of most recent dbatools errors to return. Defaults to 1 if no parameters are specified.\r\nUse this when you need to examine the latest few errors after a batch operation or troubleshooting session.", "", false, "false", "0", "" ], [ "Last", "Specifies the number of oldest dbatools errors to return from the error history.\r\nUse this when you need to see the earliest errors that occurred during a session or to trace the root cause of cascading failures.", "", false, "false", "0", "" ], [ "Skip", "Specifies the number of most recent dbatools errors to skip before returning results.\r\nUse this when you want to ignore the latest error and examine previous errors, or when paging through error history.", "", false, "false", "0", "" ], [ "All", "Returns detailed information for all dbatools-related errors in the current PowerShell session.\r\nUse this when creating support tickets, analyzing error patterns, or performing comprehensive troubleshooting of multiple failed commands.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Module", "Support" ], "CommandName": "Get-DbatoolsLog", "Name": "Get-DbatoolsLog", "Author": "Friedrich Weinmann (@FredWeinmann)", "Syntax": "Get-DbatoolsLog [[-FunctionName] \u003cString\u003e] [[-ModuleName] \u003cString\u003e] [[-Target] \u003cObject\u003e] [[-Tag] \u003cString[]\u003e] [[-Last] \u003cInt32\u003e] [-LastError] [[-Skip] \u003cInt32\u003e] [[-Runspace] \u003cGuid\u003e] [[-Level] {Critical | Important | Output | Significant | VeryVerbose | Verbose | SomewhatVerbose | System | Debug | InternalComment | Warning}] [-Raw] [-Errors] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Dataplat.Dbatools.Message.LogEntry (when -Raw is specified)\nReturns raw internal LogEntry objects from the dbatools logging system without any property filtering or flattening of multiline content.\nPSCustomObject (default)\nReturns log entries with the following properties formatted for user display:\n- CallStack: The PowerShell call stack at the point the log entry was created\r\n- ComputerName: The name of the computer where the log entry was generated\r\n- File: The PowerShell script file name where the log entry originated\r\n- FunctionName: The name of the dbatools function that created the log entry\r\n- Level: The severity level of the log message (Critical, Error, Warning, Info, Verbose, Debug, etc.)\r\n- Line: The line number in the script file where the log entry was generated\r\n- Message: The log message text with multiline content (SQL statements, multiline errors) flattened to single line by joining with spaces and collapsing multiple spaces\r\n- ModuleName: The name of the module that generated the log entry (typically \"dbatools\")\r\n- Runspace: The PowerShell runspace GUID in which the log entry was created\r\n- Tags: Array of tag strings associated with the log entry for categorization (e.g., \"backup\", \"restore\", \"connection\")\r\n- TargetObject: The SQL Server object being processed when the log entry was created (e.g., server name, database name)\r\n- Timestamp: The DateTime when the log entry was created\r\n- Type: The type of log entry (Information, Error, Warning, etc.)\r\n- Username: The username of the person executing the command that generated the log entry\nNote: Use -Raw to return unmodified LogEntry objects with Message content preserved in original multiline format for detailed troubleshooting of SQL statements.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbatoolsLog\nReturns all log entries currently in memory.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbatoolsLog -LastError\nReturns the last log entry type of error.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbatoolsLog -Target \"a\" -Last 1 -Skip 1\nReturns all log entries that targeted the object \"a\" in the second last execution sent.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbatoolsLog -Tag \"fail\" -Last 5\nReturns all log entries within the last 5 executions that contained the tag \"fail\"", "Description": "Retrieves log entries from dbatools\u0027 internal logging system, allowing you to troubleshoot command execution and track what happened during script runs. Use this when dbatools commands aren\u0027t behaving as expected or when you need to see detailed execution information for debugging purposes. The function can filter logs by specific functions, modules, targets, execution history, or message levels, making it easier to isolate issues during SQL Server automation tasks.", "Links": "https://dbatools.io/Get-DbatoolsLog", "Synopsis": "Retrieves internal log entries and error messages from dbatools module execution", "Availability": "Windows, Linux, macOS", "Params": [ [ "FunctionName", "Filters log entries to show only messages from dbatools functions matching this pattern. Supports wildcards.\r\nUse this when troubleshooting specific commands like \u0027Backup-DbaDatabase\u0027 or when you want to see all backup-related functions with \u0027Backup-Dba*\u0027.", "", false, "false", "*", "" ], [ "ModuleName", "Filters log entries to show only messages from modules matching this pattern. Supports wildcards.\r\nUse this when working with multiple PowerShell modules and you only want to see dbatools-related log entries.", "", false, "false", "*", "" ], [ "Target", "Filters log entries to show only messages related to a specific target object like a server name, database name, or other SQL Server component.\r\nUse this when troubleshooting issues with a particular SQL Server instance or database to see only relevant log entries.", "", false, "false", "", "" ], [ "Tag", "Filters log entries to show only messages that contain any of the specified tags.\r\nUse this to find specific types of operations like \u0027backup\u0027, \u0027restore\u0027, or \u0027migration\u0027 when tracking down issues with particular dbatools workflows.", "", false, "false", "", "" ], [ "Last", "Returns log entries from only the last X PowerShell command executions in your current session.\r\nUse this to focus on recent activity when troubleshooting the most recent dbatools commands you ran. Excludes Get-DbatoolsLog commands from the execution count to avoid confusion.", "", false, "false", "0", "" ], [ "LastError", "Returns only the most recent error message from the dbatools logging system.\r\nUse this as a quick way to see what went wrong with your last dbatools command execution without scrolling through all log entries.", "", false, "false", "False", "" ], [ "Skip", "Specifies how many recent executions to skip when using the -Last parameter.\r\nUse this when you want to see log entries from earlier executions, like \u0027-Last 3 -Skip 2\u0027 to see the 3rd, 4th, and 5th most recent executions.", "", false, "false", "0", "" ], [ "Runspace", "Filters log entries to show only messages from the specified PowerShell runspace GUID.\r\nUse this when troubleshooting parallel or background dbatools operations to isolate messages from specific execution threads.", "", false, "false", "", "" ], [ "Level", "Filters log entries by message severity level (Critical, Error, Warning, Info, Verbose, etc.).\r\nUse this to focus on specific severity levels, like only errors and warnings, or to see verbose details during troubleshooting. Supports arrays and ranges like (1..6).", "", false, "false", "", "" ], [ "Raw", "Returns log messages in their original format without flattening multiline content like SQL statements.\r\nUse this when you need to see the exact formatting of SQL queries or error messages for detailed troubleshooting.", "", false, "false", "False", "" ], [ "Errors", "Returns error entries from dbatools\u0027 error tracking system instead of regular log entries.\r\nUse this when you specifically need to see exceptions and errors that occurred during dbatools command execution, separate from informational logging.", "", false, "false", "False", "" ] ] }, { "Name": "Get-DbatoolsPath", "Description": "Retrieves file paths that have been configured for use by dbatools functions. These paths define where the module stores temporary files, exports, logs, and other data during SQL Server operations. DBAs can customize these paths to control where dbatools writes files, ensuring compliance with organizational file storage policies and avoiding permission issues.\n\nPaths can be configured using Set-DbatoolsPath or directly through the configuration system by creating settings with the format \"Path.Managed.\u003cPathName\u003e\". Common predefined paths include Temp, LocalAppData, AppData, and ProgramData, but custom paths can be defined for specific workflows like backup file staging or export destinations.", "Synopsis": "Retrieves configured file paths used by dbatools functions for storing temporary files, logs, and output data.", "Outputs": "System.String\nReturns the configured file path as a string. The returned path represents the location where dbatools will store files for the specified path name (Temp, LocalAppData, AppData, ProgramData, or \r\ncustom-defined path). Returns $null if the specified path name is not configured.", "Alias": "", "CommandName": "Get-DbatoolsPath", "Availability": "Windows, Linux, macOS", "Links": "https://dbatools.io/Get-DbatoolsPath", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbatoolsPath -Name \u0027temp\u0027\nReturns the temp path.", "Params": [ [ "Name", "Specifies the name of the configured path to retrieve. Common predefined paths include \u0027Temp\u0027 for temporary file operations, \u0027LocalAppData\u0027 for user-specific application data, \u0027AppData\u0027 for roaming \r\nprofile data, and \u0027ProgramData\u0027 for system-wide application data.\r\nUse this when you need to determine where dbatools will write files for export operations, temporary processing, or when configuring custom paths for specific workflows like backup staging \r\ndirectories or report output locations.\r\nCustom path names can be defined using Set-DbatoolsPath and referenced here for consistent file management across your SQL Server administration scripts.", "", true, "false", "", "" ] ], "Syntax": "Get-DbatoolsPath [-Name] \u003cString\u003e [\u003cCommonParameters\u003e]" }, { "Tags": [ "Diagnostic", "Performance", "Query" ], "CommandName": "Get-DbaTopResourceUsage", "Name": "Get-DbaTopResourceUsage", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaTopResourceUsage [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-Type] \u003cString[]\u003e] [[-Limit] \u003cInt32\u003e] [-EnableException] [-ExcludeSystem] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one result set per cached query grouped by query hash matching the specified resource metric criteria. When -Type All (default) is specified, up to 80 result objects are returned (20 per \r\nmetric type × 4 metric types).\nDuration metric results (when -Type includes \"Duration\"):\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 context where the query executed\r\n- ObjectName: The stored procedure or object name containing the query (or \u0027\u003cnone\u003e\u0027 for ad-hoc queries)\r\n- QueryHash: The binary hash identifier for the query\r\n- TotalElapsedTimeMs: Total elapsed time in milliseconds for this cached query execution plan\r\n- ExecutionCount: Total number of times this query execution plan was executed\r\n- AverageDurationMs: Average elapsed time per execution in milliseconds\r\n- QueryTotalElapsedTimeMs: Total elapsed time for all occurrences of this query hash\r\n- QueryText: The actual SQL statement text being executed\nFrequency metric results (when -Type includes \"Frequency\"):\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 context where the query executed\r\n- ObjectName: The stored procedure or object name containing the query (or \u0027\u003cnone\u003e\u0027 for ad-hoc queries)\r\n- QueryHash: The binary hash identifier for the query\r\n- ExecutionCount: Number of times this query execution plan was executed\r\n- QueryTotalExecutions: Total execution count for all occurrences of this query hash\r\n- QueryText: The actual SQL statement text being executed\nIO metric results (when -Type includes \"IO\"):\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 context where the query executed\r\n- ObjectName: The stored procedure or object name containing the query (or \u0027\u003cnone\u003e\u0027 for ad-hoc queries)\r\n- QueryHash: The binary hash identifier for the query\r\n- TotalIO: Total logical reads and writes (sum of logical read and write operations)\r\n- ExecutionCount: Number of times this query execution plan was executed\r\n- AverageIO: Average IO operations per execution\r\n- QueryTotalIO: Total IO operations for all occurrences of this query hash\r\n- QueryText: The actual SQL statement text being executed\nCPU metric results (when -Type includes \"CPU\"):\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 context where the query executed\r\n- ObjectName: The stored procedure or object name containing the query (or \u0027\u003cnone\u003e\u0027 for ad-hoc queries)\r\n- QueryHash: The binary hash identifier for the query\r\n- CpuTime: Total worker time in microseconds (CPU time consumed)\r\n- ExecutionCount: Number of times this query execution plan was executed\r\n- AverageCpuMs: Average CPU time per execution in milliseconds\r\n- QueryTotalCpu: Total CPU time for all occurrences of this query hash\r\n- QueryText: The actual SQL statement text being executed\nAdditional property available with Select-Object *:\r\n- QueryPlan: The actual execution plan XML (excluded from default display via Select-DefaultView)\nThe -ExcludeSystem parameter filters out system replication procedures (sp_MS%) from all result sets. The -Database and -ExcludeDatabase parameters filter results to specific databases before \r\naggregation.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaTopResourceUsage -SqlInstance sql2008, sql2012\nReturn the 80 (20 x 4 types) top usage results by duration, frequency, IO, and CPU servers for servers sql2008 and sql2012\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaTopResourceUsage -SqlInstance sql2008 -Type Duration, Frequency -Database TestDB\nReturn the highest usage by duration (top 20) and frequency (top 20) for the TestDB on sql2008\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaTopResourceUsage -SqlInstance sql2016 -Limit 30\nReturn the highest usage by duration (top 30) and frequency (top 30) for the TestDB on sql2016\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaTopResourceUsage -SqlInstance sql2008, sql2012 -ExcludeSystem\nReturn the 80 (20 x 4 types) top usage results by duration, frequency, IO, and CPU servers for servers sql2008 and sql2012 without any System Objects\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaTopResourceUsage -SqlInstance sql2016| Select-Object *\nReturn all the columns plus the QueryPlan column", "Description": "Analyzes cached query performance by examining sys.dm_exec_query_stats to find your worst-performing queries across four key metrics: total duration, execution frequency, IO operations, and CPU time. Each metric returns the top consumers (default 20) grouped by query hash, so you can quickly spot patterns in problematic queries that are dragging down server performance.\n\nWhen your SQL Server is running slowly, this command helps you skip the guesswork and zero in on the specific queries consuming the most resources. Instead of manually writing complex DMV queries, you get formatted results showing query text, execution plans, database context, and performance metrics in one output.\n\nYou can focus on specific databases, exclude system objects like replication procedures, or analyze just one metric type (like Duration) when investigating particular performance issues. The results include actual query text and execution plans, so you can immediately start optimizing the problematic SQL.\n\nThis command is based off of queries provided by Michael J. Swart at http://michaeljswart.com/go/Top20\n\nPer Michael: \"I\u0027ve posted queries like this before, and others have written many other versions of this query. All these queries are based on sys.dm_exec_query_stats.\"", "Links": "https://dbatools.io/Get-DbaTopResourceUsage", "Synopsis": "Identifies the most resource-intensive cached queries from sys.dm_exec_query_stats for performance 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 resource-intensive queries. Accepts multiple database names.\r\nUse this when troubleshooting performance issues in specific databases rather than analyzing server-wide query performance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies databases to skip when analyzing query performance across the SQL Server instance.\r\nUse this to exclude test databases, archived databases, or other databases that aren\u0027t relevant to your performance investigation.", "", false, "false", "", "" ], [ "Type", "Specifies which resource usage metrics to analyze: Duration, Frequency, IO, CPU, or All (default).\r\nUse specific types when investigating particular performance symptoms - Duration for slow queries, Frequency for high-activity queries, IO for disk bottlenecks, or CPU for processor-intensive \r\noperations.", "", false, "false", "All", "All,Duration,Frequency,IO,CPU" ], [ "Limit", "Controls how many top resource-consuming query hashes to return for each metric type (default is 20).\r\nIncrease this value when you need to analyze more queries, or decrease it to focus on only the most problematic queries during initial performance triage.", "", false, "false", "20", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "ExcludeSystem", "Excludes system objects like replication procedures (sp_MS% objects) from the query analysis results.\r\nUse this when you want to focus on application queries rather than system maintenance operations that may consume resources.", "", false, "false", "False", "" ] ] }, { "Tags": "Trace", "CommandName": "Get-DbaTrace", "Name": "Get-DbaTrace", "Author": "Garry Bargsley (@gbargsley), blog.garrybargsley.com", "Syntax": "Get-DbaTrace [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Id] \u003cInt32[]\u003e] [-Default] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per trace found on the SQL Server instance. When -Id is specified, only traces matching those IDs are returned. When -Default is specified, only the default trace is 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- Id: The trace ID number\r\n- Status: Numeric trace status value (0=stopped, 1=running, 2=closed)\r\n- IsRunning: Boolean indicating if the trace is currently running\r\n- Path: The file path where the trace output is stored\r\n- MaxSize: Maximum size of the trace file in megabytes (0=unlimited)\r\n- StopTime: DateTime when the trace is scheduled to stop, or null if running indefinitely\r\n- MaxFiles: Maximum number of rollover files (0=unlimited)\r\n- IsRowset: Boolean indicating if trace output is written as rowset\r\n- IsRollover: Boolean indicating if rollover file creation is enabled\r\n- IsShutdown: Boolean indicating if trace will stop on server shutdown\r\n- IsDefault: Boolean indicating if this is the default system trace\r\n- BufferCount: Number of in-memory buffers allocated for the trace\r\n- BufferSize: Size of each buffer in kilobytes\r\n- FilePosition: Current file position for trace output\r\n- ReaderSpid: Server process ID reading the trace (SPID)\r\n- StartTime: DateTime when the trace was started\r\n- LastEventTime: DateTime of the most recent trace event\r\n- EventCount: Number of events captured by the trace\r\n- DroppedEventCount: Number of events dropped due to buffer limitations\nThe properties RemotePath, Parent, and SqlCredential are also available but excluded from default view. Use Select-Object * to access all properties.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaTrace -SqlInstance sql2016\nLists all the trace files on the sql2016 SQL Server.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaTrace -SqlInstance sql2016 -Default\nLists the default trace information on the sql2016 SQL Server.", "Description": "Queries the sys.traces system view to return detailed information about active and configured traces on a SQL Server instance. This includes trace status, file locations, buffer settings, event counts, and timing data. Commonly used for monitoring trace activity, auditing trace configurations, and locating the default system trace file for troubleshooting and compliance purposes.", "Links": "https://dbatools.io/Get-DbaTrace", "Synopsis": "Retrieves SQL Server trace information including status, file paths, and configuration details", "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", "", "" ], [ "Id", "Specifies the trace ID(s) to retrieve information for. Accepts single values or arrays of trace IDs.\r\nUse this when you need to check specific traces instead of retrieving all configured traces on the instance.", "", false, "false", "", "" ], [ "Default", "Returns only the default system trace (usually trace ID 1) which SQL Server automatically creates for auditing DDL operations.\r\nUse this when you need to locate the default trace file for troubleshooting schema changes, login events, or security auditing.", "", 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", "TraceFlag", "DBCC" ], "CommandName": "Get-DbaTraceFlag", "Name": "Get-DbaTraceFlag", "Author": "Kevin Bullen (@sqlpadawan)", "Syntax": "Get-DbaTraceFlag [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-TraceFlag] \u003cInt32[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per enabled global trace flag on the SQL Server instance. If -TraceFlag is specified, only those specific trace flags (if currently enabled) are returned. If no global trace flags \r\nare enabled, nothing is 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- TraceFlag: The trace flag number (integer, e.g., 4199, 3205, 1118)\r\n- Global: Boolean indicating if the trace flag is enabled globally on the server\r\n- Status: Status value for the trace flag (typically 1 for enabled, 0 for disabled)\nThe property Session (indicating session-level flag status) is available but excluded from default view. Use Select-Object * to access all properties including Session.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaTraceFlag -SqlInstance localhost\nReturns all Trace Flag information on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaTraceFlag -SqlInstance localhost, sql2016\nReturns all Trace Flag(s) for the local and sql2016 SQL Server instances\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaTraceFlag -SqlInstance localhost -TraceFlag 4199,3205\nReturns Trace Flag status for TF 4199 and 3205 for the local SQL Server instance if they are enabled.", "Description": "Queries SQL Server instances to identify which global trace flags are currently active, returning detailed status information for monitoring and compliance purposes. This is essential for auditing server configurations, troubleshooting performance issues, and ensuring trace flag consistency across environments. You can filter results to specific trace flag numbers or retrieve all enabled flags across multiple instances.", "Links": "https://dbatools.io/Get-DbaTraceFlag", "Synopsis": "Retrieves currently enabled global trace flags 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.", "", 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 filter the results. Only returns information for the specified trace flags if they are currently enabled.\r\nUse this when you need to check the status of specific trace flags rather than reviewing all enabled flags 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": [ "CIM", "Instance", "Utility" ], "CommandName": "Get-DbaUptime", "Name": "Get-DbaUptime", "Author": "Stuart Moore (@napalmgram), stuart-moore.com", "Syntax": "Get-DbaUptime [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance containing uptime information for both SQL Server and its hosting Windows server.\nProperties:\r\n- ComputerName: The Windows server computer name (from DNS resolution)\r\n- InstanceName: The SQL Server instance name\r\n- SqlServer: The full SQL Server instance name\r\n- SqlStartTime: DateTime when SQL Server was started (based on tempdb creation date)\r\n- SqlUptime: TimeSpan object showing SQL Server uptime duration\r\n- SinceSqlStart: Formatted string of SQL Server uptime as \"X days Y hours Z minutes A seconds\"\r\n- WindowsBootTime: DateTime when the Windows server was last booted\r\n- WindowsUptime: TimeSpan object showing Windows server uptime duration\r\n- SinceWindowsBoot: Formatted string of Windows uptime as \"X days Y hours Z minutes A seconds\"", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaUptime -SqlInstance SqlBox1\\Instance2\nReturns an object with SQL Server start time, uptime as TimeSpan object, uptime as a string, and Windows host boot time, host uptime as TimeSpan objects and host uptime as a string for the sqlexpress \r\ninstance on winserver\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaUptime -SqlInstance winserver\\sqlexpress, sql2016\nReturns an object with SQL Server start time, uptime as TimeSpan object, uptime as a string, and Windows host boot time, host uptime as TimeSpan objects and host uptime as a string for the sqlexpress \r\ninstance on host winserver and the default instance on host sql2016\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaRegServer -SqlInstance sql2014 | Get-DbaUptime\nReturns an object with SQL Server start time, uptime as TimeSpan object, uptime as a string, and Windows host boot time, host uptime as TimeSpan objects and host uptime as a string for every server \r\nlisted in the Central Management Server on sql2014", "Description": "This function determines SQL Server uptime by checking the tempdb creation date and calculates Windows server uptime using CIM/WMI calls to get the last boot time. Essential for monitoring system stability, troubleshooting unexpected restarts, and generating compliance reports that require uptime documentation. Returns both raw TimeSpan objects for calculations and formatted strings for reporting, covering both the SQL Server service and the underlying Windows host.", "Links": "https://dbatools.io/Get-DbaUptime", "Synopsis": "Retrieves uptime information for SQL Server instances and their hosting Windows servers", "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", "Specifies Windows credentials to connect to the hosting server for retrieving Windows boot time and uptime information.\r\nUse this when you need different credentials to access the Windows server than your current PowerShell session, such as when querying servers in different domains or when running under a service \r\naccount that lacks WMI access.", "", 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": [ "Security", "User" ], "CommandName": "Get-DbaUserPermission", "Name": "Get-DbaUserPermission", "Author": "Brandon Abshire, netnerds.net | Josh Smith", "Syntax": "Get-DbaUserPermission [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-ExcludeSystemDatabase] [-IncludePublicGuest] [-IncludeSystemObjects] [-ExcludeSecurables] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per permission grant/denial or role membership discovered during the security audit. Separate objects are returned for server-level and database-level permissions, with each object \r\ncontaining contextual information about the grantor, grantee, and permission state.\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- Object: The scope of the permission - \u0027SERVER\u0027 for server-level permissions, or the database name for database-level permissions\r\n- Type: The type of audit row - \u0027SERVER LOGINS\u0027, \u0027SERVER SECURABLES\u0027, \u0027DB ROLE MEMBERS\u0027, or \u0027DB SECURABLES\u0027\r\n- Member: The login or principal name (populated for role membership rows only)\r\n- RoleSecurableClass: The role name for membership records, securable class for permission records, or \u0027None\u0027\r\n- SchemaOwner: The schema/owner name for object permissions (empty for role memberships)\r\n- Securable: The name of the securable object being granted permissions (table, procedure, etc.) - empty for role memberships\r\n- GranteeType: The type of grantee (USER, ROLE, APPLICATION ROLE) - empty for role memberships\r\n- Grantee: The principal name that was granted the permission - empty for role memberships\r\n- Permission: The permission name (SELECT, INSERT, EXECUTE, etc.) - empty for role memberships\r\n- State: The permission state (GRANT or DENY) - empty for role memberships\r\n- Grantor: The principal that granted the permission - empty for role memberships\r\n- GrantorType: The type of grantor (USER, ROLE) - empty for role memberships\r\n- SourceView: The STIG schema view the data came from - empty for role memberships\nNote: Records with empty property values indicate that property does not apply to that audit row type. Role membership records populate only Member, RoleSecurableClass, and connection properties. \r\nObject permission records populate all securable-related properties.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaUserPermission -SqlInstance sql2008, sqlserver2012\nCheck server and database permissions for servers sql2008 and sqlserver2012.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaUserPermission -SqlInstance sql2008 -Database TestDB\nCheck server and database permissions on server sql2008 for only the TestDB database\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaUserPermission -SqlInstance sql2008 -Database TestDB -IncludePublicGuest -IncludeSystemObjects\nCheck server and database permissions on server sql2008 for only the TestDB database,\r\nincluding public and guest grants, and sys schema objects.", "Description": "Performs a comprehensive security audit by analyzing all server logins, server-level permissions, database users, database roles, and object-level permissions across SQL Server instances. Creates temporary STIG (Security Technical Implementation Guide) objects in tempdb to gather detailed permission information for both direct and inherited access rights.\n\nThis command is essential for security compliance audits, particularly for organizations implementing DISA STIG requirements. It reveals the complete permission landscape including role memberships, explicit grants/denials, and securable object permissions, giving DBAs the detailed visibility needed for access reviews and compliance reporting.\n\nThe function uses DISA-provided Permissions.sql scripts to ensure thorough analysis of security configurations. By default, it excludes public/guest permissions and system objects to focus on meaningful security grants, but these can be included for complete visibility.\n\nNote that if you interrupt this command prematurely (Ctrl-C), it will leave behind a STIG schema in tempdb that should be manually cleaned up.", "Links": "https://dbatools.io/Get-DbaUserPermission", "Synopsis": "Audits comprehensive security permissions across SQL Server instances using DISA STIG methodology", "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 audit for user permissions and role memberships. Accepts multiple database names and supports wildcards.\r\nUse this when you need to focus the security audit on specific databases rather than scanning the entire instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies databases to skip during the security audit. Useful for excluding databases that don\u0027t require security review.\r\nCommon scenarios include excluding development databases or databases with known compliant configurations.", "", false, "false", "", "" ], [ "ExcludeSystemDatabase", "Excludes system databases (master, model, msdb, tempdb) from the security audit. Focuses the output on user databases only.\r\nUse this when compliance requirements only apply to application databases and not SQL Server system databases.", "", false, "false", "False", "" ], [ "IncludePublicGuest", "Includes permissions granted to the public database role and guest user account in the audit results.\r\nUse this for complete security visibility, as public and guest permissions affect all users and can create unintended access paths.", "", false, "false", "False", "" ], [ "IncludeSystemObjects", "Includes permissions on system schema objects (sys, INFORMATION_SCHEMA) in the audit results.\r\nEnable this when security policies require auditing access to metadata views and system functions that could expose sensitive information.", "", false, "false", "False", "" ], [ "ExcludeSecurables", "Excludes object-level permissions (tables, views, procedures, functions) from the audit and returns only role memberships.\r\nUse this for high-level security reviews focused on role-based access rather than granular object 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", "" ] ] }, { "Tags": [ "Diagnostic", "Waits", "Task" ], "CommandName": "Get-DbaWaitingTask", "Name": "Get-DbaWaitingTask", "Author": "Shawn Melton (@wsmelton), wsmelton.github.io", "Syntax": "Get-DbaWaitingTask [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Spid] \u003cObject[]\u003e] [-IncludeSystemSpid] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per waiting session found on the SQL Server instance, with the following default 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: The session ID (SPID) of the waiting session\r\n- Thread: The execution context ID (thread number within the session)\r\n- Scheduler: The scheduler ID managing this task\r\n- WaitMs: The duration of the wait in milliseconds\r\n- WaitType: The type of wait (e.g., CXPACKET, LCK_M_IX, PAGEIOLATCH_SH, etc.)\r\n- BlockingSpid: The session ID (SPID) blocking this session, or 0 if no blocking\nAdditional properties available with Select-Object *:\r\n- ResourceDesc: Detailed resource description from the wait (e.g., database:file:page IDs for page waits)\r\n- NodeId: For CXPACKET waits, the parallel exchange node ID from ResourceDesc\r\n- Dop: Degree of Parallelism for parallel execution waits; null for serial execution\r\n- DbId: Database ID where the wait is occurring\r\n- SqlText: The SQL text being executed in the waiting session (excluded from default display)\r\n- QueryPlan: The query execution plan as XML (excluded from default display)\r\n- InfoUrl: URL to SQLSkills wait type documentation for this specific wait type (excluded from default display)\nWhen -Spid is specified, only waiting tasks for those session IDs are returned. When -IncludeSystemSpid is specified, system sessions are included in results along with user sessions.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaWaitingTask -SqlInstance sqlserver2014a\nReturns the waiting task for all sessions on sqlserver2014a\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaWaitingTask -SqlInstance sqlserver2014a -IncludeSystemSpid\nReturns the waiting task for all sessions (user and system) on sqlserver2014a", "Description": "Queries sys.dm_os_waiting_tasks and related DMVs to identify sessions that are currently waiting, along with comprehensive diagnostic information including wait types, durations, blocking sessions, SQL text, and query plans. This function helps DBAs quickly identify performance bottlenecks, troubleshoot blocking issues, and analyze what\u0027s causing slowdowns in real-time. The output includes helpful context like degree of parallelism for CXPACKET waits, resource descriptions, and direct links to SQLSkills wait type documentation for further analysis.\n\nThis command is based on the waiting task T-SQL script published by Paul Randal.\nReference: https://www.sqlskills.com/blogs/paul/updated-sys-dm_os_waiting_tasks-script-2/", "Links": "https://dbatools.io/Get-DbaWaitingTask", "Synopsis": "Retrieves detailed information about currently waiting sessions and their wait types from SQL Server dynamic management views.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. Server version must be SQL Server version XXXX 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", "", "" ], [ "Spid", "Filters results to show waiting tasks for specific session IDs only. Accepts one or more SPIDs as an array.\r\nUse this when troubleshooting known problematic sessions or when you want to focus on specific user connections instead of scanning all active sessions.", "", false, "true (ByPropertyName)", "", "" ], [ "IncludeSystemSpid", "Includes system sessions (SPIDs) in the results along with user sessions. By default, only user sessions are returned.\r\nEnable this when diagnosing system-level performance issues or when system processes might be causing blocking or resource contention.", "", 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", "Pages", "DBCC" ], "CommandName": "Get-DbaWaitResource", "Name": "Get-DbaWaitResource", "Author": "Stuart Moore (@napalmgram), stuart-moore.com", "Syntax": "Get-DbaWaitResource [-SqlInstance] \u003cDbaInstanceParameter\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-WaitResource] \u003cString\u003e [-Row] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nOutput varies based on the wait resource type specified:\nPAGE Wait Resources (when WaitResource matches \u0027PAGE: dbid:fileid:pageid\u0027 format):\r\nReturns one object with the following properties:\r\n- DatabaseID: The database ID from the wait resource\r\n- DatabaseName: The name of the database containing the page\r\n- DataFileName: The logical name of the data file containing the page\r\n- DataFilePath: The physical file system path to the data file\r\n- ObjectID: The internal object ID (table or index) owning the page\r\n- ObjectName: The name of the table or index that owns the page\r\n- ObjectSchema: The schema name containing the object\r\n- ObjectType: The type of object (USER_TABLE, CLUSTERED_INDEX, NONCLUSTERED_INDEX, HEAP, etc.)\nKEY Wait Resources (when WaitResource matches \u0027KEY: hobtid (physicallocation)\u0027 format):\r\nReturns one object with the following properties:\r\n- DatabaseID: The database ID from the wait resource\r\n- DatabaseName: The name of the database containing the key\r\n- SchemaName: The schema name containing the object\r\n- IndexName: The name of the index or heap being waited on\r\n- ObjectID: The internal object ID of the table\r\n- ObjectName: The name of the table that owns the index or heap\r\n- HobtID: The heap or B-tree ID (allocation unit ID) being waited on\nWhen -Row is specified with KEY wait resources:\r\nThe output is expanded to include the actual data row from the table. The full row contents are returned as properties matching the table\u0027s column names. When the row data cannot be retrieved (row \r\nwas deleted or moved), only the key resource object properties are returned.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaWaitResource -SqlInstance server1 -WaitResource \u0027PAGE: 10:1:9180084\u0027\nWill return an object containing; database name, data file name, schema name and the object which owns the resource\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaWaitResource -SqlInstance server2 -WaitResource \u0027KEY: 7:35457594073541168 (de21f92a1572)\u0027\nWill return an object containing; database name, schema name and index name which is being waited on.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaWaitResource -SqlInstance server2 -WaitResource \u0027KEY: 7:35457594073541168 (de21f92a1572)\u0027 -row\nWill return an object containing; database name, schema name and index name which is being waited on, and in addition the contents of the locked row at the time the command is run.", "Description": "Converts cryptic wait resource identifiers from sys.dm_exec_requests into readable database object details that DBAs can actually use for troubleshooting. When you\u0027re investigating blocking chains or deadlocks, you see wait_resource values like \u0027PAGE: 10:1:9180084\u0027 or \u0027KEY: 7:35457594073541168 (de21f92a1572)\u0027 in DMVs, but these don\u0027t tell you which actual table or index is involved.\n\nFor PAGE wait resources, this function uses DBCC PAGE internally to identify the specific database, data file, schema, and object that owns the contested page. For KEY wait resources, it queries system catalog views to determine the database, schema, table, and index being waited on. With the -Row parameter, you can also retrieve the actual data from the locked row, which is invaluable for understanding what specific record is causing contention.\n\nThis eliminates the manual detective work of decoding resource IDs and saves time when you need to quickly identify the root cause of blocking issues in production environments.", "Links": "https://dbatools.io/Get-DbaWaitResource", "Synopsis": "Translates wait resource strings into human-readable database object information for troubleshooting blocking and deadlocks", "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", "", "" ], [ "WaitResource", "Specifies the cryptic wait resource identifier from sys.dm_exec_requests that you need to decode into readable database object information.\r\nAccepts PAGE format like \u0027PAGE: 10:1:9180084\u0027 or KEY format like \u0027KEY: 7:35457594073541168 (de21f92a1572)\u0027.\r\nUse this when troubleshooting blocking chains or deadlocks to identify which specific table, index, or page is causing contention.", "", true, "true (ByValue)", "", "" ], [ "Row", "Returns the actual data from the locked row in addition to the object information for KEY wait resources.\r\nProvides the specific record values that are causing the lock contention, which helps identify patterns or problematic data.\r\nOnly works with KEY wait resources and uses NOLOCK hint to retrieve the current row data safely.", "", 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", "Waits", "WaitStats" ], "CommandName": "Get-DbaWaitStatistic", "Name": "Get-DbaWaitStatistic", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaWaitStatistic [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Threshold] \u003cInt32\u003e] [-IncludeIgnorable] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per wait type found in sys.dm_os_wait_stats matching the specified threshold criteria. Each object contains detailed wait statistics and diagnostic information for a specific SQL \r\nServer wait type.\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- WaitType: The name of the SQL Server wait type (e.g., PAGEIOLATCH_EX, LCK_M_IX)\r\n- Category: The wait category classification (e.g., Buffer IO, Lock, Network IO, CPU, Idle, Memory, etc.)\r\n- WaitSeconds: Total time in seconds the system has waited on this wait type (decimal)\r\n- ResourceSeconds: Time in seconds spent waiting for a resource to become available (decimal)\r\n- SignalSeconds: Time in seconds spent waiting for a signal after acquiring the resource (decimal)\r\n- WaitCount: Total number of times this wait type has occurred (bigint)\r\n- Percentage: Percentage of total system wait time consumed by this wait type (0-100, decimal)\r\n- AverageWaitSeconds: Average time per wait occurrence in seconds (decimal)\r\n- AverageResourceSeconds: Average resource wait time per occurrence in seconds (decimal)\r\n- AverageSignalSeconds: Average signal wait time per occurrence in seconds (decimal)\r\n- URL: Hyperlink to sqlskills.com detailed documentation for this wait type (XML/string)\nAdditional properties available (use Select-Object *):\r\n- Notes: Detailed diagnostic explanation of the wait type and troubleshooting guidance from Paul Randal\u0027s methodology (when using Select-Object *)\r\n- Ignorable: Boolean indicating whether this wait type is typically safe to ignore during troubleshooting (only shown when -IncludeIgnorable is specified)\nWhen -IncludeIgnorable is not specified, the Notes and Ignorable properties are excluded from output. Use Select-Object * to access all properties including detailed diagnostic notes for each wait \r\ntype.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaWaitStatistic -SqlInstance sql2008, sqlserver2012\nCheck wait statistics for servers sql2008 and sqlserver2012\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaWaitStatistic -SqlInstance sql2008 -Threshold 98 -IncludeIgnorable\nCheck wait statistics on server sql2008 for thresholds above 98% and include wait stats that are most often, but not always, ignorable\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaWaitStatistic -SqlInstance sql2008 | Select-Object *\nShows detailed notes, if available, from Paul\u0027s post\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$output = Get-DbaWaitStatistic -SqlInstance sql2008 -Threshold 100 -IncludeIgnorable | Select-Object * | ConvertTo-DbaDataTable\nCollects all Wait Statistics (including ignorable waits) on server sql2008 into a Data Table.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$output = Get-DbaWaitStatistic -SqlInstance sql2008\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 SQL Server wait statistics from sys.dm_os_wait_stats to identify performance bottlenecks and resource contention issues. This function categorizes wait types, calculates timing metrics and percentages, and provides diagnostic explanations based on Paul Randal\u0027s methodology. Use this to pinpoint whether your SQL Server is waiting on disk I/O, memory pressure, locking issues, or other resource constraints that are slowing down query performance.\n\nReturns:\nWaitType\nCategory\nWaitSeconds\nResourceSeconds\nSignalSeconds\nWaitCount\nPercentage\nAverageWaitSeconds\nAverageResourceSeconds\nAverageSignalSeconds\nURL\n\nReference: https://www.sqlskills.com/blogs/paul/wait-statistics-or-please-tell-me-where-it-hurts/", "Links": "https://dbatools.io/Get-DbaWaitStatistic", "Synopsis": "Retrieves SQL Server wait statistics for performance analysis and troubleshooting", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. 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", "Sets the cumulative percentage threshold for filtering wait statistics results. Only wait types that fall within this percentage of total wait time are returned.\r\nUse this to focus on the most significant waits rather than seeing every minor wait type on your system. For example, 95% shows waits that make up 95% of all wait time.", "", false, "false", "95", "" ], [ "IncludeIgnorable", "Includes wait types that are typically benign and can be safely ignored during troubleshooting, such as Service Broker idle waits and background task waits.\r\nUse this when you need to see all wait activity or when investigating unusual issues with specific features like mirroring or Availability Groups.", "", 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": [ "Logging", "OS" ], "CommandName": "Get-DbaWindowsLog", "Name": "Get-DbaWindowsLog", "Author": "Drew Furgiuele | Friedrich Weinmann (@FredWeinmann)", "Syntax": "Get-DbaWindowsLog [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-Start] \u003cDateTime\u003e] [[-End] \u003cDateTime\u003e] [[-Credential] \u003cPSCredential\u003e] [[-MaxThreads] \u003cInt32\u003e] [[-MaxRemoteThreads] \u003cInt32\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per parsed error log entry found in SQL Server error log files within the specified time range. Each object contains details about a single error log record including timestamp, \r\nSPID, severity, error number, and the log message.\nProperties:\r\n- InstanceName: The SQL Server instance name where the log entry originated (format: ComputerName\\InstanceName or ComputerName for default instance)\r\n- Timestamp: The date and time when the error log entry was recorded (DateTime)\r\n- Spid: The SQL Server process ID (SPID) associated with the log entry; typically a string value like \"s\", \"sa\", \"sr\" for system processes (string)\r\n- Severity: The severity level of the error (0-25 numeric scale; 10+ indicates user errors, lower values indicate informational messages, string representation)\r\n- ErrorNumber: The SQL Server error number; 0 for informational messages, \u003e0 for actual errors (int)\r\n- State: The error state number providing additional diagnostic context for the error (int)\r\n- Message: The full text of the error log message (string)\nNote: The function parses raw SQL Server error log files using regular expressions. Only entries matching the error log format pattern are returned. Non-matching log entries are silently skipped. \r\nResults are always output as log entries are parsed during the remote execution, not held in memory.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$ErrorLogs = Get-DbaWindowsLog -SqlInstance sql01\\sharepoint\nPS C:\\\u003e $ErrorLogs | Where-Object ErrorNumber -eq 18456\nReturns all lines in the errorlogs that have event number 18456 in them\nThis exists to ignore the Script Analyzer rule for Start-Runspace", "Description": "Parses SQL Server error log files directly from the file system to extract structured error information including timestamps, SPIDs, error numbers, severity levels, and messages. Locates error log files by querying Windows Application Event Log for SQL Server startup events (Event ID 17111), then reads and parses the raw log files to provide searchable, filterable results. This is essential for troubleshooting SQL Server issues, compliance reporting, and proactive monitoring since it gives you programmatic access to detailed error information that would otherwise require manual log file review.", "Links": "https://dbatools.io/Get-DbaWindowsLog", "Synopsis": "Retrieves and parses SQL Server error log entries from the file system for analysis and troubleshooting", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The instance(s) to retrieve the event logs from", "", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Start", "Filters log entries to include only those occurring after this timestamp. Defaults to January 1, 1970.\r\nUse this to focus on recent issues or events within a specific timeframe when troubleshooting SQL Server problems.", "", false, "false", "1/1/1970 00:00:00", "" ], [ "End", "Filters log entries to include only those occurring before this timestamp. Defaults to the current date and time.\r\nCombine with Start parameter to create specific time windows for analyzing SQL Server events during known problem periods.", "", false, "false", "(Get-Date)", "" ], [ "Credential", "Credential to be used to connect to the Server. Note this is a Windows credential, as this command requires we communicate with the computer and not with the SQL instance.", "", false, "false", "", "" ], [ "MaxThreads", "Controls the maximum number of parallel threads used on the local computer for processing multiple SQL instances. Defaults to unlimited.\r\nSet a specific limit when processing many instances simultaneously to prevent overwhelming the local system with too many concurrent operations.", "", false, "false", "0", "" ], [ "MaxRemoteThreads", "Sets the maximum number of parallel threads executed on each target SQL Server for processing error log files. Defaults to 2.\r\nKeep this low to avoid excessive CPU load on production servers, as log file parsing is CPU-intensive. Set to 0 or below to remove the limit entirely.", "", false, "false", "2", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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": [ "WSFC", "FCI", "WindowsCluster", "HA" ], "CommandName": "Get-DbaWsfcAvailableDisk", "Name": "Get-DbaWsfcAvailableDisk", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaWsfcAvailableDisk [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.Management.Infrastructure.CimInstance#root/MSCluster/MSCluster_AvailableDisk\nReturns one object per available disk that can be added to the cluster. The disk must be visible to all cluster nodes to be considered available.\nAll properties from the MSCluster_AvailableDisk WMI class are returned, including:\nProperties added via Add-Member:\r\n- State: Current operational state of the disk\r\n- ClusterName: Name of the cluster\r\n- ClusterFqdn: Fully qualified domain name of the cluster\nStandard WMI properties from MSCluster_AvailableDisk:\r\n- Name: Label or designation of the disk\r\n- Id: Unique disk identifier (GUID for virtual disks, GptGuid or Signature for physical disks)\r\n- Size: Physical disk capacity in bytes\r\n- Number: Disk number as seen on the host node\r\n- Status: Operational status (OK, Degraded, Error, etc.)\r\n- ConnectedNodes: Array of cluster node names that can access the disk\r\n- Signature: MBR disk signature value\r\n- GptGuid: GUID for GPT-partitioned disks\r\n- ScsiPort: SCSI port number\r\n- ScsiBus: SCSI bus identifier\r\n- ScsiTargetID: SCSI target identification number\r\n- ScsiLUN: SCSI logical unit number\r\n- Node: Name of the node providing the disk information\r\n- ResourceName: Resource name when adding disk to cluster\nAll properties from the base WMI object are accessible; the function returns the complete object without filtering.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaWsfcAvailableDisk -ComputerName cluster01\nGets available disks from the failover cluster cluster01", "Description": "Identifies shared storage disks that are visible to all cluster nodes and eligible for clustering, but have not yet been added to the cluster\u0027s storage pool. This is essential when planning to expand SQL Server Failover Cluster Instances (FCIs) or troubleshooting storage connectivity issues. The function queries each cluster node to ensure disks are properly accessible across the entire cluster before attempting to add them as cluster resources.\n\nAll Windows Server Failover Clustering (Wsfc) commands require local admin on each member node.", "Links": "https://dbatools.io/Get-DbaWsfcAvailableDisk", "Synopsis": "Retrieves shared storage disks available for clustering but not yet assigned to a Windows Server Failover Cluster.", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the Windows Server Failover Cluster name or any cluster node name to query for available disks.\r\nUse this when you need to check shared storage from a specific cluster, especially when managing multiple clusters or troubleshooting storage visibility across cluster nodes.\r\nAccepts multiple values to query several clusters simultaneously.", "", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Allows you to login to the cluster 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": [ "WSFC", "FCI", "WindowsCluster", "HA" ], "CommandName": "Get-DbaWsfcCluster", "Name": "Get-DbaWsfcCluster", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaWsfcCluster [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.Management.Infrastructure.CimInstance#root/MSCluster/MSCluster_Cluster\nReturns one cluster object per target cluster specified via ComputerName parameter. Each object contains cluster-wide configuration and status information.\nDefault display properties (via Select-DefaultView):\r\n- Name: The name of the cluster\r\n- Fqdn: Fully qualified domain name of the cluster\r\n- State: Current operational state of the cluster (added via NoteProperty)\r\n- DrainOnShutdown: Boolean indicating if nodes drain resources during service shutdown (uint32)\r\n- DynamicQuorumEnabled: Boolean indicating if dynamic quorum adjustment is enabled (uint32)\r\n- EnableSharedVolumes: Boolean indicating if Cluster Shared Volumes feature is enabled (uint32)\r\n- SharedVolumesRoot: The root directory path for Cluster Shared Volumes\r\n- QuorumPath: File system path where quorum files are maintained\r\n- QuorumType: Current quorum type as a string (Majority Node Majority, Node and Disk Majority, No Majority - Disk Only, Node Majority, or Witness)\r\n- QuorumTypeValue: Numeric identifier representing the quorum type (uint32)\r\n- RequestReplyTimeout: Timeout period in milliseconds for request-reply operations (uint32)\nAdditional properties from MSCluster_Cluster WMI class (accessible via Select-Object *):\r\n- Caption: Short text description of the cluster\r\n- Description: Detailed cluster description\r\n- InstallDate: DateTime when the cluster was installed\r\n- Status: Cluster operational status string\r\n- AddEvictDelay: Seconds between node eviction and new node admission\r\n- AdminAccessPoint: Type of cluster administrative access point\r\n- BackupInProgress: Indicates if cluster backup is running\r\n- ClusterEnforcedAntiAffinity: Hard enforcement status of group anti-affinity\r\n- ClusterFunctionalLevel: Current cluster functional level\r\n- ClusterLogLevel: Cluster logging verbosity level\r\n- ClusterLogSize: Maximum log file size per node\r\n- ClusSvcHangTimeout: Heartbeat timeout before node considered hung\r\n- CrossSiteDelay: Heartbeat delay between sites in milliseconds\r\n- CrossSiteThreshold: Missed heartbeats before cross-site failure detected\r\n- CrossSubnetDelay: Heartbeat delay between subnets in milliseconds\r\n- CrossSubnetThreshold: Missed heartbeats before cross-subnet failure detected\r\n- CsvBalancer: Automatic CSV balancing enabled status\r\n- GracePeriodEnabled: Node grace period feature status\r\n- GracePeriodTimeout: Grace period timeout in milliseconds\r\n- IgnorePersistentStateOnStartup: Whether cluster brings online previously running groups\r\n- MaxNumberOfNodes: Maximum nodes allowed in cluster\r\n- NetftIPSecEnabled: IPSec security for internal cluster traffic\r\n- PrimaryOwnerName: Primary cluster owner name\r\n- PrimaryOwnerContact: Primary owner contact information\r\n- S2DEnabled: Storage Spaces Direct feature enablement\r\n- SameSubnetDelay: Heartbeat delay on same subnet in milliseconds\r\n- SameSubnetThreshold: Missed heartbeats on same subnet before failure detected\r\n- SharedVolumeCompatibleFilters: Filters compatible with direct I/O\r\n- SharedVolumeIncompatibleFilters: Filters that prevent direct I/O usage\r\n- S2DCacheBehavior, S2DCacheDeviceModel, S2DIOLatencyThreshold: Storage Spaces Direct configuration options\r\n- WitnessDynamicWeight: Configured witness weight for quorum calculations\r\n- All other properties defined in the MSCluster_Cluster WMI class\nAll properties from the base WMI object are accessible using Select-Object *. Use Select-Object * to see properties not shown in the default view, as noted in the second example.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaWsfcCluster -ComputerName cluster01\nGets failover cluster information about cluster01\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaWsfcCluster -ComputerName cluster01 | Select-Object *\nShows all cluster values, including the ones not shown in the default view", "Description": "Retrieves detailed configuration and operational status information from Windows Server Failover Clusters that host SQL Server instances. This function connects to cluster nodes or the cluster name itself to gather essential cluster properties including quorum configuration, shared volume settings, and current operational state.\n\nDBAs use this when troubleshooting cluster issues, validating cluster health before SQL Server installations, or documenting high availability configurations. The function returns key cluster metadata needed for capacity planning and disaster recovery preparation.\n\nAll Windows Server Failover Clustering (Wsfc) commands require local admin on each member node.", "Links": "https://dbatools.io/Get-DbaWsfcCluster", "Synopsis": "Retrieves Windows Server Failover Cluster configuration and status information for SQL Server high availability environments.", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the target Windows Server Failover Cluster to query, either by cluster name or individual node name.\r\nUse the cluster name when connecting to an active cluster, or specify a node name when the cluster service may be down.\r\nDefaults to the local computer if not specified.", "", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Allows you to login to the cluster 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": [ "WSFC", "FCI", "WindowsCluster", "HA" ], "CommandName": "Get-DbaWsfcDisk", "Name": "Get-DbaWsfcDisk", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaWsfcDisk [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per clustered disk partition found on the failover cluster.\nDefault display properties (via Select-DefaultView):\r\n- ClusterName: The name of the Windows Server Failover Cluster\r\n- ClusterFqdn: The fully qualified domain name of the cluster\r\n- ResourceGroup: The owner group of the disk resource\r\n- Disk: The disk resource name\r\n- State: The current state of the disk resource\r\n- FileSystem: The file system type (NTFS, ReFS, etc.)\r\n- Path: The mount path of the disk partition\r\n- Label: The volume label assigned to the disk\r\n- Size: Total size of the disk partition; dbasize object convertible to Bytes, KB, MB, GB, TB\r\n- Free: Free space available on the disk partition; dbasize object with unit conversion\r\n- SerialNumber: The serial number of the physical disk\nAdditional properties available (using Select-Object *):\r\n- MountPoints: Array of mount points for the disk partition\r\n- ClusterDisk: The CIM MSCluster_Disk object representing the physical disk\r\n- ClusterDiskPart: The CIM MSCluster_DiskPartition object with full partition metadata\r\n- ClusterResource: The CIM MSCluster_Resource object representing the cluster resource", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaWsfcDisk -ComputerName cluster01\nGets disk information from the failover cluster cluster01", "Description": "Retrieves comprehensive disk information from Windows Server Failover Clusters including disk space usage, file systems, mount points, and cluster resource states. This function is essential for DBAs managing SQL Server Failover Cluster Instances who need to monitor storage health and capacity across cluster nodes. Returns detailed disk properties like total size, free space, volume labels, and serial numbers for each clustered disk resource, helping identify storage bottlenecks and plan capacity upgrades.\n\nAll Windows Server Failover Clustering (Wsfc) commands require local admin on each member node.", "Links": "https://dbatools.io/Get-DbaWsfcDisk", "Synopsis": "Retrieves detailed information about clustered physical disks from Windows Server Failover Clusters.", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the Windows Server Failover Cluster to query for disk information. Accepts either a cluster node name or the cluster name itself.\r\nUse this when managing SQL Server Failover Cluster Instances to monitor storage across different cluster environments.", "", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Allows you to login to the cluster 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": [ "WSFC", "FCI", "WindowsCluster", "HA" ], "CommandName": "Get-DbaWsfcNetwork", "Name": "Get-DbaWsfcNetwork", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaWsfcNetwork [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per cluster network found on the Windows Server Failover Cluster.\nProperties:\r\n- ClusterName: The name of the Windows Server Failover Cluster\r\n- ClusterFqdn: The fully qualified domain name of the cluster\r\n- Name: The network name within the cluster configuration\r\n- Address: The network address (IP address or network identifier)\r\n- AddressMask: The subnet mask or network address mask\r\n- IPv4Addresses: Array of IPv4 addresses assigned to this cluster network\r\n- IPv4PrefixLengths: Array of IPv4 prefix lengths corresponding to IPv4Addresses\r\n- IPv6Addresses: Array of IPv6 addresses assigned to this cluster network\r\n- IPv6PrefixLengths: Array of IPv6 prefix lengths corresponding to IPv6Addresses\r\n- QuorumType: The quorum type indicator (numeric value)\r\n- QuorumTypeValue: The quorum type value representation\r\n- RequestReplyTimeout: The request/reply timeout value in milliseconds\r\n- Role: The role of the network in the cluster (cluster, client, etc.)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaWsfcNetwork -ComputerName cluster01\nGets network information from the failover cluster cluster01", "Description": "Retrieves detailed network information from Windows Server Failover Cluster nodes, including IP addresses, subnet masks, and network roles. This information is essential for diagnosing connectivity issues with SQL Server Failover Cluster Instances (FCIs) and Availability Groups, especially when troubleshooting network-related failures or validating cluster network configuration. The function returns comprehensive network details like IPv4/IPv6 addresses, prefix lengths, and quorum settings that help DBAs understand how cluster networks are configured and identify potential communication problems between nodes.\n\nAll Windows Server Failover Clustering (Wsfc) commands require local admin on each member node.", "Links": "https://dbatools.io/Get-DbaWsfcNetwork", "Synopsis": "Retrieves network configuration details from Windows Server Failover Clustering for SQL Server high availability troubleshooting.", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the Windows Server Failover Cluster name or any cluster node name to retrieve network configuration from.\r\nUse this to target a specific cluster when troubleshooting network connectivity issues with SQL Server FCIs or Availability Groups.\r\nAccepts multiple cluster names for bulk network configuration analysis.", "", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Allows you to login to the cluster 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": [ "WSFC", "FCI", "WindowsCluster", "HA" ], "CommandName": "Get-DbaWsfcNetworkInterface", "Name": "Get-DbaWsfcNetworkInterface", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaWsfcNetworkInterface [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.Management.ManagementObject\nReturns one network interface object per adapter found on cluster nodes queried. Each object represents a network interface configuration with IP address and DHCP settings.\nDefault display properties (via Select-DefaultView):\r\n- ClusterName: The name of the Windows Server Failover Cluster\r\n- ClusterFqdn: The fully qualified domain name of the cluster\r\n- Name: The name of the network interface\r\n- Network: The name or identifier of the network this interface belongs to\r\n- Node: The name of the cluster node this interface is assigned to\r\n- Adapter: The network adapter identifier or friendly name\r\n- Address: The IP address assigned to this interface\r\n- DhcpEnabled: Boolean indicating if DHCP is enabled for this interface\r\n- IPv4Addresses: String array of IPv4 addresses configured on this interface\r\n- IPv6Addresses: String array of IPv6 addresses configured on this interface\nAdditional properties available via Select-Object *:\r\nAll properties from the MSCluster_NetworkInterface WMI class, including network role, state, and adapter-level details.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaWsfcNetworkInterface -ComputerName cluster01\nGets network interface information from the failover cluster cluster01\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaWsfcNetworkInterface -ComputerName cluster01 | Select-Object *\nShows all network interface values, including the ones not shown in the default view", "Description": "Retrieves detailed network adapter information from all nodes in a Windows Server Failover Cluster, including IP addresses, DHCP settings, and network assignments. This information is essential for troubleshooting SQL Server Failover Cluster Instance connectivity issues and verifying cluster network configuration.\n\nUse this command to identify network misconfigurations that could impact SQL Server availability, document cluster network topology for compliance, or diagnose connectivity problems between cluster nodes.\n\nAll Windows Server Failover Clustering (Wsfc) commands require local admin on each member node.", "Links": "https://dbatools.io/Get-DbaWsfcNetworkInterface", "Synopsis": "Retrieves network interface configuration from Windows Server Failover Cluster nodes.", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the Windows Server Failover Cluster name or any cluster node name to query for network interface information.\r\nUse this when troubleshooting SQL Server FCI connectivity issues or documenting cluster network topology.\r\nAccepts cluster names, node names, or IP addresses of cluster resources.", "", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Allows you to login to the cluster 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": [ "WSFC", "FCI", "WindowsCluster", "HA" ], "CommandName": "Get-DbaWsfcNode", "Name": "Get-DbaWsfcNode", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaWsfcNode [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.Management.ManagementObject\nReturns one node object per cluster member node queried. Each object represents a cluster node with ownership and version information.\nDefault display properties (via Select-DefaultView):\r\n- ClusterName: The name of the Windows Server Failover Cluster\r\n- ClusterFqdn: The fully qualified domain name of the cluster\r\n- Name: The name of the cluster node (server name)\r\n- PrimaryOwnerName: The primary owner of the node resource\r\n- PrimaryOwnerContact: Contact information for the primary owner\r\n- Dedicated: Boolean indicating if the node is dedicated to clustering\r\n- NodeHighestVersion: The highest cluster API version supported by this node\r\n- NodeLowestVersion: The lowest cluster API version supported by this node\nAdditional properties available via Select-Object *:\r\nAll properties from the MSCluster_Node WMI class, including node state, resource ownership, and cluster communication details.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaWsfcNode -ComputerName cluster01\nGets node information from the failover cluster cluster01\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaWsfcNode -ComputerName cluster01 | Select-Object *\nShows all node values, including the ones not shown in the default view", "Description": "Retrieves configuration and status details for individual nodes (servers) within Windows Server Failover Clusters that host SQL Server FCIs or Availability Groups. This function connects to cluster nodes to gather essential node properties including ownership details, version information, and operational status.\n\nDBAs use this when troubleshooting cluster node issues, validating node configurations before SQL Server failover operations, or auditing cluster member server details. The function returns key node metadata needed for capacity planning, patch management coordination, and high availability troubleshooting.\n\nAll Windows Server Failover Clustering (Wsfc) commands require local admin on each member node.", "Links": "https://dbatools.io/Get-DbaWsfcNode", "Synopsis": "Retrieves detailed node information from Windows Server Failover Clusters hosting SQL Server instances.", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the Windows Server Failover Cluster or individual cluster node to query for node information. Accepts either the cluster name or any member node name.\r\nUse this when you need to connect to a specific cluster hosting SQL Server FCIs or Availability Groups to retrieve node details.", "", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Allows you to login to the cluster 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": [ "WSFC", "FCI", "WindowsCluster", "HA" ], "CommandName": "Get-DbaWsfcResource", "Name": "Get-DbaWsfcResource", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaWsfcResource [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "MSCluster_Resource (with added NoteProperties)\nReturns one resource object per cluster resource found in the specified Windows Server Failover Cluster. Each resource represents a clustered component such as a physical disk, IP address, SQL Server \r\ninstance, or network name.\nDefault display properties (via Select-DefaultView):\r\n- ClusterName: The name of the Windows Server Failover Cluster\r\n- ClusterFqdn: The fully qualified domain name of the cluster\r\n- Name: The resource name\r\n- State: Current operational status of the resource (Online, Offline, Failed, Initializing, Pending, Unknown, etc.)\r\n- Type: The resource type (e.g., \"Physical Disk\", \"IP Address\", \"Network Name\")\r\n- OwnerGroup: The resource group this resource belongs to\r\n- OwnerNode: The cluster node currently hosting this resource\r\n- PendingTimeout: Timeout in milliseconds for bringing resource online/offline (typically 180000 ms / 3 minutes)\r\n- PersistentState: Boolean indicating whether resource should be online when Cluster Service starts\r\n- QuorumCapable: Boolean indicating if the resource can be selected as quorum resource\r\n- RequiredDependencyClasses: Array of resource classes this resource depends on\r\n- RequiredDependencyTypes: Array of resource types that are required dependencies\r\n- RestartAction: Action on failure - Do Not Restart (0), Restart Without Failover (1), Restart With Failover (2)\r\n- RestartDelay: Time delay in milliseconds before restart attempt\r\n- RestartPeriod: Interval in milliseconds for restart attempt tracking\r\n- RestartThreshold: Maximum number of restart attempts within RestartPeriod\r\n- RetryPeriodOnFailure: Interval in milliseconds before retrying a failed resource\r\n- SeparateMonitor: Boolean indicating if resource requires isolated Resource Monitor process\nAdditional properties available (WMI MSCluster_Resource object):\r\n- Id: Unique identifier for the resource\r\n- CoreResource: Boolean indicating if resource is essential to cluster\r\n- IsAlivePollInterval: Polling interval in milliseconds for operational checks\r\n- LooksAlivePollInterval: Polling interval in milliseconds for appearance checks\r\n- DeadlockTimeout: Timeout in milliseconds for deadlock detection\r\n- Status: Status message string (e.g., \"OK\", \"Error\", \"Degraded\")\r\n- ResourceSpecificStatus: Resource-specific status information\r\n- IsClusterSharedVolume: Boolean indicating if resource is a cluster shared volume\r\n- MonitorProcessId: Process ID of resource monitor managing this resource\r\n- Characteristics: Resource characteristics flags\r\n- Flags: Resource configuration flags\r\n- InstallDate: DateTime when resource was installed\r\n- Caption: Short description of the resource\r\n- CryptoCheckpoints: Array of encrypted checkpoints for resource backup/restore\r\n- RegistryCheckpoints: Array of registry checkpoints for resource backup/restore\r\n- LocalQuorumCapable: Boolean indicating if usable as quorum in local quorum clusters\r\n- ResourceClass: Classification (Storage, Network, User)\nAll properties from the WMI MSCluster_Resource class are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaWsfcResource -ComputerName cluster01\nGets resource information from the failover cluster cluster01\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaWsfcResource -ComputerName cluster01 | Select-Object *\nShows all resource values, including the ones not shown in the default view", "Description": "Retrieves comprehensive information about cluster resources including SQL Server instances, disks, network names, and other services managed by the failover cluster. Shows current state, ownership, dependencies, restart policies, and timeout settings for each resource, which is essential for troubleshooting cluster issues and monitoring SQL Server FCI health.\n\nUse this when diagnosing cluster resource failures, planning maintenance windows, or investigating why SQL Server services aren\u0027t failing over properly. The state information helps identify stuck resources, while ownership details show which node currently hosts each resource.\n\nAll Windows Server Failover Clustering (Wsfc) commands require local admin on each member node.", "Links": "https://dbatools.io/Get-DbaWsfcResource", "Synopsis": "Retrieves detailed information about cluster resources in a Windows Server Failover Cluster", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the target cluster to query for resource information. Can be any cluster node name or the cluster name itself.\r\nUse this when managing multiple clusters or when connecting from outside the cluster to gather resource status and configuration details.", "", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Allows you to login to the cluster 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": [ "WSFC", "FCI", "WindowsCluster", "HA" ], "CommandName": "Get-DbaWsfcResourceGroup", "Name": "Get-DbaWsfcResourceGroup", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaWsfcResourceGroup [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-Name] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.Management.Infrastructure.CimInstance#root/MSCluster/MSCluster_ResourceGroup\nReturns one resource group object per resource group found on the specified Windows Server Failover Cluster.\nDefault display properties (via Select-DefaultView):\r\n- ClusterName: The name of the Windows Server Failover Cluster\r\n- ClusterFqdn: The fully qualified domain name of the cluster\r\n- Name: The name of the resource group\r\n- State: Current resource group state (Online, Offline, Failed, or Unknown)\r\n- PersistentState: The desired persistent state of the resource group\r\n- OwnerNode: The cluster node that currently owns this resource group\nAdditional properties available from WMI MSCluster_ResourceGroup object (via Select-Object *):\r\n- Characteristics: Resource group characteristics bitmask\r\n- CreationTime: DateTime when the resource group was created\r\n- Description: Text description of the resource group\r\n- Flags: Resource group flags\r\n- GroupType: Type of resource group\r\n- PrivateProperties: Collection of private property objects\r\n- ResourceType: The resource type of this group\r\n- StateInfo: Detailed state information\r\n- Topology: Cluster topology information", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaWsfcResourceGroup -ComputerName cluster01\nGets resource group information from the failover cluster cluster01\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaWsfcResourceGroup -ComputerName cluster01 | Select-Object *\nShows all resource values, including the ones not shown in the default view", "Description": "Retrieves detailed information about Windows Server Failover Cluster resource groups, including their current state, persistent state, and which node currently owns them. This function helps DBAs monitor and troubleshoot SQL Server Failover Cluster Instances and Availability Groups by providing visibility into the underlying cluster resource groups that control SQL Server services and resources.\n\nUse this command when you need to verify resource group health during maintenance windows, troubleshoot failover issues, or confirm which node is currently hosting specific SQL Server resources. The function translates numeric state codes into readable status values (Online, Offline, Failed, Unknown) so you can quickly identify problematic resource groups.\n\nAll Windows Server Failover Clustering (Wsfc) commands require local admin on each member node.", "Links": "https://dbatools.io/Get-DbaWsfcResourceGroup", "Synopsis": "Retrieves Windows Server Failover Cluster resource group status and ownership information", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the target Windows Server Failover Cluster to query, either as a cluster name or any node name within the cluster.\r\nUse this when connecting to specific failover clusters hosting SQL Server FCI or Availability Group resources.\r\nDefaults to the local computer if not specified.", "", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Allows you to login to the cluster using alternative credentials.", "", false, "false", "", "" ], [ "Name", "Filters results to only include resource groups with the specified names. Supports multiple values.\r\nUse this when you need to check specific SQL Server resource groups like \u0027SQL Server (MSSQLSERVER)\u0027 or named Availability Groups.\r\nOmit this parameter to retrieve all resource groups in the cluster.", "", 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": [ "WSFC", "FCI", "WindowsCluster", "HA" ], "CommandName": "Get-DbaWsfcResourceType", "Name": "Get-DbaWsfcResourceType", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaWsfcResourceType [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.Management.Infrastructure.CimInstance#root/MSCluster/MSCluster_ResourceType\nReturns one resource type object per resource type available in the Windows Server Failover Cluster. Resource types represent the available building blocks for creating cluster resources such as SQL \r\nServer instances, network names, and shared storage.\nDefault display properties (via Select-DefaultView):\r\n- ClusterName: Name of the cluster containing this resource type\r\n- ClusterFqdn: Fully qualified domain name of the cluster\r\n- Name: Name of the resource type (key property)\r\n- DisplayName: Displayed name for the resource type shown in user interfaces\r\n- DllName: File name of the dynamic-link library that implements the resource type\r\n- RequiredDependencyTypes: Array of resource type names that resources of this type must depend on (Windows Server 2012+)\nAdditional properties available (from WMI MSCluster_ResourceType object):\r\n- Caption: Short textual description of the resource type\r\n- Description: Detailed description of the resource type\r\n- Characteristics: Bit flags defining resource type characteristics\r\n- Flags: Resource type flags\r\n- ResourceClass: Classification of resource type (Storage, Network, User, Unknown)\r\n- QuorumCapable: Boolean indicating if resource can be selected as quorum resource\r\n- IsAlivePollInterval: Recommended poll interval in milliseconds for liveness checks\r\n- LooksAlivePollInterval: Recommended poll interval in milliseconds for operational status checks\r\n- DeadlockTimeout: Milliseconds before declaring a deadlock in resource calls\r\n- PendingTimeout: Milliseconds before forcibly terminating unresponsive resources\r\n- AdminExtensions: Class identifiers for Cluster Administrator extension DLLs\r\n- Status: Current operational status of the resource type\nAll properties from the WMI MSCluster_ResourceType object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaWsfcResourceType -ComputerName cluster01\nGets resource type information from the failover cluster cluster01", "Description": "Retrieves detailed information about all resource types available in a Windows Server Failover Cluster. Resource types define what kinds of cluster resources can be created, including SQL Server instances, network names, IP addresses, and shared storage. This information is essential when configuring or troubleshooting SQL Server Failover Cluster Instances (FCI), as it shows which resource types are installed and their dependencies.\n\nReturns resource type properties including display names, DLL locations, and required dependency relationships. This helps DBAs understand the available building blocks for creating clustered SQL Server resources and diagnose configuration issues.\n\nAll Windows Server Failover Clustering (Wsfc) commands require local admin on each member node.", "Links": "https://dbatools.io/Get-DbaWsfcResourceType", "Synopsis": "Retrieves available resource types from Windows Server Failover Cluster for SQL Server FCI configuration.", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the target Windows Server Failover Cluster by providing either a cluster node name or the cluster name itself.\r\nUse this when connecting to a specific cluster to retrieve its available resource types for SQL Server FCI planning or troubleshooting.\r\nDefaults to the local computer name if not specified.", "", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Allows you to login to the cluster 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": [ "WSFC", "FCI", "WindowsCluster", "HA" ], "CommandName": "Get-DbaWsfcRole", "Name": "Get-DbaWsfcRole", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaWsfcRole [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.Management.Infrastructure.CimInstance#root/MSCluster/MSCluster_ResourceGroup\nReturns one resource group (role) object per cluster role found in the Windows Server Failover Cluster. Resource groups bundle together related cluster resources and manage their failover behavior as \r\na single unit.\nDefault display properties (via Select-DefaultView):\r\n- ClusterName: Name of the cluster containing this role\r\n- ClusterFqdn: Fully qualified domain name of the cluster\r\n- Name: Name of the resource group (key property), typically the cluster role name (e.g., SQL Server instance name)\r\n- OwnerNode: Name of the node currently hosting this resource group\r\n- State: Current state of the resource group translated to readable format (Online, Offline, Failed, Partial Online, Pending, or Unknown)\nAdditional properties available (from WMI MSCluster_ResourceGroup object):\r\n- Caption: Short textual description of the resource group\r\n- Description: Detailed comments about the resource group\r\n- Id: Network identifier for the group\r\n- Status: Current status string (OK, Error, Degraded, Unknown, etc.)\r\n- InstallDate: DateTime when the group was created\r\n- Characteristics: Bit flags defining group characteristics\r\n- Flags: Flags set for the group\r\n- DefaultOwner: Node number where group was last activated or moved (node preferences)\r\n- AutoFailbackType: Whether automatic failback to preferred owner is enabled (0=Prevent, 1=Allow)\r\n- FailbackWindowStart: Earliest hour (local cluster time) group can move back to preferred node (-1 to 23)\r\n- FailbackWindowEnd: Latest hour group can move back to preferred node (-1 to 23)\r\n- FailoverPeriod: Hours during which failover threshold applies (1-1193 hours)\r\n- FailoverThreshold: Maximum number of failover attempts allowed within FailoverPeriod\r\n- PersistentState: Whether group stays offline or comes online when Cluster service starts\r\n- Priority: Priority value for the resource group (0-4999)\r\n- AntiAffinityClassNames: Groups that should not be hosted on the same cluster node\r\n- GroupType: Type of resource group (cluster, SQL Server instance, file server, virtual machine, etc.)\r\n- IsCore: Boolean indicating if group is essential cluster group that cannot be deleted\r\n- CCFEpoch: Current CCF (Cluster Configuration Fence) of the resource group (Windows Server 2016+)\r\n- ResiliencyPeriod: Resiliency period in seconds (Windows Server 2016+)\nAll properties from the WMI MSCluster_ResourceGroup object are accessible using Select-Object *. Use Select-Object * to view all available properties including dynamically populated values based on \r\ncurrent cluster state.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaWsfcRole -ComputerName cluster01\nGets role information from the failover cluster cluster01\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaWsfcRole -ComputerName cluster01 | Select-Object *\nShows all role values, including the ones not shown in the default view", "Description": "Retrieves detailed information about Windows Server Failover Cluster roles (resource groups), including their current state, and which node currently owns them. This function helps DBAs monitor and troubleshoot SQL Server Failover Cluster Instances and Availability Groups by providing visibility into the underlying cluster roles that control SQL Server services and resources.\n\nUse this command when you need to verify role health during maintenance windows, troubleshoot failover issues, or confirm which node is currently hosting specific SQL Server resources. The function translates numeric state codes into readable status values (Online, Offline, Failed, Pending) so you can quickly identify problematic roles.\n\nAll Windows Server Failover Clustering (Wsfc) commands require local admin on each member node.", "Links": "https://dbatools.io/Get-DbaWsfcRole", "Synopsis": "Retrieves Windows Server Failover Cluster role status and ownership information for SQL Server monitoring", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the cluster node name or cluster name to connect to for retrieving role information. Accepts multiple values for querying multiple clusters.\r\nUse this when you need to check role status on remote clusters or when working with multiple cluster environments.", "", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Allows you to login to the cluster 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": [ "WSFC", "FCI", "WindowsCluster", "HA" ], "CommandName": "Get-DbaWsfcSharedVolume", "Name": "Get-DbaWsfcSharedVolume", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaWsfcSharedVolume [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.Management.ManagementObject\nReturns one ClusterSharedVolume WMI object per shared volume found on the cluster, with three added NoteProperties providing cluster context.\nDefault display properties (ClusterSharedVolume WMI class properties plus):\r\n- ClusterName: Name of the Windows Server Failover Cluster\r\n- ClusterFqdn: Fully qualified domain name of the failover cluster\r\n- State: Current state of the cluster shared volume (Online, Offline, Failed, etc.), converted from numeric value\nAll properties from the underlying ClusterSharedVolume WMI class are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaWsfcSharedVolume -ComputerName cluster01\nGets shared volume (CSV) information from the failover cluster cluster01", "Description": "Retrieves detailed configuration and operational information about Cluster Shared Volumes (CSVs) from Windows Server Failover Clusters. CSVs provide the shared storage foundation for SQL Server Failover Cluster Instances (FCIs) and other clustered applications, making this function essential for monitoring storage health and troubleshooting cluster storage issues.\n\nDBAs use this when validating CSV health before SQL Server installations, investigating storage-related performance problems in clustered environments, or documenting shared storage configurations for disaster recovery planning. The function returns CSV properties along with cluster context including state information and fully qualified cluster names.\n\nAll Windows Server Failover Clustering (Wsfc) commands require local admin on each member node.", "Links": "https://dbatools.io/Get-DbaWsfcSharedVolume", "Synopsis": "Retrieves Cluster Shared Volume configuration and status from Windows Server Failover Clusters hosting SQL Server instances.", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the target Windows Server Failover Cluster to query for Cluster Shared Volume information. Accepts either individual cluster node names or the cluster name itself.\r\nUse this when you need to check CSV health and configuration on remote clusters hosting SQL Server FCIs. Defaults to the local computer if not specified.", "", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Allows you to login to the cluster 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": [ "ExtendedEvent", "XE", "XEvent" ], "CommandName": "Get-DbaXEObject", "Name": "Get-DbaXEObject", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaXEObject [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Type] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per Extended Events component available on the SQL Server instance. The number of objects returned depends on the SQL Server version and installed components.\nDefault display properties (excludes ComputerName, InstanceName, ObjectTypeRaw):\r\n- PackageName: Name of the Extended Events package (e.g., \u0027package0\u0027, \u0027sqlserver\u0027)\r\n- ObjectType: Type of XE object (Event, Action, Target, Map, Message, Type, PredicateComparator, PredicateSource)\r\n- TargetName: Name of the Extended Events object\r\n- Description: Description of what the XE object does\nAll properties available when using Select-Object *:\r\n- ComputerName: The computer name 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- PackageName: Name of the Extended Events package\r\n- ObjectType: Friendly-formatted object type\r\n- ObjectTypeRaw: Raw database value (\u0027type\u0027, \u0027event\u0027, \u0027target\u0027, \u0027pred_compare\u0027, \u0027pred_source\u0027, \u0027action\u0027, \u0027map\u0027, \u0027message\u0027)\r\n- TargetName: Name of the Extended Events object\r\n- Description: Description of the XE object\nUse the -Type parameter to filter results to specific component types without changing the output structure.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaXEObject -SqlInstance sql2016\nLists all the XE Objects on the sql2016 SQL Server.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaXEObject -SqlInstance sql2017 -Type Action, Event\nLists all the XE Objects of type Action and Event on the sql2017 SQL Server.", "Description": "This function queries sys.dm_xe_packages and sys.dm_xe_objects to discover what Extended Events components are available on your SQL Server instances. Use this when planning Extended Events sessions to see what events you can capture, what actions you can attach, and what targets you can write to. Essential for DBAs setting up performance monitoring, security auditing, or troubleshooting sessions since XE object availability varies by SQL Server version and edition.", "Links": "https://dbatools.io/Get-DbaXEObject", "Synopsis": "Retrieves Extended Events objects available for monitoring and troubleshooting on 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 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", "", "" ], [ "Type", "Filters the Extended Events objects by specific component types to help you find the XE building blocks you need.\r\nUse this when planning XE sessions to focus on specific components rather than viewing all available objects.\r\nEvents capture SQL Server activities, Actions attach additional data to events, Targets define where to store captured data, and Predicates filter which events to capture.", "", false, "false", "", "Type,Event,Target,Action,Map,Message,PredicateComparator,PredicateSource" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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": "Get-DbaXESession", "Name": "Get-DbaXESession", "Author": "Klaas Vandenberghe (@PowerDBAKlaas)", "Syntax": "Get-DbaXESession [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Session] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.XEvent.Session\nReturns one Session object per Extended Events session 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- Name: The name of the Extended Events session\r\n- Status: Current session status - either \"Running\" or \"Stopped\"\r\n- StartTime: DateTime when the session was started (null if stopped)\r\n- AutoStart: Boolean indicating if the session starts automatically when SQL Server starts\r\n- State: SMO object state (Existing, Creating, Pending, etc.)\r\n- Targets: Collection of target objects configured for this session\r\n- TargetFile: Array of resolved file paths for all event_file targets (includes UNC paths for network access)\r\n- Events: Collection of Extended Events configured in this session\r\n- MaxMemory: Maximum memory allocation for the session in KB\r\n- MaxEventSize: Maximum event size the session will capture in KB\nAdditional properties added as NoteProperties:\r\n- Session: The session name (alias for Name property)\r\n- RemoteTargetFile: Array of UNC paths for all target files (for remote file access)\r\n- Parent: Reference to the parent Microsoft.SqlServer.Management.Smo.Server object\r\n- Store: Reference to the Microsoft.SqlServer.Management.XEvent.XEStore object\nAdditional properties available from SMO Session object (via Select-Object *):\r\n- ID: Unique identifier for the session\r\n- EventRetentionMode: Event retention behavior setting\r\n- MaxDispatchLatency: Maximum dispatch latency in seconds\r\n- MemoryPartitionMode: Memory partitioning strategy\r\n- TrackCausality: Boolean indicating if causality tracking is enabled\r\n- IdentityKey: Identity key of the session object", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaXESession -SqlInstance ServerA\\sql987\nReturns a custom object with ComputerName, SQLInstance, Session, StartTime, Status and other properties.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaXESession -SqlInstance ServerA\\sql987 | Format-Table ComputerName, SqlInstance, Session, Status -AutoSize\nReturns a formatted table displaying ComputerName, SqlInstance, Session, and Status.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e\u0027ServerA\\sql987\u0027,\u0027ServerB\u0027 | Get-DbaXESession\nReturns a custom object with ComputerName, SqlInstance, Session, StartTime, Status and other properties, from multiple SQL instances.", "Description": "This function connects to one or more SQL Server instances and returns comprehensive information about Extended Events sessions, including their current status, configuration details, target files, and memory settings. Extended Events sessions are SQL Server\u0027s modern event-handling system used for performance monitoring, troubleshooting, and auditing. This command helps DBAs inventory existing sessions, verify their operational status, and locate output files across multiple SQL Server instances without manually connecting to each server. The function automatically resolves target file paths and provides both local and UNC path information for easier file access from remote management stations.", "Links": "https://dbatools.io/Get-DbaXESession", "Synopsis": "Retrieves Extended Events sessions with detailed 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 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", "", "" ], [ "Session", "Filters results to specific Extended Events sessions by name. Accepts multiple session names as an array.\r\nUse this when you need to check status or configuration of particular sessions rather than viewing all XE sessions on the instance.", "Sessions", 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": "Get-DbaXESessionTarget", "Name": "Get-DbaXESessionTarget", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaXESessionTarget [-SqlCredential \u003cPSCredential\u003e] [-Session \u003cString[]\u003e] [-Target \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]\nGet-DbaXESessionTarget -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Session \u003cString[]\u003e] [-Target \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]\nGet-DbaXESessionTarget [-SqlCredential \u003cPSCredential\u003e] [-Session \u003cString[]\u003e] [-Target \u003cString[]\u003e] -InputObject \u003cSession[]\u003e [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.XEvent.Target\nReturns one Target object per Extended Events session target found on the specified SQL Server instance(s). One target can be any kind of data collector configured for a session (event files, ring \r\nbuffers, event counters, etc.).\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- Session: The name of the Extended Events session containing this target\r\n- SessionStatus: Current session status - either \"Running\" or \"Stopped\"\r\n- Name: The target type/name (e.g., \u0027package0.event_file\u0027, \u0027package0.ring_buffer\u0027)\r\n- ID: Unique identifier for this target within the session\r\n- Field: Collection of target field configuration parameters\r\n- PackageName: The Extended Events package name that provides this target type (usually \u0027package0\u0027)\r\n- File: Array of resolved file paths for file-based targets (includes UNC paths for network access)\r\n- Description: Description of the target type and its purpose\r\n- ScriptName: The target name formatted for scripting purposes\nAdditional properties added as NoteProperties:\r\n- TargetFile: Array of resolved file paths for this target (local paths)\r\n- RemoteTargetFile: Array of UNC paths for this target (for remote file access)\nAdditional properties available from SMO Target object (via Select-Object *):\r\n- TargetFields: Collection containing detailed configuration parameters for the target\r\n- State: SMO object state (Existing, Creating, Pending, etc.)\r\n- Urn: Unified Resource Name for the target object\r\n- IdentityKey: Identity key of the target object\r\n- KeyChain: Identity path of the object\r\n- ModuleID: Module identifier for the target\r\n- Parent: Reference to parent Session object\r\n- Properties: Collection of property objects for this target", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaXESessionTarget -SqlInstance ServerA\\sql987 -Session system_health\nShows targets for the system_health session on ServerA\\sql987.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaXESession -SqlInstance sql2016 -Session system_health | Get-DbaXESessionTarget\nReturns the targets for the system_health session on sql2016.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaXESession -SqlInstance sql2016 -Session system_health | Get-DbaXESessionTarget -Target package0.event_file\nReturn only the package0.event_file target for the system_health session on sql2016.", "Description": "Returns detailed information about Extended Events session targets including their properties, file paths, and current status. This function helps DBAs examine where Extended Events data is being captured, whether sessions are running or stopped, and provides both local and UNC file paths for easy access to target files. Use this when you need to locate XE log files, verify target configurations, or troubleshoot Extended Events sessions that aren\u0027t capturing data as expected.", "Links": "https://dbatools.io/Get-DbaXESessionTarget", "Synopsis": "Retrieves Extended Events session targets with their configurations and file locations.", "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.", "", 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", "", "" ], [ "Session", "Filters results to specific Extended Events sessions by name. Supports wildcards and multiple session names.\r\nUse this when you only need target information from particular XE sessions instead of all sessions on the instance.", "", false, "false", "", "" ], [ "Target", "Filters results to specific target types such as \u0027event_file\u0027, \u0027ring_buffer\u0027, or \u0027event_counter\u0027. Supports multiple target names.\r\nUse this when you need information about particular target types, like finding all file-based targets or checking ring buffer configurations.", "", false, "false", "", "" ], [ "InputObject", "Accepts Extended Events session objects from Get-DbaXESession through the pipeline. Allows chaining commands for more complex filtering.\r\nUse this when you\u0027ve already retrieved specific XE sessions and want to examine their targets without re-querying the server.", "", 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": [ "ExtendedEvent", "XE", "XEvent" ], "CommandName": "Get-DbaXESessionTargetFile", "Name": "Get-DbaXESessionTargetFile", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaXESessionTargetFile [-SqlCredential \u003cPSCredential\u003e] [-Session \u003cString[]\u003e] [-Target \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]\nGet-DbaXESessionTargetFile -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Session \u003cString[]\u003e] [-Target \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]\nGet-DbaXESessionTargetFile [-SqlCredential \u003cPSCredential\u003e] [-Session \u003cString[]\u003e] [-Target \u003cString[]\u003e] -InputObject \u003cObject[]\u003e [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.IO.FileInfo\nReturns one FileInfo object per Extended Events target file found on the file system. These are the physical .xel and .xem files generated by Extended Events sessions with file-based targets.\nProperties:\r\n- Name: The file name with extension (e.g., system_health_0_130000000000000000.xel)\r\n- FullName: The complete file path including directory\r\n- DirectoryName: The directory path containing the file\r\n- Length: File size in bytes\r\n- LastWriteTime: DateTime when the file was last modified\r\n- CreationTime: DateTime when the file was created\r\n- Attributes: File attributes (e.g., Archive, Compressed)\r\n- Directory: DirectoryInfo object for the parent directory\r\n- Extension: The file extension (.xel or .xem)\nAll properties from the standard PowerShell FileInfo object are available and can be accessed with Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaXESessionTargetFile -SqlInstance sql2017 -Session \u0027Long Running Queries\u0027\nShows Target Files for the \u0027Long Running Queries\u0027 session on sql2017.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaXESession -SqlInstance sql2016 -Session \u0027Long Running Queries\u0027 | Get-DbaXESessionTarget | Get-DbaXESessionTargetFile\nReturns the Target Files for the system_health session on sql2016.", "Description": "Returns file system objects for Extended Events session target files, allowing you to examine the actual XE log files created by file-based targets. This function locates and lists the physical .xel files generated by Extended Events sessions, making it easy to access them for analysis with tools like SQL Server Management Studio or third-party XE file readers. Handles both local and remote SQL Server instances, automatically resolving UNC paths for remote servers so you can access XE files regardless of where the SQL Server is located.", "Links": "https://dbatools.io/Get-DbaXESessionTargetFile", "Synopsis": "Retrieves physical Extended Events target files from the file system for analysis and troubleshooting.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server", "", 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", "", "" ], [ "Session", "Specifies the Extended Events session name to retrieve target files from. Filters results to only include files generated by the specified session.\r\nUse this when you want to focus on files from a specific XE session like \u0027system_health\u0027 or custom monitoring sessions rather than all sessions on the instance.", "", false, "false", "", "" ], [ "Target", "Specifies the Extended Events target name to retrieve files from within the specified session. Filters results to only include files from the specified target.\r\nUse this when a session has multiple targets and you only need files from specific targets like \u0027event_file\u0027 or custom target configurations.", "", false, "false", "", "" ], [ "InputObject", "Accepts Extended Events target objects piped from Get-DbaXESessionTarget for processing their associated target files.\r\nUse this when you want to chain commands to first get specific targets and then retrieve their corresponding physical files on the file system.", "", 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": [ "ExtendedEvent", "XE", "XEvent" ], "CommandName": "Get-DbaXESessionTemplate", "Name": "Get-DbaXESessionTemplate", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaXESessionTemplate [[-Path] \u003cString[]\u003e] [[-Pattern] \u003cString\u003e] [[-Template] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per Extended Event session template found in the specified template directories. Each template is represented as a custom object with metadata extracted from the XML template file \r\nand supplementary information from the metadata catalog.\nDefault display properties (via Select-DefaultView):\r\n- Name: The session name from the template (e.g., \u0027system_health\u0027, \u0027Deadlock_Tracking\u0027)\r\n- Category: The template category for organizational grouping (e.g., \u0027Performance\u0027, \u0027Security\u0027, \u0027Monitoring\u0027)\r\n- Source: The source or author of the template (e.g., \u0027Microsoft\u0027, \u0027Jes Borland\u0027, \u0027Christian Grafe\u0027)\r\n- Compatibility: Comma-separated list of SQL Server versions this template is compatible with (e.g., \u00272008, 2012, 2014, 2016, 2017, 2019\u0027)\r\n- Description: Text description of what the template monitors or its intended use case\nAdditional properties available (use Select-Object * to view):\r\n- TemplateName: The template name element from XML\r\n- Path: FileInfo object representing the template file path\r\n- File: The template file name with extension\nUse Select-Object * to access all properties including the file path and additional metadata embedded in the template objects.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaXESessionTemplate\nReturns information about all the templates in the local dbatools repository.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaXESessionTemplate | Out-GridView -PassThru | Import-DbaXESessionTemplate -SqlInstance sql2017 | Start-DbaXESession\nAllows you to select a Session template, then import it to the specified instance and start the session.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaXESessionTemplate -Path \"$home\\Documents\\SQL Server Management Studio\\Templates\\XEventTemplates\"\nReturns information about all the templates in your local XEventTemplates repository.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaXESessionTemplate -Pattern duration\nReturns information about all the templates that match the word \"duration\" in the title, category or body.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaXESessionTemplate | Select-Object *\nReturns more information about the template, including the full path/filename.", "Description": "Retrieves metadata from Extended Event session templates stored in XML format, showing you what pre-built Extended Event sessions are available before importing them to your SQL Server instances. This saves you from manually browsing template files or guessing what monitoring solutions exist for specific scenarios.\n\nUse this command when you need to set up Extended Event monitoring but want to start with proven templates rather than building sessions from scratch. It\u0027s particularly helpful for discovering templates that monitor specific areas like performance, deadlocks, or security events.\n\nThe function parses templates and returns key information including the template name, category, source, SQL Server compatibility, and description. You can filter results by pattern matching or select specific templates by name.\n\nThe default repository contains templates from:\nMicrosoft\u0027s Templates that come with SSMS\nJes Borland\u0027s \"Everyday Extended Events\" presentation and GitHub repository (https://github.com/grrlgeek/extended-events)\nChristian Grafe (@ChrGraefe) XE Repo: https://github.com/chrgraefe/sqlscripts/blob/master/XE-Events/\nErin Stellato\u0027s Blog: https://www.sqlskills.com/blogs/erin/\n\nSome profile templates converted using:\nsp_SQLskills_ConvertTraceToExtendedEvents.sql\nJonathan M. Kehayias, SQLskills.com\nhttp://sqlskills.com/blogs/jonathan", "Links": "https://dbatools.io/Get-DbaXESessionTemplate", "Synopsis": "Retrieves metadata from Extended Event session templates to help you discover and select pre-built monitoring solutions.", "Availability": "Windows, Linux, macOS", "Params": [ [ "Path", "Specifies the directory path containing Extended Event template XML files. Defaults to the built-in dbatools template repository.\r\nUse this when you want to browse custom or additional templates stored in your own directory instead of the default collection.", "", false, "false", "\"$script:PSModuleRoot\\bin\\XEtemplates\"", "" ], [ "Pattern", "Filters templates by searching for the specified text pattern across template names, categories, sources, and descriptions.\r\nUse this to quickly find templates related to specific monitoring scenarios like \"deadlock\", \"performance\", or \"security\" without browsing all available templates.", "", false, "false", "", "" ], [ "Template", "Specifies the exact name(s) of specific templates to retrieve, matching the template file names without the .xml extension.\r\nUse this when you know the specific template names you want to examine, such as \"Deadlock_Tracking\" or \"Query_Duration_Performance\".", "", 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": "Get-DbaXEStore", "Name": "Get-DbaXEStore", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Get-DbaXEStore [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.XEvent.XEStore\nReturns one XEStore object per SQL Server instance specified, providing access to Extended Events sessions, packages, and configuration management.\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 format)\r\n- ServerName: The name of the SQL Server instance from the XEStore object\r\n- Sessions: Collection of Extended Events sessions on the instance\r\n- Packages: Collection of XEvent packages available on the instance\r\n- RunningSessionCount: The number of currently active/running XEvent sessions\nAll properties from the base SMO XEStore object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaXEStore -SqlInstance ServerA\\sql987\nReturns an XEvent Store.", "Description": "Retrieves the Extended Events store object from SQL Server instances, which serves as the foundation for working with Extended Events sessions, packages, and configurations. The store object provides access to session management, event package information, and running session counts. This is typically the first step when building Extended Events monitoring solutions or auditing XEvent configurations across your environment.", "Links": "https://dbatools.io/Get-DbaXEStore", "Synopsis": "Retrieves the Extended Events store object for managing XEvent sessions and configurations", "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.", "", 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": "Grant-DbaAgPermission", "Name": "Grant-DbaAgPermission", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Grant-DbaAgPermission [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Login] \u003cString[]\u003e] [[-AvailabilityGroup] \u003cString[]\u003e] [-Type] \u003cString[]\u003e [[-Permission] \u003cString[]\u003e] [[-InputObject] \u003cLogin[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per permission grant operation when granting permissions on database mirroring endpoints or availability groups. When performing GrantAvailabilityGroupCreateDatabasePrivilege \r\noperations, no output is returned.\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- Name: The login name that was granted the permission\r\n- Permission: The permission type that was granted (Connect, Alter, Control, TakeOwnership, ViewDefinition)\r\n- Type: Always \"Grant\" indicating this is a permission grant operation\r\n- Status: Status of the grant operation (\"Success\" if completed without error)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGrant-DbaAgPermission -SqlInstance sql2017a -Type AvailabilityGroup -AvailabilityGroup SharePoint -Permission CreateAnyDatabase\nAdds CreateAnyDatabase permissions to the SharePoint availability group on sql2017a. Does not prompt for confirmation.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGrant-DbaAgPermission -SqlInstance sql2017a -Type AvailabilityGroup -AvailabilityGroup ag1, ag2 -Permission CreateAnyDatabase -Confirm\nAdds CreateAnyDatabase permissions to the ag1 and ag2 availability groups on sql2017a. Prompts for confirmation.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaLogin -SqlInstance sql2017a | Out-GridView -Passthru | Grant-DbaAgPermission -Type EndPoint\nGrants the selected logins Connect permissions on the DatabaseMirroring endpoint for sql2017a", "Description": "Grants permissions to SQL Server logins for availability groups (Alter, Control, TakeOwnership, ViewDefinition) and database mirroring endpoints (Connect, Alter, Control, and others). Essential for setting up high availability and disaster recovery scenarios where service accounts or users need access to manage or connect to availability group resources. Windows logins are automatically created if they don\u0027t exist on the target instance, simplifying multi-server availability group deployments.", "Links": "https://dbatools.io/Grant-DbaAgPermission", "Synopsis": "Grants specific permissions to logins for availability groups and database mirroring endpoints.", "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", "", "" ], [ "Login", "Specifies the SQL Server logins that will receive the permissions. Windows logins are automatically created if they don\u0027t exist on the target instance.\r\nUse this when you need to grant permissions to specific service accounts or users for availability group operations.", "", false, "false", "", "" ], [ "AvailabilityGroup", "Specifies which availability groups to grant permissions on. Required when using Type \u0027AvailabilityGroup\u0027.\r\nUse this to limit permission grants to specific AGs rather than all availability groups on the instance.", "", false, "false", "", "" ], [ "Type", "Specifies whether to grant permissions on database mirroring endpoints or availability groups. Use \u0027Endpoint\u0027 for database mirroring endpoint permissions or \u0027AvailabilityGroup\u0027 for AG-level \r\npermissions.\r\nEndpoint permissions are needed for replicas to communicate, while AvailabilityGroup permissions control AG management operations.", "", true, "false", "", "Endpoint,AvailabilityGroup" ], [ "Permission", "Specifies which permissions to grant. Defaults to \u0027Connect\u0027 for basic endpoint access.\r\nFor endpoints: Connect, Alter, Control, and others. For availability groups: Alter, Control, TakeOwnership, ViewDefinition only.\r\nUse \u0027CreateAnyDatabase\u0027 for AGs to allow automatic seeding of new databases to replicas.", "", false, "false", "Connect", "Alter,Connect,Control,CreateAnyDatabase,CreateSequence,Delete,Execute,Impersonate,Insert,Receive,References,Select,Send,TakeOwnership,Update,ViewChangeTracking,ViewDefinition" ], [ "InputObject", "Accepts login objects from Get-DbaLogin pipeline input. Use this when you\u0027ve already retrieved specific logins and want to grant them permissions.\r\nProvides an alternative to specifying individual login names with the -Login parameter.", "", 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", "", "" ] ] }, { "Name": "Import-Command", "Description": null, "Synopsis": "\r\nImport-Command [-Path \u003cstring\u003e] [\u003cCommonParameters\u003e]\r\n", "Outputs": "returnValue\r\n-----------\r\n@{type=}", "Alias": "", "CommandName": "Import-Command", "Availability": "Windows, Linux, macOS", "Links": null, "Examples": "", "Params": [ [ "Path", "", "", false, "true (ByValue)", null, "" ] ], "Syntax": "syntaxItem \r\n---------- \r\n{@{name=Import-Command; CommonParameters=True; WorkflowCommonParameters=False; parameter=System.Object[]}}" }, { "Tags": [ "Migration", "Backup", "Export" ], "CommandName": "Import-DbaBinaryFile", "Name": "Import-DbaBinaryFile", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Import-DbaBinaryFile [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString\u003e] [[-Table] \u003cString\u003e] [[-Schema] \u003cString\u003e] [[-Statement] \u003cString\u003e] [[-FileNameColumn] \u003cString\u003e] [[-BinaryColumn] \u003cString\u003e] [-NoFileNameColumn] [[-InputObject] \u003cTable[]\u003e] [[-FilePath] \u003cFileInfo[]\u003e] [[-Path] \u003cFileInfo[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per file imported. Each object contains status and context information about the import operation.\nProperties:\r\n- ComputerName: The computer name of the SQL Server instance where the file was imported\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 where the file was imported\r\n- Table: The name of the table where the binary file was stored\r\n- FilePath: The full file system path of the source file that was imported\r\n- Status: The import operation status (\"Success\" when file was successfully imported)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-ChildItem C:\\photos | Import-DbaBinaryFile -SqlInstance sqlcs -Database employees -Table photos\nImports all photos from C:\\photos into the photos table in the employees database on sqlcs. Automatically guesses the column names for the image and filename columns.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eImport-DbaBinaryFile -SqlInstance sqlcs -Database tempdb -Table BunchOFiles -FilePath C:\\azure\\adalsql.msi\nImports the file adalsql.msi into the BunchOFiles table in the tempdb database on sqlcs. Automatically guesses the column names for the image and filename columns.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eImport-DbaBinaryFile -SqlInstance sqlcs -Database tempdb -Table BunchOFiles -FilePath C:\\azure\\adalsql.msi -FileNameColumn fname -BinaryColumn data\nImports the file adalsql.msi into the BunchOFiles table in the tempdb database on sqlcs. Uses the fname and data columns for the filename and binary data.", "Description": "Reads binary files from disk and stores them in SQL Server tables with binary, varbinary, or image columns. This is useful for storing documents, images, executables, or any file type directly in the database for archival, content management, or application integration scenarios.\n\nThe command automatically detects the appropriate columns for storing file data - it looks for binary-type columns (binary, varbinary, image) for the file contents and columns containing \"name\" for the filename. You can also specify exact column names or provide a custom INSERT statement for more complex scenarios.\n\nFiles can be imported individually, from directories (with recursion), or piped in from Get-ChildItem. Each file is read as a byte array and inserted using parameterized queries to safely handle binary data of any size within SQL Server\u0027s limits.", "Links": "https://dbatools.io/Import-DbaBinaryFile", "Synopsis": "Loads binary files from the filesystem into SQL Server database tables", "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 the target database where the binary files will be imported. Required when not using InputObject.\r\nUse this to identify which database contains the table for storing your binary files.", "", false, "false", "", "" ], [ "Table", "Specifies the target table where binary files will be stored. Must contain at least one binary-type column (binary, varbinary, image).\r\nUse this when importing files into a specific table designed for file storage. Supports three-part naming (db.schema.table).\r\nIf the object has special characters please wrap them in square brackets [ ].\r\nUsing dbo.First.Table will try to find table named \u0027Table\u0027 on schema \u0027First\u0027 and database \u0027dbo\u0027.\r\nThe correct way to find table named \u0027First.Table\u0027 on schema \u0027dbo\u0027 is by passing dbo.[First.Table]\r\nAny actual usage of the ] must be escaped by duplicating the ] character.\r\nThe correct way to find a table Name] in schema Schema.Name is by passing [Schema.Name].[Name]]]", "", false, "false", "", "" ], [ "Schema", "Specifies the schema containing the target table. Defaults to the user\u0027s default schema if not specified.\r\nUse this when your table exists in a non-default schema or when you need to be explicit about schema ownership.", "", false, "false", "", "" ], [ "Statement", "Provides a custom INSERT statement for complex import scenarios. Must include @FileContents parameter for binary data.\r\nUse this when automatic column detection fails or when you need custom INSERT logic with joins, triggers, or computed columns.\r\nExample: INSERT INTO db.tbl ([FileNameColumn], [bBinaryColumn]) VALUES (@FileName, @FileContents)\r\nThe @FileContents parameter is required. Include @FileName parameter if storing filenames.", "", false, "false", "", "" ], [ "FileNameColumn", "Specifies which column will store the original filename. Auto-detects columns containing \u0027name\u0027 if not specified.\r\nUse this when your table has multiple name-related columns or when auto-detection fails to identify the correct column.", "", false, "false", "", "" ], [ "BinaryColumn", "Specifies which column will store the binary file data. Auto-detects binary, varbinary, or image columns if not specified.\r\nUse this when your table has multiple binary columns or when auto-detection fails to identify the correct storage column.", "", false, "false", "", "" ], [ "NoFileNameColumn", "Indicates that the target table does not have a column for storing filenames. Only the binary data will be imported.\r\nUse this when your table design only stores file content without filename metadata for blob storage scenarios.", "", false, "false", "False", "" ], [ "InputObject", "Accepts table objects from Get-DbaDbTable for pipeline-based imports. Alternative to specifying Database and Table parameters.\r\nUse this when working with multiple tables or when integrating with other dbatools commands that return table objects.", "", false, "true (ByValue)", "", "" ], [ "FilePath", "Specifies one or more individual files to import into the database table. Accepts pipeline input from Get-ChildItem.\r\nUse this when importing specific files rather than entire directories. Cannot be used with Path parameter.", "FullName", false, "true (ByPropertyName)", "", "" ], [ "Path", "Specifies a directory containing files to import. Recursively processes all files within the directory and subdirectories.\r\nUse this when bulk importing multiple files from a folder structure. Cannot be used with FilePath 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", "" ], [ "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": [ "Import", "Data", "Utility" ], "CommandName": "Import-DbaCsv", "Name": "Import-DbaCsv", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Import-DbaCsv [[-Path] \u003cObject[]\u003e] [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Database] \u003cString\u003e [[-Table] \u003cString\u003e] [[-Schema] \u003cString\u003e] [-Truncate] [[-Delimiter] \u003cString\u003e] [-SingleColumn] [[-BatchSize] \u003cInt32\u003e] [[-NotifyAfter] \u003cInt32\u003e] [-TableLock] [-CheckConstraints] [-FireTriggers] [-KeepIdentity] [-KeepNulls] [[-Column] \u003cString[]\u003e] [[-ColumnMap] \u003cHashtable\u003e] [-KeepOrdinalOrder] [-AutoCreateTable] [-NoProgress] [-NoHeaderRow] [-UseFileNameForSchema] [[-Quote] \u003cChar\u003e] [[-Escape] \u003cChar\u003e] [[-Comment] \u003cChar\u003e] [[-TrimmingOption] \u003cString\u003e] [[-BufferSize] \r\n\u003cInt32\u003e] [[-ParseErrorAction] \u003cString\u003e] [[-Encoding] \u003cString\u003e] [[-NullValue] \u003cString\u003e] [[-MaxQuotedFieldLength] \u003cInt32\u003e] [-SkipEmptyLine] [-SupportsMultiline] [-UseColumnDefault] [-NoTransaction] [[-MaxDecompressedSize] \u003cInt64\u003e] [[-SkipRows] \u003cInt32\u003e] [[-QuoteMode] \u003cString\u003e] [[-DuplicateHeaderBehavior] \u003cString\u003e] [[-MismatchedFieldAction] \u003cString\u003e] [-DistinguishEmptyFromNull] [-NormalizeQuotes] [-CollectParseErrors] [[-MaxParseErrors] \u003cInt32\u003e] [[-StaticColumns] \u003cHashtable\u003e] [[-DateTimeFormats] \u003cString[]\u003e] [[-Culture] \u003cString\u003e] [[-SampleRows] \u003cInt32\u003e] [-DetectColumnTypes] [-Parallel] \r\n[[-ThrottleLimit] \u003cInt32\u003e] [[-ParallelBatchSize] \u003cInt32\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per CSV file imported. Each object contains comprehensive metrics about the import operation.\nProperties:\r\n- ComputerName: The computer name of the SQL Server instance where the CSV was imported\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance format)\r\n- Database: The database name where data was imported\r\n- Table: The table name where CSV data was loaded\r\n- Schema: The schema name containing the target table\r\n- RowsCopied: The total number of rows successfully copied from the CSV file (int64)\r\n- Elapsed: The elapsed time for the import operation in elapsed time format (automatically formatted as HH:mm:ss.fff)\r\n- RowsPerSecond: The average import rate calculated as total rows divided by elapsed time in seconds (decimal)\r\n- Path: The full file system path of the imported CSV file\nAll size and rate metrics are calculated based on the actual import duration, which for type detection operations does not include\r\nthe time spent scanning the file for column type inference.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eImport-DbaCsv -Path C:\\temp\\housing.csv -SqlInstance sql001 -Database markets\nImports the entire comma-delimited housing.csv to the SQL \"markets\" database on a SQL Server named sql001, using the first row as column names.\nSince a table name was not specified, the table name is automatically determined from filename as \"housing\".\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eImport-DbaCsv -Path .\\housing.csv -SqlInstance sql001 -Database markets -Table housing -Delimiter \"`t\" -NoHeaderRow\nImports the entire tab-delimited housing.csv, including the first row which is not used for colum names, to the SQL markets database, into the housing table, on a SQL Server named sql001.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eImport-DbaCsv -Path C:\\temp\\huge.txt -SqlInstance sqlcluster -Database locations -Table latitudes -Delimiter \"|\"\nImports the entire pipe-delimited huge.txt to the locations database, into the latitudes table on a SQL Server named sqlcluster.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eImport-DbaCsv -Path c:\\temp\\SingleColumn.csv -SqlInstance sql001 -Database markets -Table TempTable -SingleColumn\nImports the single column CSV into TempTable\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-ChildItem -Path \\\\FileServer\\csvs | Import-DbaCsv -SqlInstance sql001, sql002 -Database tempdb -AutoCreateTable\nImports every CSV in the \\\\FileServer\\csvs path into both sql001 and sql002\u0027s tempdb database. Each CSV will be imported into an automatically determined table name.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-ChildItem -Path \\\\FileServer\\csvs | Import-DbaCsv -SqlInstance sql001, sql002 -Database tempdb -AutoCreateTable -WhatIf\nShows what would happen if the command were to be executed\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eImport-DbaCsv -Path c:\\temp\\dataset.csv -SqlInstance sql2016 -Database tempdb -Column Name, Address, Mobile\nImport only Name, Address and Mobile even if other columns exist. All other columns are ignored and therefore null or default values.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eImport-DbaCsv -Path C:\\temp\\schema.data.csv -SqlInstance sql2016 -database tempdb -UseFileNameForSchema\nWill import the contents of C:\\temp\\schema.data.csv to table \u0027data\u0027 in schema \u0027schema\u0027.\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003eImport-DbaCsv -Path C:\\temp\\schema.data.csv -SqlInstance sql2016 -database tempdb -UseFileNameForSchema -Table testtable\nWill import the contents of C:\\temp\\schema.data.csv to table \u0027testtable\u0027 in schema \u0027schema\u0027.\n-------------------------- EXAMPLE 10 --------------------------\nPS C:\\\u003e$columns = @{\n\u003e\u003e Text = \u0027FirstName\u0027\r\n\u003e\u003e Number = \u0027PhoneNumber\u0027\r\n\u003e\u003e }\r\nPS C:\\\u003e Import-DbaCsv -Path c:\\temp\\supersmall.csv -SqlInstance sql2016 -Database tempdb -ColumnMap $columns\nThe CSV field \u0027Text\u0027 is inserted into SQL column \u0027FirstName\u0027 and CSV field Number is inserted into the SQL Column \u0027PhoneNumber\u0027. All other columns are ignored and therefore null or default values.\n-------------------------- EXAMPLE 11 --------------------------\nPS C:\\\u003e$columns = @{\n\u003e\u003e 0 = \u0027FirstName\u0027\r\n\u003e\u003e 1 = \u0027PhoneNumber\u0027\r\n\u003e\u003e }\r\nPS C:\\\u003e Import-DbaCsv -Path c:\\temp\\supersmall.csv -SqlInstance sql2016 -Database tempdb -NoHeaderRow -ColumnMap $columns\nIf the CSV has no headers, passing a ColumnMap works when you have as the key the ordinal of the column (0-based).\r\nIn this example the first CSV field is inserted into SQL column \u0027FirstName\u0027 and the second CSV field is inserted into the SQL Column \u0027PhoneNumber\u0027.\n-------------------------- EXAMPLE 12 --------------------------\nPS C:\\\u003eImport-DbaCsv -Path C:\\temp\\data.csv -SqlInstance sql001 -Database tempdb -Table MyTable -Delimiter \"::\" -AutoCreateTable\nImports a CSV file that uses a multi-character delimiter (::). The new CSV reader supports delimiters of any length,\r\nnot just single characters.\n-------------------------- EXAMPLE 13 --------------------------\nPS C:\\\u003eImport-DbaCsv -Path C:\\temp\\data.csv.gz -SqlInstance sql001 -Database tempdb -Table MyTable -AutoCreateTable\nImports a gzip-compressed CSV file. Compression is automatically detected from the .gz extension and the file\r\nis decompressed on-the-fly during import without extracting to disk.\n-------------------------- EXAMPLE 14 --------------------------\nPS C:\\\u003eImport-DbaCsv -Path C:\\temp\\export.csv -SqlInstance sql001 -Database tempdb -Table MyTable -SkipRows 3 -AutoCreateTable\nSkips the first 3 rows of the file before reading headers and data. Useful for files that have metadata rows,\r\ncomments, or report headers before the actual CSV content begins.\n-------------------------- EXAMPLE 15 --------------------------\nPS C:\\\u003eImport-DbaCsv -Path C:\\temp\\data.csv -SqlInstance sql001 -Database tempdb -Table MyTable -DuplicateHeaderBehavior Rename -AutoCreateTable\nHandles CSV files with duplicate column headers by automatically renaming them (e.g., Name, Name_2, Name_3).\r\nWithout this, duplicate headers would cause an error.\n-------------------------- EXAMPLE 16 --------------------------\nPS C:\\\u003eImport-DbaCsv -Path C:\\temp\\messy.csv -SqlInstance sql001 -Database tempdb -Table MyTable -MismatchedFieldAction PadWithNulls -AutoCreateTable\nImports a CSV where some rows have fewer fields than the header row. Missing fields are padded with NULL values\r\ninstead of throwing an error. Useful for importing data from systems that omit trailing empty fields.\n-------------------------- EXAMPLE 17 --------------------------\nPS C:\\\u003eImport-DbaCsv -Path C:\\temp\\data.csv -SqlInstance sql001 -Database tempdb -Table MyTable -QuoteMode Lenient -AutoCreateTable\nUses lenient quote parsing for CSV files with improperly escaped quotes. This is useful when importing data\r\nfrom systems that don\u0027t follow RFC 4180 strictly, such as files with embedded quotes that aren\u0027t doubled.\n-------------------------- EXAMPLE 18 --------------------------\nPS C:\\\u003e# Import CSV with proper type conversion to a pre-created table\nPS C:\\\u003e $query = \"CREATE TABLE TypedData (id INT, amount DECIMAL(10,2), active BIT, created DATETIME)\"\r\nPS C:\\\u003e Invoke-DbaQuery -SqlInstance sql001 -Database tempdb -Query $query\r\nPS C:\\\u003e Import-DbaCsv -Path C:\\temp\\typed.csv -SqlInstance sql001 -Database tempdb -Table TypedData\nImports CSV data into a table with specific column types. The CSV reader automatically converts string values\r\nto the appropriate SQL Server types (INT, DECIMAL, BIT, DATETIME, etc.) during import.\n-------------------------- EXAMPLE 19 --------------------------\nPS C:\\\u003eImport-DbaCsv -Path C:\\temp\\large.csv -SqlInstance sql001 -Database tempdb -Table BigData -AutoCreateTable -Parallel\nImports a large CSV file using parallel processing for improved performance. The -Parallel switch enables\r\nconcurrent line reading, parsing, and type conversion, which can provide 2-4x speedup on multi-core systems\r\nfor files with 100K+ rows.\n-------------------------- EXAMPLE 20 --------------------------\nPS C:\\\u003eImport-DbaCsv -Path C:\\temp\\huge.csv -SqlInstance sql001 -Database tempdb -Table HugeData -AutoCreateTable -Parallel -ThrottleLimit 4\nImports a large CSV with parallel processing limited to 4 worker threads. Use -ThrottleLimit to control\r\nresource usage on shared systems or when you want to limit CPU consumption during the import.\n-------------------------- EXAMPLE 21 --------------------------\nPS C:\\\u003eImport-DbaCsv -Path C:\\temp\\massive.csv -SqlInstance sql001 -Database tempdb -Table MassiveData -AutoCreateTable -Parallel -ParallelBatchSize 500\nImports a very large CSV with parallel processing using larger batch sizes. Increase -ParallelBatchSize\r\nfor very large files (millions of rows) to reduce synchronization overhead. The default is 100.\n-------------------------- EXAMPLE 22 --------------------------\nPS C:\\\u003eImport-DbaCsv -Path C:\\temp\\refresh.csv -SqlInstance sql001 -Database tempdb -Table LookupData -Truncate\nPerforms a full data refresh by truncating the existing table before importing. The truncate and import\r\noperations are wrapped in a transaction, so if the import fails, the original data is preserved.\n-------------------------- EXAMPLE 23 --------------------------\nPS C:\\\u003e$static = @{ SourceFile = \"sales_2024.csv\"; ImportDate = (Get-Date); Region = \"EMEA\" }\nPS C:\\\u003e Import-DbaCsv -Path C:\\temp\\sales.csv -SqlInstance sql001 -Database sales -Table SalesData -StaticColumns $static -AutoCreateTable\nImports CSV data and adds three static columns (SourceFile, ImportDate, Region) to every row.\r\nThis is useful for tracking data lineage and tagging imported records with metadata.\n-------------------------- EXAMPLE 24 --------------------------\nPS C:\\\u003eImport-DbaCsv -Path C:\\temp\\oracle_export.csv -SqlInstance sql001 -Database tempdb -Table OracleData -DateTimeFormats @(\"dd-MMM-yyyy\", \"dd-MMM-yyyy HH:mm:ss\") -AutoCreateTable\nImports a CSV with Oracle-style date formats (e.g., \"15-Jan-2024\"). The -DateTimeFormats parameter\r\nspecifies custom format strings to parse non-standard date columns correctly.\n-------------------------- EXAMPLE 25 --------------------------\nPS C:\\\u003eImport-DbaCsv -Path C:\\temp\\german_data.csv -SqlInstance sql001 -Database tempdb -Table GermanData -Culture \"de-DE\" -AutoCreateTable\nImports a CSV with German number formatting where comma is the decimal separator (e.g., \"1.234,56\").\r\nThe -Culture parameter ensures numbers are parsed correctly according to the specified locale.\n-------------------------- EXAMPLE 26 --------------------------\nPS C:\\\u003eImport-DbaCsv -Path C:\\temp\\sales.csv -SqlInstance sql001 -Database sales -Table SalesData -AutoCreateTable -SampleRows 10000\nImports sales.csv and creates the table with optimal column types inferred from the first 10,000 rows.\r\nInstead of nvarchar(MAX) for all columns, the table will have appropriate types like int, decimal(10,2),\r\ndatetime2, bit, or varchar(50) based on the actual data patterns detected.\nThis is fast but has a small risk if data patterns change after the sampled rows.\n-------------------------- EXAMPLE 27 --------------------------\nPS C:\\\u003eImport-DbaCsv -Path C:\\temp\\large_dataset.csv -SqlInstance sql001 -Database warehouse -Table FactSales -AutoCreateTable -DetectColumnTypes\nImports large_dataset.csv with guaranteed optimal column types by scanning the entire file first.\r\nA separate progress bar shows \"Analyzing column types...\" during the detection phase.\r\nThe final output (Elapsed, RowsPerSecond) reflects only the import time, not the detection overhead.\nThis is slower (reads file twice) but guarantees no import failures due to type mismatches.\n-------------------------- EXAMPLE 28 --------------------------\nPS C:\\\u003eImport-DbaCsv -Path C:\\temp\\products.csv -SqlInstance sql001 -Database inventory -Table Products -AutoCreateTable -SampleRows 5000 -DateTimeFormats @(\"dd-MMM-yyyy\", \"yyyy/MM/dd\")\nImports products.csv with type detection from 5,000 rows, using custom date formats for parsing.\r\nColumns containing dates in formats like \"15-Jan-2024\" or \"2024/01/15\" will be detected as datetime2.\n-------------------------- EXAMPLE 29 --------------------------\nPS C:\\\u003eImport-DbaCsv -Path C:\\temp\\quickload.csv -SqlInstance sql001 -Database tempdb -Table QuickData -AutoCreateTable\nImports quickload.csv with AutoCreateTable. After import completes, column sizes are automatically\r\noptimized by querying actual max lengths and altering columns from nvarchar(MAX) to padded sizes\r\nlike nvarchar(16), nvarchar(32), nvarchar(64), etc. The nvarchar type is preserved to avoid any\r\nrisk of data loss from Unicode conversion. For ASCII-\u003evarchar conversion, use -SampleRows or -DetectColumnTypes.", "Description": "Import-DbaCsv uses .NET\u0027s SqlBulkCopy class to efficiently load CSV data into SQL Server tables, handling files of any size from small datasets to multi-gigabyte imports. The function wraps the entire operation in a transaction, so any failure or interruption rolls back all changes automatically.\n\nWhen the target table doesn\u0027t exist, you can use -AutoCreateTable to create it on the fly with basic nvarchar(max) columns. For production use, create your table first with proper data types and constraints. The function intelligently maps CSV columns to table columns by name, with fallback to ordinal position when needed.\n\nSupports various CSV formats including custom delimiters, quoted fields, gzip compression (.csv.gz files), and multi-line values within quoted fields. Column mapping lets you import specific columns or rename them during import, while schema detection can automatically place data in the correct schema based on filename patterns.\n\nPerfect for ETL processes, data migrations, or loading reference data where you need reliable, fast imports with proper error handling and transaction safety.", "Links": "https://dbatools.io/Import-DbaCsv", "Synopsis": "Imports CSV files into SQL Server tables using high-performance bulk copy operations.", "Availability": "Windows, Linux, macOS", "Params": [ [ "Path", "Specifies the file path to CSV files for import. Supports single files, multiple files, or pipeline input from Get-ChildItem.\r\nAccepts .csv files and compressed .csv.gz files for large datasets with automatic decompression.", "Csv,FullPath", false, "true (ByValue)", "", "" ], [ "SqlInstance", "The SQL Server Instance to import data into.", "", 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 target database for the CSV import. The database must exist on the SQL Server instance.\r\nUse this to direct your data load to the appropriate database, whether it\u0027s a staging, ETL, or production database.", "", true, "false", "", "" ], [ "Table", "Specifies the destination table name. If omitted, uses the CSV filename as the table name.\r\nThe table will be created automatically with -AutoCreateTable using nvarchar(max) columns, but for production use, create the table first with proper data types and constraints.", "", false, "false", "", "" ], [ "Schema", "Specifies the target schema for the table. Defaults to \u0027dbo\u0027 if not specified.\r\nIf the schema doesn\u0027t exist, it will be created automatically when using -AutoCreateTable. This parameter takes precedence over -UseFileNameForSchema.", "", false, "false", "", "" ], [ "Truncate", "Removes all existing data from the destination table before importing. The truncate operation is part of the transaction.\r\nUse this for full data refreshes where you want to replace all existing data with the CSV contents.", "", false, "false", "False", "" ], [ "Delimiter", "Sets the field separator used in the CSV file. Defaults to comma if not specified.\r\nCommon values include comma (,), tab (`t), pipe (|), semicolon (;), or space for different export formats from various systems.\r\nMulti-character delimiters are fully supported (e.g., \"::\", \"||\", \"\\t\\t\").", "DelimiterChar", false, "false", ",", "" ], [ "SingleColumn", "Indicates the CSV contains only one column of data without delimiters. Use this for simple lists or single-value imports.\r\nPrevents the function from failing when no delimiter is found in the file content.", "", false, "false", "False", "" ], [ "BatchSize", "Controls how many rows are sent to SQL Server in each batch during the bulk copy operation. Defaults to 50,000.\r\nLarger batches are generally more efficient but use more memory, while smaller batches provide better granular control and error isolation.", "", false, "false", "50000", "" ], [ "NotifyAfter", "Sets how often progress notifications are displayed during the import, measured in rows. Defaults to 50,000.\r\nLower values provide more frequent updates but may slow the import slightly, while higher values reduce overhead for very large files.", "", false, "false", "50000", "" ], [ "TableLock", "Acquires an exclusive table lock for the duration of the import instead of using row-level locks.\r\nImproves performance for large imports by reducing lock overhead, but blocks other operations on the table during the import.", "", false, "false", "False", "" ], [ "CheckConstraints", "Enforces check constraints, foreign keys, and other table constraints during the import. By default, constraints are not checked for performance.\r\nEnable this when data integrity validation is critical, but expect slower import performance.", "", false, "false", "False", "" ], [ "FireTriggers", "Executes INSERT triggers on the destination table during the bulk copy operation. By default, triggers are not fired for performance.\r\nUse this when your triggers perform essential business logic like auditing, logging, or cascading updates that must run during import.", "", false, "false", "False", "" ], [ "KeepIdentity", "Preserves identity column values from the CSV instead of generating new ones. By default, the destination assigns new identity values.\r\nUse this when migrating data and you need to maintain existing primary key values or referential integrity.", "", false, "false", "False", "" ], [ "KeepNulls", "Preserves NULL values from the CSV instead of replacing them with column default values.\r\nUse this when your data intentionally contains NULLs that should be maintained, rather than having them replaced by table defaults.", "", false, "false", "False", "" ], [ "Column", "Imports only the specified columns from the CSV file, ignoring all others. Column names must match exactly.\r\nUse this to selectively load data when you only need certain fields, reducing import time and storage requirements.", "", false, "false", "", "" ], [ "ColumnMap", "Maps CSV columns to different table column names using a hashtable. Keys are CSV column names, values are table column names.\r\nUse this when your CSV headers don\u0027t match your table structure or when importing from systems with different naming conventions.", "", false, "false", "", "" ], [ "KeepOrdinalOrder", "Maps columns by position rather than by name matching. The first CSV column goes to the first table column, second to second, etc.\r\nUse this when column names don\u0027t match but the order is correct, or when dealing with files that have inconsistent header naming.", "", false, "false", "False", "" ], [ "AutoCreateTable", "Creates the destination table automatically if it doesn\u0027t exist, using nvarchar(max) for all columns.\r\nAfter import, column sizes are automatically optimized based on actual data lengths (nvarchar(MAX) -\u003e nvarchar(16/32/64/etc.)).\nFor proper type inference (int, decimal, datetime2, varchar vs nvarchar), use -SampleRows or -DetectColumnTypes instead.\r\nFor production use with specific constraints, create tables manually with appropriate data types, indexes, and constraints.", "", false, "false", "False", "" ], [ "NoProgress", "Disables the progress bar display during import to improve performance, especially for very large files.\r\nUse this in automated scripts or when maximum import speed is more important than visual progress feedback.", "", false, "false", "False", "" ], [ "NoHeaderRow", "Treats the first row as data instead of column headers. Use this when your CSV file starts directly with data rows.\r\nWhen enabled, columns are mapped by ordinal position and you\u0027ll need to ensure your target table column order matches the CSV.", "", false, "false", "False", "" ], [ "UseFileNameForSchema", "Extracts the schema name from the filename using the first period as a delimiter. For example, \u0027sales.customers.csv\u0027 imports to the \u0027sales\u0027 schema.\r\nIf no period is found, defaults to \u0027dbo\u0027. The schema will be created if it doesn\u0027t exist. This parameter is ignored if -Schema is explicitly specified.", "", false, "false", "False", "" ], [ "Quote", "Specifies the character used to quote fields containing delimiters or special characters. Defaults to double-quote (\").\r\nChange this when your CSV uses different quoting conventions, such as single quotes from certain export tools.", "", false, "false", "\"", "" ], [ "Escape", "Specifies the character used to escape quote characters within quoted fields. Defaults to double-quote (\").\r\nModify this when dealing with CSV files that use different escaping conventions, such as backslash escaping.", "", false, "false", "\"", "" ], [ "Comment", "Specifies the character that marks comment lines to be ignored during import. Defaults to hashtag (#).\r\nUse this when your CSV files contain comment lines with metadata or instructions that should be skipped.", "", false, "false", "#", "" ], [ "TrimmingOption", "Controls automatic whitespace removal from field values. Options are All, None, UnquotedOnly, or QuotedOnly.\r\nUse \u0027All\u0027 to clean up data with inconsistent spacing, or \u0027None\u0027 to preserve exact formatting when whitespace is significant.", "", false, "false", "None", "All,None,UnquotedOnly,QuotedOnly" ], [ "BufferSize", "Sets the internal buffer size in bytes for reading the CSV file. Defaults to 4096 bytes.\r\nIncrease this value for better performance with very large files, but it will use more memory during the import process.", "", false, "false", "4096", "" ], [ "ParseErrorAction", "Determines how to handle malformed rows during import. \u0027ThrowException\u0027 stops the import, \u0027AdvanceToNextLine\u0027 skips bad rows.\r\nUse \u0027AdvanceToNextLine\u0027 for importing data with known quality issues where you want to load as much valid data as possible.", "", false, "false", "ThrowException", "AdvanceToNextLine,ThrowException" ], [ "Encoding", "Specifies the text encoding of the CSV file. Defaults to UTF-8.\r\nChange this when dealing with files from legacy systems that use different encodings like ASCII or when dealing with international character sets.", "", false, "false", "UTF8", "ASCII,BigEndianUnicode,Byte,String,Unicode,UTF7,UTF8,Unknown" ], [ "NullValue", "Specifies which text value in the CSV should be treated as SQL NULL. Common values include \u0027NULL\u0027, \u0027null\u0027, or empty strings.\r\nUse this when your source system exports NULL values as specific text strings that need to be converted to database NULLs.", "", false, "false", "", "" ], [ "MaxQuotedFieldLength", "Sets the maximum allowed length in bytes for quoted fields to prevent memory issues with malformed data.\r\nIncrease this when working with legitimate large text fields, or decrease it to catch data quality issues early.", "", false, "false", "0", "" ], [ "SkipEmptyLine", "Ignores completely empty lines in the CSV file during import.\r\nUse this when your source files contain blank lines for formatting that should not create empty rows in your table.", "", false, "false", "False", "" ], [ "SupportsMultiline", "Allows field values to span multiple lines when properly quoted, such as addresses or comments with embedded line breaks.\r\nEnable this when your CSV contains multi-line text data that should be preserved as single field values.", "", false, "false", "False", "" ], [ "UseColumnDefault", "Applies table column default values when CSV fields are missing or empty.\r\nUse this when your CSV doesn\u0027t include all table columns and you want defaults applied rather than NULLs or import failures.", "", false, "false", "False", "" ], [ "NoTransaction", "Disables the automatic transaction wrapper, allowing partial imports to remain committed even if the operation fails.\r\nUse this for very large imports where you want to commit data in batches, but be aware that failed imports may leave partial data.", "", false, "false", "False", "" ], [ "MaxDecompressedSize", "Maximum size in bytes for decompressed data when reading compressed CSV files (.gz, .br, .deflate, .zlib).\r\nThis protects against decompression bomb attacks. Default is 10GB (10737418240 bytes).\r\nSet to 0 for unlimited (not recommended for untrusted files).", "", false, "false", "10737418240", "" ], [ "SkipRows", "Number of rows to skip at the beginning of the file before reading headers or data.\r\nUseful for files with metadata rows before the actual CSV content.", "", false, "false", "0", "" ], [ "QuoteMode", "Controls how quoted fields are parsed.\r\n- Strict: RFC 4180 compliant parsing (default)\r\n- Lenient: More forgiving parsing for malformed CSV files with embedded quotes", "", false, "false", "Strict", "Strict,Lenient" ], [ "DuplicateHeaderBehavior", "Controls how duplicate column headers are handled.\r\n- ThrowException: Throw an error (default)\r\n- Rename: Rename duplicates (Name_2, Name_3, etc.)\r\n- UseFirstOccurrence: Keep first, ignore duplicates\r\n- UseLastOccurrence: Keep last, rename earlier occurrences", "", false, "false", "ThrowException", "ThrowException,Rename,UseFirstOccurrence,UseLastOccurrence" ], [ "MismatchedFieldAction", "Controls what happens when a row has more or fewer fields than expected.\r\n- ThrowException: Throw an error (default)\r\n- PadWithNulls: Pad missing fields with null\r\n- TruncateExtra: Remove extra fields\r\n- PadOrTruncate: Both pad and truncate as needed", "", false, "false", "ThrowException", "ThrowException,PadWithNulls,TruncateExtra,PadOrTruncate" ], [ "DistinguishEmptyFromNull", "When specified, treats empty quoted fields (\"\") as empty strings and\r\nunquoted empty fields (,,) as null values.", "", false, "false", "False", "" ], [ "NormalizeQuotes", "When specified, converts smart/curly quotes (\u0027 \u0027 \" \") to standard ASCII quotes before parsing.\r\nUseful when importing data exported from Microsoft Word or Excel.", "", false, "false", "False", "" ], [ "CollectParseErrors", "When specified, collects parse errors instead of throwing immediately.\r\nUse with -MaxParseErrors to limit the number of errors collected.\r\nErrors can be retrieved from the reader after import completes.", "", false, "false", "False", "" ], [ "MaxParseErrors", "Maximum number of parse errors to collect before stopping.\r\nOnly applies when -CollectParseErrors is specified. Default is 1000.", "", false, "false", "1000", "" ], [ "StaticColumns", "A hashtable of static column names and values to add to every row.\r\nUseful for tagging imported data with metadata like source filename or import timestamp.\r\nKeys are column names, values are the static values to insert.\r\nExample: @{ SourceFile = \"data.csv\"; ImportDate = (Get-Date) }", "", false, "false", "", "" ], [ "DateTimeFormats", "An array of custom date/time format strings for parsing date columns.\r\nUseful when importing data with non-standard date formats (e.g., Oracle\u0027s dd-MMM-yyyy).\r\nExample: @(\"dd-MMM-yyyy\", \"yyyy/MM/dd\", \"MM-dd-yyyy\")", "", false, "false", "", "" ], [ "Culture", "The culture name to use for parsing numbers and dates (e.g., \"de-DE\", \"fr-FR\", \"en-US\").\r\nUseful when importing CSV files with locale-specific number formats (e.g., comma as decimal separator).\r\nDefault is InvariantCulture.", "", false, "false", "", "" ], [ "SampleRows", "Enables smart type detection by sampling the first N rows of the CSV file.\r\nWhen specified, the command analyzes the sample to infer optimal SQL Server column types\r\ninstead of using nvarchar(MAX) for all columns.\nThis is faster than -DetectColumnTypes but has a small risk if data patterns change\r\nafter the sampled rows (e.g., row 10001 has a longer string than any in the sample).\nImplies -AutoCreateTable behavior for type detection.\nExample: -SampleRows 10000 samples the first 10,000 rows to determine types like\r\nint, bigint, decimal(p,s), datetime2, bit, uniqueidentifier, or varchar(n)/nvarchar(n)\r\nwith appropriate lengths. Unlike plain -AutoCreateTable, this can infer varchar for\r\nASCII-only string data, saving storage space.", "", false, "false", "0", "" ], [ "DetectColumnTypes", "Enables smart type detection by scanning the entire CSV file before import.\r\nThis guarantees no import failures due to type mismatches but requires reading\r\nthe file twice (once for analysis, once for import).\nA separate progress bar is displayed during the type detection phase.\r\nThe final output (Elapsed, RowsPerSecond) reflects only the import time,\r\nnot the detection overhead.\nImplies -AutoCreateTable behavior for type detection.\nDetected types include: int, bigint, decimal(p,s), datetime2, bit,\r\nuniqueidentifier, varchar(n) for ASCII-only strings, and nvarchar(n) when Unicode is detected.\r\nThis provides optimal storage by using varchar where possible.", "", false, "false", "False", "" ], [ "Parallel", "Enables parallel processing for improved performance on large files.\r\nWhen enabled, line reading, parsing, and type conversion are performed in parallel\r\nusing a producer-consumer pipeline. This can provide 2-4x performance improvement\r\non multi-core systems.\nNote: Parallel processing is most beneficial for large files (\u003e100K rows) with\r\ncomplex type conversions. For small files, sequential processing may be faster\r\ndue to lower overhead.\nWhen Parallel is used, the progress bar is disabled because the progress callback\r\ncannot run in background threads.", "", false, "false", "False", "" ], [ "ThrottleLimit", "Sets the maximum number of worker threads for parallel processing.\r\nDefault is 0, which uses the number of logical processors on the system.\r\nSet to 1 to effectively disable parallelism while still using the pipeline architecture.\r\nOnly used when Parallel is specified.", "", false, "false", "0", "" ], [ "ParallelBatchSize", "Sets the number of records to batch before yielding to the consumer during parallel processing.\r\nLarger batches reduce synchronization overhead but increase memory usage and latency.\r\nDefault is 100. Minimum is 1.\r\nOnly used when Parallel is specified.", "", false, "false", "100", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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": [ "Performance", "DataCollector", "PerfCounter" ], "CommandName": "Import-DbaPfDataCollectorSetTemplate", "Name": "Import-DbaPfDataCollectorSetTemplate", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Import-DbaPfDataCollectorSetTemplate [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-DisplayName] \u003cString\u003e] [-SchedulesEnabled] [[-RootPath] \u003cString\u003e] [-Segment] [[-SegmentMaxDuration] \u003cInt32\u003e] [[-SegmentMaxSize] \u003cInt32\u003e] [[-Subdirectory] \u003cString\u003e] [[-SubdirectoryFormat] \u003cInt32\u003e] [[-SubdirectoryFormatPattern] \u003cString\u003e] [[-Task] \u003cString\u003e] [-TaskRunAsSelf] [[-TaskArguments] \u003cString\u003e] [[-TaskUserTextArguments] \u003cString\u003e] [-StopOnCompletion] [[-Path] \u003cString[]\u003e] [[-Template] \u003cString[]\u003e] [[-Instance] \u003cString[]\u003e] [-EnableException] [-WhatIf] [-Confirm] \r\n[\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one Data Collector Set object for each template successfully imported or modified. When collector sets are created or updated, counters are automatically duplicated for each SQL Server \r\ninstance detected on the target machine.\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:\\\u003eImport-DbaPfDataCollectorSetTemplate -ComputerName sql2017 -Template \u0027Long Running Query\u0027\nCreates a new data collector set named \u0027Long Running Query\u0027 from the dbatools repository on the SQL Server sql2017.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eImport-DbaPfDataCollectorSetTemplate -ComputerName sql2017 -Template \u0027Long Running Query\u0027 -DisplayName \u0027New Long running query\u0027 -Confirm\nCreates a new data collector set named \"New Long Running Query\" using the \u0027Long Running Query\u0027 template. Forces a confirmation if the template exists.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorSet -ComputerName sql2017 -Session db_ola_health | Remove-DbaPfDataCollectorSet\nImport-DbaPfDataCollectorSetTemplate -ComputerName sql2017 -Template db_ola_health | Start-DbaPfDataCollectorSet\nImports a session if it exists, then recreates it using a template.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorSetTemplate | Out-GridView -PassThru | Import-DbaPfDataCollectorSetTemplate -ComputerName sql2017\nAllows you to select a Session template then import to an instance named sql2017.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eImport-DbaPfDataCollectorSetTemplate -ComputerName sql2017 -Template \u0027Long Running Query\u0027 -Instance SHAREPOINT\nCreates a new data collector set named \u0027Long Running Query\u0027 from the dbatools repository on the SQL Server sql2017 for both the default and the SHAREPOINT instance.\nIf you\u0027d like to remove counters for the default instance, use Remove-DbaPfDataCollectorCounter.", "Description": "Creates Windows Performance Monitor data collector sets using XML templates containing SQL Server performance counters. This eliminates the need to manually configure dozens of performance counters through the Performance Monitor GUI. The function can use built-in templates from the dbatools repository (like \u0027Long Running Query\u0027 or \u0027db_ola_health\u0027) or custom XML template files you specify.\n\nPerformance counters are automatically configured for all SQL Server instances detected on the target machine. When multiple instances exist, the function duplicates relevant counters for each instance so you get complete coverage across your SQL Server environment.\n\nRequires local administrator privileges on the target computer when importing data collector sets.\n\nSee https://msdn.microsoft.com/en-us/library/windows/desktop/aa371952 for more information", "Links": "https://dbatools.io/Import-DbaPfDataCollectorSetTemplate", "Synopsis": "Creates Windows Performance Monitor data collector sets with SQL Server-specific performance counters from predefined templates.", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the Windows server where the Performance Monitor data collector set will be created. Defaults to the local machine.\r\nUse this when monitoring SQL Server instances on remote servers or when centralizing performance monitoring from a management workstation.", "", 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", "", "" ], [ "DisplayName", "Sets the display name for the data collector set as it appears in Performance Monitor. Defaults to the template name.\r\nUse this to create meaningful names when deploying multiple collector sets or to distinguish between environments like \u0027Prod-SQL-Perf\u0027 or \u0027Dev-Query-Analysis\u0027.", "", false, "false", "", "" ], [ "SchedulesEnabled", "Enables scheduled data collection for the collector set if defined in the template. When disabled, the collector set must be started manually.\r\nUse this switch when you want the collector set to automatically start and stop based on predefined schedules rather than manual intervention.", "", false, "false", "False", "" ], [ "RootPath", "Specifies the base directory where performance log files will be stored. Defaults to %systemdrive%\\PerfLogs\\Admin\\[CollectorSetName].\r\nChange this when you need to store performance logs on a different drive with more space or faster storage for high-frequency data collection.", "", false, "false", "", "" ], [ "Segment", "Enables automatic log file segmentation when maximum file size or duration limits are reached during data collection.\r\nUse this to prevent single log files from becoming too large and to maintain manageable file sizes for analysis tools and storage management.", "", false, "false", "False", "" ], [ "SegmentMaxDuration", "Specifies the maximum time duration (in seconds) before a new log file is created during data collection. Requires -Segment to be enabled.\r\nSet this to control how long each performance log file covers, which helps with organizing data by time periods for analysis.", "", false, "false", "0", "" ], [ "SegmentMaxSize", "Specifies the maximum size (in bytes) for each performance log file before a new file is created. Requires -Segment to be enabled.\r\nSet this to prevent individual log files from consuming excessive disk space and to maintain consistent file sizes for easier management.", "", false, "false", "0", "" ], [ "Subdirectory", "Specifies a subdirectory name under the root path where log files will be stored for this collector set instance.\r\nUse this to organize performance logs by purpose, environment, or time period within your monitoring directory structure.", "", false, "false", "", "" ], [ "SubdirectoryFormat", "Controls how Performance Monitor decorates the subdirectory name with timestamp information. Uses numeric flags where 3 includes day/hour formatting.\r\nThis automatically creates time-stamped subdirectories to organize log files chronologically, making it easier to locate performance data from specific time periods.", "", false, "false", "3", "" ], [ "SubdirectoryFormatPattern", "Specifies the timestamp format pattern used for decorating subdirectory names. Default is \u0027yyyyMMdd\\-NNNNNN\u0027 (year-month-day-sequence).\r\nCustomize this pattern when you need specific date/time formatting for your log file organization or to match existing naming conventions.", "", false, "false", "yyyyMMdd\\-NNNNNN", "" ], [ "Task", "Specifies a Windows Task Scheduler job name to execute automatically when the data collector set stops or between log segments.\r\nUse this to trigger post-processing tasks like data analysis scripts, log file compression, or alerting when performance data collection completes.", "", false, "false", "", "" ], [ "TaskRunAsSelf", "Forces the scheduled task to run using the same user account as the data collector set rather than the account specified in the task definition.\r\nUse this when you need consistent security context between data collection and post-processing tasks for file access permissions.", "", false, "false", "False", "" ], [ "TaskArguments", "Specifies command-line arguments to pass to the scheduled task when it executes after data collection stops.\r\nUse this to pass parameters like log file paths, collection timestamps, or processing options to your post-collection analysis scripts.", "", false, "false", "", "" ], [ "TaskUserTextArguments", "Provides replacement text for the {usertext} placeholder variable in task arguments when the scheduled task executes.\r\nUse this to dynamically pass environment-specific information like server names, database names, or custom identifiers to your post-processing tasks.", "", false, "false", "", "" ], [ "StopOnCompletion", "Automatically stops the data collector set when all individual data collectors within the set have finished their collection tasks.\r\nUse this switch when you want the collector set to terminate cleanly after completing defined collection tasks rather than running indefinitely.", "", false, "false", "False", "" ], [ "Path", "Specifies the file path to custom XML template files containing performance counter definitions. Accepts multiple file paths.\r\nUse this when you have custom performance monitoring templates or need to import templates from sources other than the built-in dbatools repository.", "FullName", false, "true (ByPropertyName)", "", "" ], [ "Template", "Selects predefined performance monitoring templates from the dbatools repository such as \u0027Long Running Query\u0027 or \u0027db_ola_health\u0027. Press Tab to see available options.\r\nUse this for quick deployment of SQL Server-specific performance monitoring without creating custom XML templates.", "", false, "false", "", "" ], [ "Instance", "Specifies additional SQL Server named instances to include in performance monitoring beyond the default instance. The template applies to all detected instances by default.\r\nUse this when you have multiple SQL Server instances on a server and want to add specific named instances like \u0027SHAREPOINT\u0027 or \u0027REPORTING\u0027 to the monitoring scope.", "", 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": [ "RegisteredServer", "CMS" ], "CommandName": "Import-DbaRegServer", "Name": "Import-DbaRegServer", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Import-DbaRegServer [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Path] \u003cString[]\u003e] [[-InputObject] \u003cObject[]\u003e] [[-Group] \u003cObject\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.RegisteredServers.RegisteredServer\nReturns one RegisteredServer object for each server successfully imported into the target Central Management Server (CMS). When importing from XML files, returns only newly imported servers (servers \r\nthat did not exist before the import operation).\nDefault display properties (via Select-DefaultView):\r\n- Name: The display name of the registered server as shown in SSMS Registered Servers\r\n- ServerName: The actual SQL Server connection string (computer name, IP address, or instance name)\r\n- Group: The CMS group path (hierarchical, using backslash separators) or null for root-level servers\r\n- Description: Text description of the registered server\r\n- Source: Source location of the registration - \"Central Management Servers\", \"Local Server Groups\", or \"Azure Data Studio\"\nAdditional properties available from the RegisteredServer object (via Select-Object *):\r\n- ComputerName: NetBIOS computer name of the CMS instance\r\n- InstanceName: The SQL Server instance name of the CMS\r\n- SqlInstance: The full SQL Server instance name of the CMS\r\n- ParentServer: The parent CMS instance name\r\n- ConnectionString: The connection string with decrypted password if available\r\n- SecureConnectionString: The connection string as a SecureString object if password was decrypted\r\n- Id: Internal identifier for the registered server\r\n- ServerType: Type of server (DatabaseEngine, AnalysisServices, ReportingServices, etc.)\r\n- CredentialPersistenceType: Whether credentials are stored\r\n- Urn: The Uniform Resource Name (URN) for the registered server object\nAll properties from the base RegisteredServer SMO object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eImport-DbaRegServer -SqlInstance sql2012 -Path C:\\temp\\corp-regservers.xml\nImports C:\\temp\\corp-regservers.xml to the CMS on sql2012\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eImport-DbaRegServer -SqlInstance sql2008 -Group hr\\Seattle -Path C:\\temp\\Seattle.xml\nImports C:\\temp\\Seattle.xml to Seattle subgroup within the hr group on sql2008\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaRegServer -SqlInstance sql2008, sql2012 | Import-DbaRegServer -SqlInstance sql2017\nImports all registered servers from sql2008 and sql2012 to sql2017\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaRegServerGroup -SqlInstance sql2008 -Group hr\\Seattle | Import-DbaRegServer -SqlInstance sql2017 -Group Seattle\nImports all registered servers from the hr\\Seattle group on sql2008 to the Seattle group on sql2017", "Description": "Imports registered servers and server groups into a SQL Server Central Management Server (CMS) from multiple sources including exported XML files, other CMS instances, or custom objects like CSVs. The function automatically creates missing server groups during import and supports importing to specific group locations within the CMS hierarchy. This is essential for migrating CMS configurations between environments, consolidating server inventories from multiple sources, or bulk-loading server lists into a new CMS setup.", "Links": "https://dbatools.io/Import-DbaRegServer", "Synopsis": "Imports registered servers and server groups into SQL Server Central Management Server from XML files, other CMS instances, or custom objects", "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", "", "" ], [ "Path", "Specifies the file path to XML files containing exported registered server configurations from SQL Server Management Studio or Export-DbaRegServer.\r\nUse this when migrating CMS configurations between environments or restoring server lists from backup exports.", "FullName", false, "false", "", "" ], [ "InputObject", "Accepts registered server objects, server group objects, or custom objects like CSV data for bulk import operations. Supports piping from Get-DbaRegServer and Get-DbaRegServerGroup cmdlets.\r\nWhen importing from CSV or custom objects, ServerName column is required while Name, Description, and Group columns are optional. Use this for consolidating servers from multiple CMS instances or \r\nbulk-loading server inventories.", "", false, "true (ByValue)", "", "" ], [ "Group", "Specifies the target group within the CMS hierarchy where servers will be imported. Accepts group paths using backslash notation like \"hr\\Seattle\" or ServerGroup objects from Get-DbaRegServerGroup.\r\nUse this when you need to organize imported servers into specific groups rather than importing to the root level.", "", 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": [ "SpConfig", "Configure", "Configuration" ], "CommandName": "Import-DbaSpConfigure", "Name": "Import-DbaSpConfigure", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Import-DbaSpConfigure [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nImport-DbaSpConfigure [-Source \u003cDbaInstanceParameter\u003e] [-Destination \u003cDbaInstanceParameter\u003e] [-SourceSqlCredential \u003cPSCredential\u003e] [-DestinationSqlCredential \u003cPSCredential\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nImport-DbaSpConfigure [-SqlInstance \u003cDbaInstanceParameter\u003e] [-Path \u003cString\u003e] [-SqlCredential \u003cPSCredential\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.Boolean\nReturns $true if the sp_configure settings were successfully applied to the destination instance, or $false if the operation failed.\nWhen using the -ServerCopy parameter set, settings are migrated from the source instance to the destination instance and the command returns a boolean indicating success or failure of the overall \r\nmigration process.\nWhen using the -FromFile parameter set, sp_configure settings from a SQL file are executed against the target instance and the command returns a boolean indicating success or failure of the \r\nconfiguration import.\nNote: The function may also display warning messages about configuration options that require SQL Server restart, but these do not affect the boolean return value.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eImport-DbaSpConfigure -Source sqlserver -Destination sqlcluster\nImports the sp_configure settings from the source server sqlserver and sets them on the sqlcluster server using Windows Authentication\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eImport-DbaSpConfigure -Source sqlserver -Destination sqlcluster -Force\nImports the sp_configure settings from the source server sqlserver and sets them on the sqlcluster server using Windows Authentication. Will not do a version check between Source and Destination\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eImport-DbaSpConfigure -Source sqlserver -Destination sqlcluster -SourceSqlCredential $SourceSqlCredential -DestinationSqlCredential $DestinationSqlCredential\nImports the sp_configure settings from the source server sqlserver and sets them on the sqlcluster server using the SQL credentials stored in the variables $SourceSqlCredential and \r\n$DestinationSqlCredential\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eImport-DbaSpConfigure -SqlInstance sqlserver -Path .\\spconfig.sql -SqlCredential $SqlCredential\nImports the sp_configure settings from the file .\\spconfig.sql and sets them on the sqlserver server using the SQL credential stored in the variable $SqlCredential", "Description": "Copies all sp_configure settings from a source SQL Server instance to a destination instance, or applies sp_configure settings from a SQL file to an instance. This function handles advanced options visibility, validates server versions for compatibility, and executes the necessary RECONFIGURE statements. Essential for maintaining consistent configuration across environments during migrations, standardization projects, or when applying saved configuration templates.", "Links": "https://dbatools.io/Import-DbaSpConfigure", "Synopsis": "Copies sp_configure settings between SQL Server instances or applies settings from a SQL file.", "Availability": "Windows, Linux, macOS", "Params": [ [ "Source", "Source SQL Server instance to copy sp_configure settings from. Requires sysadmin privileges to read configuration values.\r\nUse this when migrating settings between servers or standardizing configurations across your environment.", "", false, "false", "", "" ], [ "Destination", "Target SQL Server instance where sp_configure settings will be applied. Requires sysadmin privileges to modify configuration.\r\nThis server will have its configuration updated to match the source server\u0027s settings.", "", false, "false", "", "" ], [ "SourceSqlCredential", "Credentials for connecting to the source SQL Server instance. Use when Windows authentication is not available.\r\nAccepts PowerShell credential objects created with Get-Credential.", "", false, "false", "", "" ], [ "DestinationSqlCredential", "Credentials for connecting to the destination SQL Server instance. Use when Windows authentication is not available.\r\nAccepts PowerShell credential objects created with Get-Credential.", "", false, "false", "", "" ], [ "SqlInstance", "Specifies a SQL Server instance to set up sp_configure values on using a SQL file.", "", false, "false", "", "" ], [ "Path", "Path to a SQL script file containing sp_configure commands to execute. The file should contain individual sp_configure statements.\r\nUse this parameter when applying saved configurations from Export-DbaSpConfigure or custom configuration scripts.", "", false, "false", "", "" ], [ "SqlCredential", "Use this SQL credential if you are setting up sp_configure values from a SQL file.\nLogin 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", "Bypasses the SQL Server version compatibility check between source and destination instances. By default, major versions must match.\r\nUse with caution as some configuration options may not be available or may behave differently across 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": "Module", "CommandName": "Import-DbatoolsConfig", "Name": "Import-DbatoolsConfig", "Author": "Friedrich Weinmann (@FredWeinmann)", "Syntax": "Import-DbatoolsConfig -Path \u003cString[]\u003e [-IncludeFilter \u003cString[]\u003e] [-ExcludeFilter \u003cString[]\u003e] [-Peek] [-EnableException] [\u003cCommonParameters\u003e]\nImport-DbatoolsConfig -ModuleName \u003cString\u003e [-ModuleVersion \u003cInt32\u003e] [-Scope {UserDefault | UserMandatory | SystemDefault | SystemMandatory | FileUserLocal | FileUserShared | FileSystem}] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.Object[] (when -Peek is specified)\nReturns an array of configuration element objects that would be imported without applying them. Each element has the following properties:\r\n- FullName (string) - The fully qualified configuration name (e.g., \u0027sql.connection.timeout\u0027)\r\n- Value (object) - The configuration value to be applied\r\n- Type (string) - The data type of the configuration value\r\n- KeepPersisted (boolean) - Boolean indicating if the value should remain persisted across sessions\nReturns nothing (when -Peek is not specified)\nWhen not using -Peek, the command imports configuration settings into the current session without returning output. Configuration is applied via Set-DbatoolsConfig and persists in the dbatools \r\nmodule\u0027s internal configuration storage.\nNote: The function writes status messages to the information stream during import, but these are not part of the formal output.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eImport-DbatoolsConfig -Path \u0027.\\config.json\u0027\nImports the configuration stored in \u0027.\\config.json\u0027\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eImport-DbatoolsConfig -ModuleName message\nImports all the module specific settings that have been persisted in any of the default file system paths.", "Description": "Loads dbatools configuration settings from JSON files or retrieves module-specific settings from default configuration locations. This lets you restore saved dbatools preferences, share standardized settings across your team, or apply configuration baselines to multiple servers. You can import from local files, web URLs, or raw JSON strings, with optional filtering to selectively apply only the settings you need.", "Links": "https://dbatools.io/Import-DbatoolsConfig", "Synopsis": "Imports dbatools configuration settings from JSON files or default module paths.", "Availability": "Windows, Linux, macOS", "Params": [ [ "Path", "Specifies the path to JSON configuration files, web URLs, or raw JSON strings to import settings from.\r\nUse this to restore saved dbatools preferences, apply team-standard configurations, or load settings from remote locations.\r\nAccepts local file paths, HTTP/HTTPS URLs, or direct JSON content as strings.", "", true, "true (ByValue)", "", "" ], [ "ModuleName", "Specifies which dbatools module\u0027s configuration settings to import from default system locations.\r\nUse this to restore module-specific settings that were previously saved using Export-DbatoolsConfig.\r\nCommon modules include \u0027message\u0027 for logging preferences and \u0027sql\u0027 for connection defaults.", "", true, "false", "", "" ], [ "ModuleVersion", "Specifies which version of the module configuration schema to load when importing persisted settings.\r\nDefaults to version 1, which works for most scenarios unless you\u0027re working with legacy configuration exports.\r\nOnly change this if you\u0027re importing settings exported with a different version of dbatools.", "", false, "false", "1", "" ], [ "Scope", "Controls which configuration storage locations to search when importing module settings.\r\nOptions include FileUserLocal (user profile), FileUserShared (shared user settings), and FileSystem (system-wide).\r\nUser settings override system settings when the same configuration exists in multiple locations.", "", false, "false", "FileUserLocal, FileUserShared, FileSystem", "" ], [ "IncludeFilter", "Specifies wildcard patterns to selectively import only matching configuration items from the source.\r\nUse this to import specific settings like \u0027sql.connection.*\u0027 for connection-related configs or \u0027logging.*\u0027 for logging preferences.\r\nSupports PowerShell -like wildcard matching with * and ? characters.", "", false, "false", "", "" ], [ "ExcludeFilter", "Specifies wildcard patterns to exclude specific configuration items during import.\r\nUse this to skip sensitive settings like credentials or environment-specific paths when sharing configurations.\r\nApplied after IncludeFilter, allowing you to include a category but exclude specific items within it.", "", false, "false", "", "" ], [ "Peek", "Returns the configuration items that would be imported without actually applying them to your session.\r\nUse this to preview configuration changes before applying them, especially when importing from unfamiliar sources.\r\nHelpful for validating configuration files and understanding what settings will be modified.", "", 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": "Import-DbaXESessionTemplate", "Name": "Import-DbaXESessionTemplate", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Import-DbaXESessionTemplate [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Name] \u003cString\u003e] [[-Path] \u003cString[]\u003e] [[-Template] \u003cString[]\u003e] [[-TargetFilePath] \u003cString\u003e] [[-TargetFileMetadataPath] \u003cString\u003e] [[-StartUpState] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.XEvent.Session\nReturns one Extended Events session object for each template successfully imported and created. When -StartUpState On is specified, the session is also started and configured to autostart on server \r\nrestart.\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 Extended Events session\r\n- Status: Current session status (Running, Stopped, or other state values)\r\n- StartTime: DateTime when the session was started (null if stopped)\r\n- AutoStart: Boolean indicating if the session starts automatically on SQL Server restart\r\n- State: SMO object state (Existing, Creating, Pending, Dropping, etc.)\r\n- Targets: Target collection for the session (event file, ring buffer, etc.)\r\n- TargetFile: File path(s) where XE trace data is being written\r\n- Events: Events configured in the session\r\n- MaxMemory: Maximum memory in MB allocated to the session\r\n- MaxEventSize: Maximum size in MB for individual events\nAdditional properties available (from SMO Session object):\r\n- Parent: Reference to the parent XEStore object\r\n- Store: Reference to the parent XEStore object\r\n- Session: Copy of the session name property\r\n- RemoteTargetFile: UNC paths for remote target files\r\n- All other standard SMO Session properties accessible via Select-Object *\nAll properties from the base SMO XEvent.Session object are accessible even though only default properties are displayed without using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eImport-DbaXESessionTemplate -SqlInstance sql2017 -Template \"15 Second IO Error\"\nCreates a new XESession named \"15 Second IO Error\" from the dbatools repository to the SQL Server sql2017.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eImport-DbaXESessionTemplate -SqlInstance sql2017 -Template \"Index Page Splits\" -StartUpState On\nCreates a new XESession named \"Index Page Splits\" from the dbatools repository to the SQL Server sql2017, starts the XESession and sets the StartUpState to On so that it starts on the next server \r\nrestart.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eImport-DbaXESessionTemplate -SqlInstance sql2017 -Template \"Query Wait Statistics\" -Name \"Query Wait Stats\" | Start-DbaXESession\nCreates a new XESession named \"Query Wait Stats\" using the Query Wait Statistics template, then immediately starts it.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaXESession -SqlInstance sql2017 -Session \u0027Database Health 2014\u0027 | Remove-DbaXESession\nPS C:\\\u003e Import-DbaXESessionTemplate -SqlInstance sql2017 -Template \u0027Database Health 2014\u0027 | Start-DbaXESession\nRemoves a session if it exists, then recreates it using a template.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaXESessionTemplate | Out-GridView -PassThru | Import-DbaXESessionTemplate -SqlInstance sql2017\nAllows you to select a Session template then import to an instance named sql2017.", "Description": "Creates new Extended Events sessions using predefined XML templates from the dbatools repository or custom template files you specify. This function simplifies XE session deployment by providing ready-to-use templates for common monitoring scenarios like performance troubleshooting, security auditing, and health monitoring.\n\nTemplates from the dbatools repository include popular configurations for index page splits, query wait statistics, deadlock monitoring, IO errors, and database health checks. You can also import custom templates created from existing sessions or third-party sources.\n\nThe function automatically handles SQL Server version compatibility, validates template XML structure, checks for existing sessions to prevent conflicts, and can optionally start sessions immediately with auto-start configuration for server restarts.", "Links": "https://dbatools.io/Import-DbaXESessionTemplate", "Synopsis": "Creates Extended Events sessions from XML templates on 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 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", "", "" ], [ "Name", "Specifies a custom name for the Extended Events session being created. When not provided, the session name defaults to the template filename.\r\nUse this when you need multiple sessions from the same template or want descriptive names that match your monitoring standards.", "", false, "false", "", "" ], [ "Path", "Specifies the full file path to custom Extended Events session XML template files. Accepts multiple file paths for bulk imports.\r\nUse this when importing custom templates you\u0027ve created or third-party XE session definitions instead of built-in dbatools templates.", "FullName", false, "true (ByPropertyName)", "", "" ], [ "Template", "Specifies the name of a built-in Extended Events template from the dbatools repository. Accepts multiple template names for bulk deployment.\r\nUse tab completion to browse available templates like \"Blocked Process Report\", \"Query Wait Statistics\", or \"Index Page Splits\". These templates provide pre-configured monitoring for common DBA \r\nscenarios.", "", false, "false", "", "" ], [ "TargetFilePath", "Overrides the default directory for Extended Events trace files (.xel files) in the template. Specify only the directory path, not filenames.\r\nUse this when you need XE files stored in specific locations for storage management, compliance, or performance reasons. The path is relative to the SQL Server instance.", "", false, "false", "", "" ], [ "TargetFileMetadataPath", "Overrides the default directory for Extended Events metadata files (.xem files) in the template. Specify only the directory path, not filenames.\r\nUse this when you need XE metadata files stored separately from trace files or in specific locations for organizational purposes. The path is relative to the SQL Server instance.", "", false, "false", "", "" ], [ "StartUpState", "Controls whether the Extended Events session starts immediately and automatically restarts after SQL Server restarts. Default is Off.\r\nSet to \"On\" when you need continuous monitoring that survives server restarts, such as for production performance monitoring or security auditing sessions.", "", false, "false", "Off", "On,Off" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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": "Install-DbaAgentAdminAlert", "Name": "Install-DbaAgentAdminAlert", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Install-DbaAgentAdminAlert [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Category] \u003cString\u003e] [[-Database] \u003cString\u003e] [[-Operator] \u003cString\u003e] [[-OperatorEmail] \u003cString\u003e] [[-DelayBetweenResponses] \u003cInt32\u003e] [-Disabled] [[-EventDescriptionKeyword] \u003cString\u003e] [[-EventSource] \u003cString\u003e] [[-JobId] \u003cString\u003e] [[-ExcludeSeverity] \u003cInt32[]\u003e] [[-ExcludeMessageId] \u003cInt32[]\u003e] [[-NotificationMessage] \u003cString\u003e] [[-NotifyMethod] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Alert\nReturns one Alert object per severity level or message ID for which an alert was successfully created. By default, this results in 12 objects (9 severity levels 17-25 plus 3 message IDs 823-825), or \r\nfewer if specific severities or message IDs are excluded via -ExcludeSeverity or -ExcludeMessageId parameters.\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\r\n- Name: The alert name (e.g., \"Severity 017 - Insufficient Resources\", \"Error Number 823 - Read/Write Error\")\r\n- Severity: The error severity level being monitored (0 for message ID alerts, 17-25 for severity alerts)\r\n- MessageId: The error message ID being monitored (0 for severity alerts, 823-825 for message ID alerts)\r\n- JobName: Name of the SQL Server Agent job executed when alert fires (if -JobId was specified)\r\n- CategoryName: Name of the alert category (if -Category was specified)\r\n- DelayBetweenResponses: Minimum seconds between alert notifications (if -DelayBetweenResponses was specified)\r\n- ID: Unique identifier for the alert within the instance\r\n- AlertType: Type of alert (Severity or Message ID based)\r\n- IsEnabled: Boolean indicating if the alert is enabled\r\n- LastRaised: DateTime when the alert last fired\r\n- OccurrenceCount: Number of times the alert has fired\nAdditional properties available (from SMO Alert object):\r\n- CategoryId: Numeric 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 specific database alert is restricted to (if -Database was specified)\r\n- Urn: The Uniform Resource Name of the alert object\r\n- State: SMO object state (Existing, Creating, Pending, Dropping, etc.)\r\n- Notifications: DataTable containing notification settings for operators\r\n- EventSource: Event source filter if specified\r\n- EventDescriptionKeyword: Event description keyword filter if specified\r\n- NotifyMethod: Notification method configured for the alert\nAll properties from the base SMO Alert object are accessible using Select-Object * even though only default properties are displayed by default.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInstall-DbaAgentAdminAlert -SqlInstance sql1\nCreates alerts for severity 17-25 and messages 823-825 on sql1", "Description": "Creates a predefined set of SQL Server Agent alerts that monitor for critical system errors (severity levels 17-25) and disk I/O corruption errors (messages 823-825). These alerts catch serious issues like hardware failures, database corruption, insufficient resources, and fatal system errors that require immediate DBA attention.\n\nThe function automatically creates alerts for severity levels 17-25 and error messages 823-825 unless specifically excluded. It can create missing operators and alert categories as needed, making it easy to establish consistent monitoring across multiple SQL Server instances.\n\nYou can specify an operator to use for the alert, or it will use any operator it finds if there is just one. Alternatively, if you specify both an operator name and an email, it will create the operator if it does not exist.", "Links": "https://dbatools.io/Install-DbaAgentAdminAlert", "Synopsis": "Creates standard SQL Server Agent alerts for critical system errors and disk I/O failures", "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", "", "" ], [ "Category", "Assigns the alerts to a specific SQL Server Agent alert category for better organization and management. Defaults to \u0027Uncategorized\u0027 if not specified.\r\nUse this to group related alerts together, making it easier to manage alert policies and review alert activity in SQL Server Management Studio. If the category doesn\u0027t exist, it will be created \r\nautomatically.", "", false, "false", "", "" ], [ "Database", "Restricts the alerts to fire only for errors occurring in the specified database. If not specified, alerts will fire for errors in any database on the instance.\r\nUse this when you want to monitor only specific critical databases and avoid noise from test or development databases on the same instance.", "", false, "false", "", "" ], [ "Operator", "Specifies the SQL Server Agent operator who will receive notifications when these alerts are triggered. The operator must already exist on the target instance unless you also provide OperatorEmail.\r\nIf not specified and only one operator exists on the instance, that operator will be used automatically. Required for alert notifications to function properly.", "", false, "false", "", "" ], [ "OperatorEmail", "Creates a new SQL Server Agent operator with this email address if the specified operator name doesn\u0027t exist. Must be used together with the Operator parameter.\r\nThis allows you to set up both the operator and alerts in a single command when configuring monitoring on a new instance.", "", false, "false", "", "" ], [ "DelayBetweenResponses", "Sets the minimum time in seconds that must pass before the alert can fire again for the same condition. Prevents notification spam when errors occur repeatedly.\r\nUse this to avoid flooding your inbox during cascading failures or when the same error occurs multiple times in rapid succession.", "", false, "false", "0", "" ], [ "Disabled", "Creates the alerts in a disabled state, preventing them from firing until manually enabled. By default, alerts are created in an enabled state.\r\nUse this when you want to set up the alert infrastructure first and enable specific alerts later after testing or validation.", "", false, "false", "False", "" ], [ "EventDescriptionKeyword", "Filters alerts to fire only when the error message text contains this specific keyword or phrase. Applied in addition to the standard severity and message ID criteria.\r\nUse this to create more targeted alerts that focus on specific error conditions within the broader categories of critical system errors.", "", false, "false", "", "" ], [ "EventSource", "Restricts alerts to fire only for errors originating from a specific event source or application. If not specified, alerts will fire regardless of the error source.\r\nUse this to focus monitoring on specific applications or services that interact with your SQL Server instance when you want to isolate alerts from particular systems.", "", false, "false", "", "" ], [ "JobId", "Specifies a SQL Server Agent job to execute automatically when any of these alerts fire. Must be a valid job GUID that exists on the target instance.\r\nUse this to trigger automated response scripts, such as collecting diagnostic information, attempting automatic recovery, or escalating to additional monitoring systems.", "", false, "false", "00000000-0000-0000-0000-000000000000", "" ], [ "ExcludeSeverity", "Excludes specific error severity levels from the standard alert creation. By default, the function creates alerts for severity levels 17-25 which cover resource issues, internal errors, and fatal \r\nsystem problems.\r\nUse this when you want to skip certain severities, perhaps because you already have custom alerts configured for them or they\u0027re not relevant to your environment.", "", false, "false", "", "" ], [ "ExcludeMessageId", "Excludes specific SQL Server error message IDs from the standard alert creation. By default, the function creates alerts for messages 823-825 which detect disk I/O hardware errors and database \r\ncorruption issues.\r\nUse this when you want to skip certain message IDs, perhaps because you have existing custom alerts for these errors or they don\u0027t apply to your storage configuration.", "", false, "false", "", "" ], [ "NotificationMessage", "Customizes the message content sent to operators when an alert fires. If not specified, SQL Server uses the default system-generated message.\r\nUse this to include specific instructions, contact information, or troubleshooting steps that help your team respond more effectively to critical errors.", "", false, "false", "", "" ], [ "NotifyMethod", "Specifies how the operator should be notified when the alert fires. Valid options are \u0027NotifyEmail\u0027, \u0027Pager\u0027, \u0027NetSend\u0027, \u0027NotifyAll\u0027, or \u0027None\u0027. Defaults to \u0027NotifyAll\u0027.\r\nUse \u0027NotifyEmail\u0027 for email-only notifications, \u0027NotifyAll\u0027 to use all configured notification methods for the operator, or \u0027None\u0027 to create alerts without notifications (useful for logging only).", "", false, "false", "NotifyAll", "None,NotifyEmail,Pager,NetSend,NotifyAll" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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", "Erik Darling", "DarlingData" ], "CommandName": "Install-DbaDarlingData", "Name": "Install-DbaDarlingData", "Author": "Ant Green (@ant_green)", "Syntax": "Install-DbaDarlingData [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject\u003e] [[-Branch] \u003cString\u003e] [[-Procedure] \u003cString[]\u003e] [[-LocalFile] \u003cString\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per script file processed. When installing all procedures, one object is returned per SQL script file encountered. When using the -Procedure parameter to install specific \r\nprocedures, only scripts matching those procedures are processed and returned.\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 target database where scripts are installed\r\n- Name: The base name of the script file (without extension)\r\n- Status: Installation status - \u0027Installed\u0027 (newly created), \u0027Updated\u0027 (already existed and was overwritten), \u0027Skipped\u0027 (version incompatible like sp_QuickieStore on SQL Server \u003c 2016), or \u0027Error\u0027 \r\n(script execution failed)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInstall-DbaDarlingData -SqlInstance server1 -Database master\nLogs into server1 with Windows authentication and then installs all of Erik\u0027s scripts in the master database.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInstall-DbaDarlingData -SqlInstance server1\\instance1 -Database DBA\nLogs into server1\\instance1 with Windows authentication and then installs all of Erik\u0027s scripts in the DBA database.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eInstall-DbaDarlingData -SqlInstance server1\\instance1 -Database master -SqlCredential $cred\nLogs into server1\\instance1 with SQL authentication and then installs all of Erik\u0027s scripts in the master database.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eInstall-DbaDarlingData -SqlInstance sql2016\\standardrtm, sql2016\\sqlexpress, sql2014\nLogs into sql2016\\standardrtm, sql2016\\sqlexpress and sql2014 with Windows authentication and then installs al of Erik\u0027s scripts in the master database.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eInstall-DbaDarlingData -SqlInstance sql2016 -Branch dev\nInstalls the dev branch version of Erik\u0027s scripts in the master database on sql2016 instance.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eInstall-DbaDarlingData -SqlInstance server1\\instance1 -Database DBA -Procedure Human, Pressure\nLogs into server1\\instance1 with Windows authentication and then installs sp_HumanEvents and sp_PressureDetector of Erik\u0027s scripts in the DBA database.", "Description": "Downloads, extracts and installs Erik Darling\u0027s collection of performance monitoring stored procedures from the DarlingData GitHub repository. This gives you access to popular diagnostic tools like sp_HumanEvents for extended events analysis, sp_PressureDetector for memory pressure monitoring, sp_QuickieStore for Query Store analysis, and several others that help with SQL Server performance troubleshooting. The function handles version compatibility automatically (for example, skipping sp_QuickieStore on SQL Server versions below 2016) and only installs the stored procedures themselves, not other repository contents like views or documentation.\n\nDarlingData links:\nhttps://www.erikdarling.com\nhttps://github.com/erikdarlingdata/DarlingData", "Links": "https://dbatools.io/Install-DbaDarlingData", "Synopsis": "Downloads and installs Erik Darling\u0027s performance monitoring stored procedures", "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 the target database where Erik Darling\u0027s performance monitoring stored procedures will be installed.\r\nCommonly set to master, DBA, or a dedicated administrative database where diagnostic procedures are centralized.\r\nThe database must already exist on the target instance.", "", false, "false", "master", "" ], [ "Branch", "Specifies which branch of the DarlingData repository to install from.\r\nUse \u0027main\u0027 for the latest stable release or \u0027dev\u0027 for experimental features and bug fixes.\r\nThe dev branch may contain newer procedures or fixes not yet available in the main branch.\r\nAllowed values:\r\n main (default)\r\n dev", "", false, "false", "main", "main,dev" ], [ "Procedure", "Specifies which specific performance monitoring procedures to install instead of the complete collection.\r\nUse this when you only need particular diagnostic tools or want to avoid installing procedures you don\u0027t use.\r\nEach procedure addresses different performance areas: HumanEvents for extended events analysis, PressureDetector for memory pressure monitoring, QuickieStore for Query Store analysis.\r\nAllowed Values or Combination of Values:\r\n All (default, to install all procedures)\r\n HumanEvents (to install sp_HumanEvents)\r\n PressureDetector (to install sp_PressureDetector)\r\n QuickieStore (to install sp_QuickieStore)\r\n HumanEventsBlockViewer (to install sp_HumanEventsBlockViewer)\r\n LogHunter (to install sp_LogHunter)\r\n HealthParser (to install sp_HealthParser)\r\n IndexCleanup (to install sp_IndexCleanup)\r\n PerfCheck (to install sp_PerfCheck)\r\nThe following shorthands are allowed, ordered as above: Human, Pressure, Quickie, Block, Log, Health, Index, Perf.", "", false, "false", "All", "All,Human,HumanEvents,Pressure,PressureDetector,Quickie,QuickieStore,Block,HumanEventsBlockViewer,Log,LogHunter,Health,HealthParser,Index,IndexCleanup,Perf,PerfCheck" ], [ "LocalFile", "Specifies the path to a local zip file containing the DarlingData procedures instead of downloading from GitHub.\r\nUse this when internet access is restricted, when you need to install a specific version, or when you have a pre-downloaded copy.\r\nThe file must be the official zip distribution from the DarlingData repository maintainers.\r\nIf this parameter is not specified, the latest version will be downloaded and installed from https://github.com/erikdarlingdata/DarlingData", "", false, "false", "", "" ], [ "Force", "Forces a fresh download of the DarlingData procedures even if a cached version already exists locally.\r\nUse this when you need to ensure you have the absolute latest version or when troubleshooting installation issues.\r\nWithout this switch, the function uses the cached version if available to improve performance.", "", 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 to confirm actions", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Community", "FirstResponderKit" ], "CommandName": "Install-DbaFirstResponderKit", "Name": "Install-DbaFirstResponderKit", "Author": "Tara Kizer, Brent Ozar Unlimited (brentozar.com)", "Syntax": "Install-DbaFirstResponderKit [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Branch] \u003cString\u003e] [[-Database] \u003cObject\u003e] [[-LocalFile] \u003cString\u003e] [[-OnlyScript] \u003cString[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per script file processed. By default, returns one object per .sql file matching the sp_*.sql pattern plus SqlServerVersions.sql. When using the -OnlyScript parameter, only \r\nspecified scripts are processed and returned.\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 target database where scripts are installed\r\n- Name: The base name of the script file (without extension)\r\n- Status: Installation status - \u0027Installed\u0027 (newly created), \u0027Updated\u0027 (already existed and was overwritten), \u0027Skipped\u0027 (version incompatible like sp_BlitzQueryStore on SQL Server \u003c 2016 or \r\nsp_BlitzInMemoryOLTP on SQL Server \u003c 2014), or \u0027Error\u0027 (script execution failed)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInstall-DbaFirstResponderKit -SqlInstance server1 -Database master\nLogs into server1 with Windows authentication and then installs the FRK in the master database.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInstall-DbaFirstResponderKit -SqlInstance server1\\instance1 -Database DBA\nLogs into server1\\instance1 with Windows authentication and then installs the FRK in the DBA database.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eInstall-DbaFirstResponderKit -SqlInstance server1\\instance1 -Database master -SqlCredential $cred\nLogs into server1\\instance1 with SQL authentication and then installs the FRK in the master database.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eInstall-DbaFirstResponderKit -SqlInstance sql2016\\standardrtm, sql2016\\sqlexpress, sql2014\nLogs into sql2016\\standardrtm, sql2016\\sqlexpress and sql2014 with Windows authentication and then installs the FRK in the master database.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$servers = \"sql2016\\standardrtm\", \"sql2016\\sqlexpress\", \"sql2014\"\nPS C:\\\u003e $servers | Install-DbaFirstResponderKit\nLogs into sql2016\\standardrtm, sql2016\\sqlexpress and sql2014 with Windows authentication and then installs the FRK in the master database.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eInstall-DbaFirstResponderKit -SqlInstance sql2016 -Branch dev\nInstalls the dev branch version of the FRK in the master database on sql2016 instance.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eInstall-DbaFirstResponderKit -SqlInstance sql2016 -OnlyScript sp_Blitz.sql, sp_BlitzWho.sql, SqlServerVersions.sql\nInstalls only the procedures sp_Blitz and sp_BlitzWho and the table SqlServerVersions by running the corresponding scripts.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eInstall-DbaFirstResponderKit -SqlInstance sql2016 -OnlyScript Install-All-Scripts.sql\nInstalls the First Responder Kit using the official install script.\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003eInstall-DbaFirstResponderKit -SqlInstance sql-server-001.database.windows.net -OnlyScript Install-Azure.sql\nInstalls the First Responder Kit using the official install script for Azure SQL Database.\n-------------------------- EXAMPLE 10 --------------------------\nPS C:\\\u003eInstall-DbaFirstResponderKit -SqlInstance sql2016 -OnlyScript Uninstall.sql\nUninstalls the First Responder Kit by running the official uninstall script.", "Description": "Downloads and installs the First Responder Kit (FRK), a collection of stored procedures designed for SQL Server health checks, performance analysis, and troubleshooting. The FRK includes essential procedures like sp_Blitz for overall health assessment, sp_BlitzCache for query performance analysis, sp_BlitzIndex for index recommendations, and sp_BlitzFirst for real-time performance monitoring.\n\nThis function automatically downloads the latest version from GitHub, caches it locally, and installs the procedures into your specified database. You can install the complete toolkit or select specific procedures based on your needs. The function handles version compatibility automatically, skipping procedures that aren\u0027t supported on older SQL Server versions.\n\nPerfect for DBAs who need standardized diagnostic tools across multiple SQL Server instances without manually downloading and deploying scripts.\n\nFirst Responder Kit links:\nhttp://FirstResponderKit.org\nhttps://github.com/BrentOzarULTD/SQL-Server-First-Responder-Kit", "Links": "https://dbatools.io/Install-DbaFirstResponderKit", "Synopsis": "Downloads and installs Brent Ozar\u0027s First Responder Kit diagnostic stored procedures.", "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", "", "" ], [ "Branch", "Specifies which GitHub branch of the First Responder Kit to download and install. Defaults to \u0027main\u0027 for the stable release.\r\nUse \u0027dev\u0027 to install the development branch when you need the latest features or bug fixes that haven\u0027t been released yet.", "", false, "false", "main", "main,dev" ], [ "Database", "Specifies the target database where the First Responder Kit stored procedures will be installed. Defaults to master.\r\nConsider using a dedicated DBA or utility database instead of master for better organization and maintenance.", "", false, "false", "master", "" ], [ "LocalFile", "Specifies the path to a local zip file containing the First Responder Kit scripts instead of downloading from GitHub.\r\nUse this when you have a specific version cached locally, when internet access is restricted, or when you need to install a customized version of the toolkit.", "", false, "false", "", "" ], [ "OnlyScript", "Specifies specific script files to install instead of the entire First Responder Kit. Accepts multiple script names and wildcards.\r\nUse this to install only the procedures you need (like sp_Blitz.sql, sp_BlitzCache.sql) or to run official install scripts (Install-All-Scripts.sql, Install-Azure.sql). Also supports Uninstall.sql to \r\nremove the toolkit.", "", false, "false", "", "Install-All-Scripts.sql,Install-Azure.sql,sp_Blitz.sql,sp_BlitzFirst.sql,sp_BlitzIndex.sql,sp_BlitzCache.sql,sp_BlitzWho.sql,sp_BlitzAnalysis.sql,sp_BlitzBackups.sql,sp_BlitzLock.sql,sp_DatabaseRestore.sql,sp_ineachdb.sql,SqlServerVersions.sql,Uninstall.sql" ], [ "Force", "Forces a fresh download of the First Responder Kit from GitHub even if a cached version already exists locally.\r\nUse this when you want to ensure you have the absolute latest version or when the cached version may be corrupted.", "", 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 to confirm actions", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Deployment", "Install" ], "CommandName": "Install-DbaInstance", "Name": "Install-DbaInstance", "Author": "Reitse Eskens (@2meterDBA), Kirill Kravtsov (@nvarscar)", "Syntax": "Install-DbaInstance [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [-Version] \u003cString\u003e [[-InstanceName] \u003cString\u003e] [[-SaCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [[-Authentication] \u003cString\u003e] [[-ConfigurationFile] \u003cObject\u003e] [[-Configuration] \u003cHashtable\u003e] [[-Path] \u003cString[]\u003e] [[-Feature] \u003cString[]\u003e] [[-AuthenticationMode] \u003cString\u003e] [[-InstancePath] \u003cString\u003e] [[-DataPath] \u003cString\u003e] [[-LogPath] \u003cString\u003e] [[-TempPath] \u003cString\u003e] [[-BackupPath] \u003cString\u003e] [[-UpdateSourcePath] \u003cString\u003e] [[-AdminAccount] \u003cString[]\u003e] [[-ASAdminAccount] \u003cString[]\u003e] [[-Port] \u003cInt32\u003e] [[-Throttle] \u003cInt32\u003e] \r\n[[-ProductID] \u003cString\u003e] [[-AsCollation] \u003cString\u003e] [[-SqlCollation] \u003cString\u003e] [[-EngineCredential] \u003cPSCredential\u003e] [[-AgentCredential] \u003cPSCredential\u003e] [[-ASCredential] \u003cPSCredential\u003e] [[-ISCredential] \u003cPSCredential\u003e] [[-RSCredential] \u003cPSCredential\u003e] [[-FTCredential] \u003cPSCredential\u003e] [[-PBEngineCredential] \u003cPSCredential\u003e] [[-SaveConfiguration] \u003cString\u003e] [-PerformVolumeMaintenanceTasks] [-Restart] [-NoPendingRenameCheck] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance installed, providing detailed installation results and status information for each target computer.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The target computer where SQL Server was installed\r\n- InstanceName: The SQL Server instance name that was installed\r\n- Version: The SQL Server version installed (e.g., 14.0 for SQL Server 2017)\r\n- Port: The TCP port configured for the instance after installation (nullable int, null if default 1433)\r\n- Successful: Boolean indicating if the installation completed successfully (True/False)\r\n- Restarted: Boolean indicating if the computer was restarted during installation (True/False)\r\n- Installer: The full path to the SQL Server setup.exe file used for installation\r\n- ExitCode: The exit code returned by setup.exe (nullable int; 0 = success, 3010 = reboot required, other values = failure)\r\n- LogFile: The full path to the installation Summary.txt log file on the target computer\r\n- Notes: Array of strings containing installation warnings, errors, or post-installation action notes\nAdditional properties available:\r\n- SACredential: The SA account credential provided if mixed-mode authentication was configured\r\n- Configuration: The hashtable of SQL Server configuration settings used for installation\r\n- ExitMessage: Detailed exit message text extracted from the installation summary log\r\n- Log: Full contents of the installation Summary.txt file as array of strings, includes detailed setup diagnostics\r\n- ConfigurationFile: Path to the ConfigurationFile.ini used during installation on the target computer\nWhen multiple instances are specified via -SqlInstance, one object is returned per instance. When -Throttle limits parallelism,\r\ninstallation objects are returned as each instance completes. Examine the Successful and ExitCode properties to determine\r\ninstallation outcome; ExitMessage and Log properties contain detailed diagnostic information for troubleshooting failed installations.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInstall-DbaInstance -Version 2017 -Feature All\nInstall a default SQL Server instance and run the installation enabling all features with default settings. Automatically generates configuration.ini\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInstall-DbaInstance -SqlInstance sql2017\\sqlexpress, server01 -Version 2017 -Feature Default\nInstall a named SQL Server instance named sqlexpress on sql2017, and a default instance on server01. Automatically generates configuration.ini.\r\nDefault features will be installed.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eInstall-DbaInstance -Version 2008R2 -SqlInstance sql2017 -ConfigurationFile C:\\temp\\configuration.ini\nInstall a default named SQL Server instance on the remote machine, sql2017 and use the local configuration.ini\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eInstall-DbaInstance -Version 2017 -InstancePath G:\\SQLServer -UpdateSourcePath \u0027\\\\my\\updates\u0027\nRun the installation locally with default settings apart from the application volume, this will be redirected to G:\\SQLServer.\r\nThe installation procedure would search for SQL Server updates in \\\\my\\updates and slipstream them into the installation.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$svcAcc = Get-Credential MyDomain\\SvcSqlServer\nPS C:\\\u003e Install-DbaInstance -Version 2016 -InstancePath D:\\Root -DataPath E: -LogPath L: -PerformVolumeMaintenanceTasks -EngineCredential $svcAcc\nInstall SQL Server 2016 instance into D:\\Root drive, set default data folder as E: and default logs folder as L:.\r\nPerform volume maintenance tasks permission is granted. MyDomain\\SvcSqlServer is used as a service account for SqlServer.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e$svcAcc = [PSCredential]::new(\"MyDomain\\SvcSqlServer$\", [SecureString]::new())\nPS C:\\\u003e Install-DbaInstance -Version 2016 -InstancePath D:\\Root -DataPath E: -LogPath L: -PerformVolumeMaintenanceTasks -EngineCredential $svcAcc\nThe same as the last example except MyDomain\\SvcSqlServer is now a Managed Service Account (MSA).\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003e$config = @{\n\u003e\u003e AGTSVCSTARTUPTYPE = \"Manual\"\r\n\u003e\u003e BROWSERSVCSTARTUPTYPE = \"Manual\"\r\n\u003e\u003e FILESTREAMLEVEL = 1\r\n\u003e\u003e }\r\nPS C:\\\u003e Install-DbaInstance -SqlInstance localhost\\v2017:1337 -Version 2017 -SqlCollation Latin1_General_CI_AS -Configuration $config\nRun the installation locally with default settings overriding the value of specific configuration items.\r\nInstance name will be defined as \u0027v2017\u0027; TCP port will be changed to 1337 after installation.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003e$svcAcc = Get-Credential MyDomain\\SvcSqlServer\nPS C:\\\u003e Install-DbaInstance -Version 2022 -Feature Engine,AnalysisServices -AdminAccount \"AD\\MSSQLAdmins\" -ASAdminAccount \"AD\\SSASAdmins\" -EngineCredential $svcAcc -ASCredential $svcAcc\nInstall SQL Server 2022 with Database Engine and Analysis Services features.\r\nGrants sysadmin rights to AD\\MSSQLAdmins on the Database Engine and administrator rights to AD\\SSASAdmins on Analysis Services.\r\nUses MyDomain\\SvcSqlServer as the service account for both services.", "Description": "Orchestrates unattended SQL Server installations by generating configuration files and executing setup.exe remotely or locally. Automates the tedious process of creating proper configuration.ini files, handling service accounts, and managing installation prerequisites like pending reboots and authentication protocols.\n\nThe function dynamically builds installation configurations based on your parameters, automatically configures optimal settings like tempdb file counts based on CPU cores (SQL 2016+), and handles authentication scenarios including CredSSP for network installations. It can install multiple instances in parallel and manages the complete installation lifecycle from prerequisite checks to post-installation TCP port configuration.\n\nKey automation features include:\n* Generates secure SA passwords for mixed authentication mode installations\n* Automatically grants sysadmin rights to your account or specified administrators\n* Configures tempdb file counts based on server CPU cores for optimal performance\n* Handles service account credentials using native PowerShell credential objects\n* Manages installation media location detection across network and local paths\n* Performs prerequisite validation including pending reboot detection\n* Supports parallel installation across multiple servers with throttling controls\n* Configures TCP port settings post-installation when specified\n\nAdvanced configuration capabilities:\n* Import existing Configuration.ini files or build configurations from scratch\n* Override any SQL Server setup parameter using the -Configuration hashtable\n* Support for specialized installations like failover cluster instances\n* Enable instant file initialization (perform volume maintenance tasks) automatically\n* Slipstream updates during installation using -UpdateSourcePath\n* Install specific feature combinations using templates (Default, All) or individual components\n\nAuthentication and credential management:\n* Automatically configures CredSSP authentication for network-based installations when needed\n* Supports various authentication protocols (Kerberos, NTLM, Basic) with fallback options\n* Handles domain service accounts, managed service accounts (MSAs), and local accounts\n* Manages distinct service credentials for Database Engine, SQL Agent, Analysis Services, Integration Services, and other components\n\nInstallation media requirements:\n* Requires extracted SQL Server installation media accessible to target servers\n* Supports both local and network-based installation media repositories\n* Automatically locates appropriate setup.exe files based on specified SQL Server version\n* Falls back to Evaluation edition if no Product ID is provided in configuration\n\nRemote execution considerations:\n* Requires elevated privileges on target computers for SQL Server installation\n* Automatically handles CredSSP configuration when installing from network shares\n* Supports custom authentication protocols and credential delegation scenarios\n* Can optionally restart target computers automatically when required by installation prerequisites\n\nNote that the downloaded installation media must be extracted and available to the server where the installation runs.\nNOTE: If no ProductID (PID) is found in the configuration files/parameters, Evaluation version is going to be installed.\n\nWhen using CredSSP authentication, this function will try to configure CredSSP authentication for PowerShell Remoting sessions.\nIf this is not desired (e.g.: CredSSP authentication is managed externally, or is already configured appropriately,)\nit can be disabled by setting the dbatools configuration option \u0027commands.initialize-credssp.bypass\u0027 value to $true.\nTo be able to configure CredSSP, the command needs to be run in an elevated PowerShell session.", "Links": "https://dbatools.io/Install-DbaInstance", "Synopsis": "Automates SQL Server instance installation across local and remote computers with customizable configuration.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target computer and, optionally, a new instance name and a port number.\r\nUse one of the following generic formats:\r\nServer1\r\nServer2\\Instance1\r\nServer1\\Alpha:1533, Server2\\Omega:1566\r\n\"ServerName\\NewInstanceName,1534\"\nYou can also define instance name and port using -InstanceName and -Port parameters.", "ComputerName", false, "false", "$env:COMPUTERNAME", "" ], [ "Version", "Specifies the SQL Server version to install using the year-based identifier.\r\nValid values are 2008, 2008R2, 2012, 2014, 2016, 2017, 2019, 2022, and 2025.\r\nThis parameter determines which setup.exe file to locate in the installation media and configures version-specific features like tempdb file optimization (SQL 2016+).", "", true, "false", "", "2008,2008R2,2012,2014,2016,2017,2019,2022,2025" ], [ "InstanceName", "Specifies the name for the new SQL Server instance, overriding any instance name in the SqlInstance parameter.\r\nUse \u0027MSSQLSERVER\u0027 for the default instance or a custom name for named instances.\r\nNamed instances enable multiple SQL Server installations on the same server and affect service names, registry keys, and connection strings.", "", false, "false", "", "" ], [ "SaCredential", "Specifies the password for the sa account when AuthenticationMode is set to Mixed.\r\nIf not provided with Mixed mode, a random 128-character password is automatically generated and returned in the output.\r\nOnly required when you want to set a specific sa password instead of using the auto-generated one.", "", false, "false", "", "" ], [ "Credential", "Windows Credential with permission to log on to the remote server.\r\nMust be specified for any remote connection if SQL Server installation media is located on a network folder.\nAuthentication will default to CredSSP if -Credential is used.\r\nFor CredSSP see also additional information in DESCRIPTION.", "", false, "false", "", "" ], [ "Authentication", "Specifies the PowerShell remoting authentication protocol for connecting to remote servers during installation.\r\nDefaults to CredSSP when -Credential is provided to handle network share access and avoid double-hop authentication issues.\r\nUse \u0027Kerberos\u0027 in domain environments where CredSSP is restricted, or \u0027Basic\u0027 for workgroup scenarios.\r\nWhen installing from network shares, CredSSP is typically required to pass credentials through to the file server.", "", false, "false", "@(\u0027Credssp\u0027, \u0027Default\u0027)[$null -eq $Credential]", "Default,Basic,Negotiate,NegotiateWithImplicitCredential,Credssp,Digest,Kerberos" ], [ "ConfigurationFile", "Path to an existing SQL Server Configuration.ini file to use for the installation.\r\nUse this when you have a pre-configured setup file from a previous installation or when you need specific settings not covered by the function parameters.\r\nThe function will read and apply all settings from this file, overriding any conflicting parameters.", "FilePath", false, "true (ByValue)", "", "" ], [ "Configuration", "A hashtable containing SQL Server setup configuration parameters that override function defaults.\r\nUse this for advanced scenarios like setting custom startup types, enabling specific features, or configuring failover cluster instances.\r\nEach key-value pair becomes a parameter in the Configuration.ini file, allowing full control over the installation process.\r\nWhen ACTION is specified, only minimal defaults are set, requiring you to provide all necessary configuration items for that specific installation type.", "", false, "false", "", "" ], [ "Path", "Specifies the directory containing extracted SQL Server installation media, which will be scanned recursively for the appropriate setup.exe.\r\nCan be a local path or network share accessible from target servers during remote installations.\r\nThe path must contain the extracted ISO contents or downloaded installer files, not the ISO file itself.", "", false, "false", "(Get-DbatoolsConfigValue -Name \u0027Path.SQLServerSetup\u0027)", "" ], [ "Feature", "Specifies which SQL Server components to install, either as individual features or using predefined templates.\r\n\u0027Default\u0027 installs Engine, Replication, FullText, and Tools for typical database server setups.\r\n\u0027All\u0027 installs every available feature for the specified version.\r\nChoose specific features like \u0027Engine\u0027, \u0027AnalysisServices\u0027, \u0027ReportingServices\u0027, or \u0027IntegrationServices\u0027 for targeted installations based on your requirements.", "", false, "false", "Default", "Default,All,Engine,Tools,Replication,FullText,DataQuality,PolyBase,MachineLearning,AnalysisServices,ReportingServices,ReportingForSharepoint,SharepointAddin,IntegrationServices,MasterDataServices,PythonPackages,RPackages,BackwardsCompatibility,Connectivity,ReplayController,ReplayClient,SDK,BIDS,SSMS" ], [ "AuthenticationMode", "Specifies the SQL Server authentication mode: Windows (Windows Authentication only) or Mixed (Windows and SQL Authentication).\r\nWindows mode is more secure and recommended for domain environments, while Mixed mode is required for applications that need SQL logins.\r\nWhen using Mixed mode, ensure you provide a strong SaCredential or allow the function to generate a secure random password.", "", false, "false", "Windows", "Windows,Mixed" ], [ "InstancePath", "Specifies the root directory where SQL Server instance files will be installed, including program files, system databases, and logs.\r\nDefaults to the standard program files location unless you need to install on a different drive for capacity or performance reasons.\r\nThis path becomes the base for all instance-specific directories unless individual paths are specified.", "", false, "false", "", "" ], [ "DataPath", "Specifies the default directory for user database data files (.mdf and .ndf).\r\nUsed as the default location when creating new databases if no explicit path is provided in CREATE DATABASE statements.\r\nConsider placing this on high-performance storage separate from logs for optimal I/O performance.", "", false, "false", "", "" ], [ "LogPath", "Specifies the default directory for user database transaction log files (.ldf).\r\nUsed as the default location for transaction logs when creating new databases.\r\nBest practice is to place logs on separate storage from data files to optimize write performance and enable better backup strategies.", "", false, "false", "", "" ], [ "TempPath", "Specifies the directory for tempdb database files, which handle temporary objects and internal SQL Server operations.\r\nConsider placing tempdb on fast storage (SSD) separate from user databases since it\u0027s heavily used for sorts, joins, and temporary tables.\r\nFor SQL 2016+, the function automatically configures multiple tempdb data files based on CPU core count.", "", false, "false", "", "" ], [ "BackupPath", "Specifies the default directory for database backup files when no explicit path is provided in BACKUP commands.\r\nThis location should have sufficient space for your backup retention strategy and be accessible to your backup software.\r\nConsider network accessibility if you plan to backup to shared storage or use backup software that requires UNC paths.", "", false, "false", "", "" ], [ "UpdateSourcePath", "Specifies the directory containing SQL Server updates (service packs, cumulative updates) to apply during installation.\r\nEnables slipstream installation to avoid separate patching steps after the base installation completes.\r\nThe path should contain the update executable files compatible with the SQL Server version being installed.", "", false, "false", "", "" ], [ "AdminAccount", "Specifies one or more Windows accounts to grant sysadmin privileges on the new SQL Server instance.\r\nDefaults to the current user or the account specified in the Credential parameter.\r\nUse domain\\\\username format for domain accounts or computername\\\\username for local accounts.", "", false, "false", "", "" ], [ "ASAdminAccount", "Specifies one or more Windows accounts to grant administrator privileges on Analysis Services.\r\nRequired when installing Analysis Services feature. At least one administrator account must be specified.\r\nUse domain\\\\username format for domain accounts or computername\\\\username for local accounts.", "", false, "false", "", "" ], [ "Port", "Specifies the TCP port number for SQL Server after installation, overriding the default port 1433.\r\nThe function configures the port post-installation since SQL Server setup doesn\u0027t directly support custom ports.\r\nUse non-standard ports for security through obscurity or when running multiple instances that need distinct ports.", "", false, "false", "0", "" ], [ "Throttle", "Specifies the maximum number of concurrent SQL Server installations when targeting multiple servers.\r\nControls resource usage and network bandwidth by limiting parallel operations.\r\nConsider your network capacity, installation media server performance, and available system resources when adjusting from the default of 50.", "", false, "false", "50", "" ], [ "ProductID", "Specifies the product license key (PID) to install a licensed edition of SQL Server instead of Evaluation edition.\r\nRequired only when the installation media doesn\u0027t include an embedded license key.\r\nWithout a valid ProductID, the installation defaults to a time-limited Evaluation edition that expires after 180 days.", "PID", false, "false", "", "" ], [ "AsCollation", "Specifies the collation for Analysis Services, determining sort order and character comparison rules for SSAS databases.\r\nDefaults to Latin1_General_CI_AS if not specified.\r\nChoose a collation that matches your data locale and case sensitivity requirements for dimensional and tabular models.", "", false, "false", "", "" ], [ "SqlCollation", "Specifies the server-level collation for the Database Engine, affecting sort order, case sensitivity, and accent sensitivity for all databases.\r\nDefaults to the Windows locale setting if not specified.\r\nChoose carefully as changing server collation after installation requires rebuilding system databases and can affect application compatibility.", "", false, "false", "", "" ], [ "EngineCredential", "Specifies the Windows account to run the SQL Server Database Engine service.\r\nUse domain service accounts for network access, Managed Service Accounts (MSAs) for automated password management, or local accounts for standalone servers.\r\nThe account needs specific Windows privileges like \u0027Log on as a service\u0027 and permissions to the installation directories.", "", false, "false", "", "" ], [ "AgentCredential", "Specifies the Windows account to run the SQL Server Agent service, which manages scheduled jobs, alerts, and replication.\r\nTypically uses the same account as the Database Engine for simplicity, but can be separate for security isolation.\r\nRequires permissions to execute job steps, access network resources for backup jobs, and interact with other SQL Server instances for replication.", "", false, "false", "", "" ], [ "ASCredential", "Specifies the Windows account to run the Analysis Services (SSAS) service for OLAP cubes and tabular models.\r\nThe account needs permissions to data sources, file system access for processing, and network connectivity for distributed queries.\r\nConsider using a dedicated service account when SSAS requires different security contexts than the Database Engine.", "", false, "false", "", "" ], [ "ISCredential", "Specifies the Windows account to run the Integration Services (SSIS) service for ETL package execution and management.\r\nThe account needs permissions to source and destination systems, file shares for package storage, and SQL Server databases for logging and configuration.\r\nUse a service account with broad permissions since SSIS packages often access multiple systems and data sources.", "", false, "false", "", "" ], [ "RSCredential", "Specifies the Windows account to run the Reporting Services (SSRS) service for report generation and delivery.\r\nThe account needs permissions to the report server database, data sources used in reports, and network resources for email delivery.\r\nConsider network connectivity requirements when reports access remote data sources or when using email subscriptions.", "", false, "false", "", "" ], [ "FTCredential", "Specifies the Windows account to run the Full-Text Filter Daemon service for indexing and searching text content in databases.\r\nThe account needs permissions to database files and temporary directories used during full-text indexing operations.\r\nUsually runs under a low-privilege account since it only processes text extraction and indexing without requiring broad system access.", "", false, "false", "", "" ], [ "PBEngineCredential", "Specifies the Windows account to run the PolyBase Engine service for distributed queries against Hadoop, Azure Blob Storage, and other external data sources.\r\nThe account needs network access to external systems and permissions to temporary directories for data processing.\r\nRequired when installing PolyBase features for big data integration and external table functionality.", "", false, "false", "", "" ], [ "SaveConfiguration", "Specifies a path to save the generated Configuration.ini file for future reference or reuse.\r\nWithout this parameter, the configuration file is created in a temporary location and not preserved after installation.\r\nUseful for documenting installation settings, troubleshooting, or replicating installations across multiple servers.", "", false, "false", "", "" ], [ "PerformVolumeMaintenanceTasks", "Grants the SQL Server service account \u0027Perform volume maintenance tasks\u0027 privilege to enable instant file initialization.\r\nAllows SQL Server to skip zero-initialization of data files, significantly reducing the time for database creation, restore operations, and auto-growth events.\r\nOnly affects data files; transaction log files are always zero-initialized for transaction integrity.", "InstantFileInitialization,IFI", false, "false", "False", "" ], [ "Restart", "Automatically restarts target computers when required by Windows updates, pending file operations, or installation prerequisites.\r\nUse this during maintenance windows when automatic restarts are acceptable.\r\nWithout this parameter, installations will fail if pending restarts are detected, requiring manual intervention.", "", false, "false", "False", "" ], [ "NoPendingRenameCheck", "Skips the check for pending file rename operations when validating reboot requirements.\r\nUse this when you know pending renames won\u0027t affect the SQL Server installation or when working with systems that show false positives for pending renames.\r\nGenerally safer to allow the default validation unless you have specific reasons to bypass this safety check.", "", false, "false", "(Get-DbatoolsConfigValue -Name \u0027OS.PendingRename\u0027 -Fallback $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", "OlaHallengren" ], "CommandName": "Install-DbaMaintenanceSolution", "Name": "Install-DbaMaintenanceSolution", "Author": "Viorel Ciucu, cviorel.com", "Syntax": "Install-DbaMaintenanceSolution [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString\u003e] [[-BackupLocation] \u003cString\u003e] [[-CleanupTime] \u003cInt32\u003e] [[-OutputFileDirectory] \u003cString\u003e] [-ReplaceExisting] [-LogToTable] [[-Solution] \u003cString[]\u003e] [-InstallJobs] [[-AutoScheduleJobs] \u003cString[]\u003e] [[-StartTime] \u003cString\u003e] [[-LocalFile] \u003cString\u003e] [-Force] [-InstallParallel] [-ChangeBackupType] [-Compress] [-CopyOnly] [-Verify] [-CheckSum] [[-ModificationLevel] \u003cInt32\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance where the maintenance solution was installed. Each object contains installation result information.\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- Results: Status of the installation (\"Success\" or \"Failed\")\nOnly returns output when installation actually executes (not during WhatIf). When using -WhatIf, no output is generated.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInstall-DbaMaintenanceSolution -SqlInstance RES14224 -Database DBA -InstallJobs -CleanupTime 72\nInstalls Ola Hallengren\u0027s Solution objects on RES14224 in the DBA database.\r\nBackups will default to the default Backup Directory.\r\nIf the Maintenance Solution already exists, the script will be halted.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInstall-DbaMaintenanceSolution -SqlInstance RES14224 -Database DBA -InstallJobs -BackupLocation \"Z:\\SQLBackup\" -CleanupTime 72\nThis will create the Ola Hallengren\u0027s Solution objects. Existing objects are not affected in any way.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$params = @{\n\u003e\u003e SqlInstance = \u0027MyServer\u0027\r\n\u003e\u003e Database = \u0027maintenance\u0027\r\n\u003e\u003e ReplaceExisting = $true\r\n\u003e\u003e InstallJobs = $true\r\n\u003e\u003e LogToTable = $true\r\n\u003e\u003e BackupLocation = \u0027C:\\Data\\Backup\u0027\r\n\u003e\u003e CleanupTime = 65\r\n\u003e\u003e Verbose = $true\r\n\u003e\u003e }\r\n\u003e\u003e Install-DbaMaintenanceSolution @params\nInstalls Maintenance Solution to myserver in database. Adds Agent Jobs, and if any currently exist, they\u0027ll be replaced.\nSince the `LogToTable` switch is enabled, the CommandLog table will be dropped and recreated also.\nIf the tables relating to `InstallParallel` are present, they will not be dropped.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$params = @{\n\u003e\u003e SqlInstance = \u0027RES14224\u0027\r\n\u003e\u003e Database = \u0027DBA\u0027\r\n\u003e\u003e InstallJobs = $true\r\n\u003e\u003e BackupLocation = \u0027Z:\\SQLBackup\u0027\r\n\u003e\u003e CleanupTime = 72\r\n\u003e\u003e ReplaceExisting = $true\r\n\u003e\u003e }\r\nPS C:\\\u003e Install-DbaMaintenanceSolution @params\nThis will drop and then recreate the Ola Hallengren\u0027s Solution objects\r\nThe cleanup script will drop and recreate:\r\n- STORED PROCEDURE [dbo].[CommandExecute]\r\n- STORED PROCEDURE [dbo].[DatabaseBackup]\r\n- STORED PROCEDURE [dbo].[DatabaseIntegrityCheck]\r\n- STORED PROCEDURE [dbo].[IndexOptimize]\nThe tables will not be dropped as the `LogToTable` and `InstallParallel` switches are not enabled.\r\n- [dbo].[CommandLog]\r\n- [dbo].[Queue]\r\n- [dbo].[QueueDatabase]\nThe following SQL Agent jobs will be deleted:\r\n- \u0027Output File Cleanup\u0027\r\n- \u0027IndexOptimize - USER_DATABASES\u0027\r\n- \u0027sp_delete_backuphistory\u0027\r\n- \u0027DatabaseBackup - USER_DATABASES - LOG\u0027\r\n- \u0027DatabaseBackup - SYSTEM_DATABASES - FULL\u0027\r\n- \u0027DatabaseBackup - USER_DATABASES - FULL\u0027\r\n- \u0027sp_purge_jobhistory\u0027\r\n- \u0027DatabaseIntegrityCheck - SYSTEM_DATABASES\u0027\r\n- \u0027CommandLog Cleanup\u0027\r\n- \u0027DatabaseIntegrityCheck - USER_DATABASES\u0027\r\n- \u0027DatabaseBackup - USER_DATABASES - DIFF\u0027\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eInstall-DbaMaintenanceSolution -SqlInstance RES14224 -Database DBA -InstallParallel\nThis will create the Queue and QueueDatabase tables for uses when manually changing jobs to use the @DatabasesInParallel = \u0027Y\u0027 flag\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e$params = @{\n\u003e\u003e SqlInstance = \"localhost\"\r\n\u003e\u003e InstallJobs = $true\r\n\u003e\u003e CleanupTime = 720\r\n\u003e\u003e AutoSchedule = \"WeeklyFull\"\r\n\u003e\u003e }\r\n\u003e\u003e Install-DbaMaintenanceSolution @params\nThis will create the Ola Hallengren\u0027s Solution objects and the SQL Agent Jobs.\nWeeklyFull will create weekly full, daily differential and 15 minute log backups of _user_ databases.\n_System_ databases will be backed up daily.\nDatabases will be backed up to the default location for the instance, and backups will be deleted after 720 hours (30 days).\nSee https://github.com/dataplat/dbatools/pull/8911 for details on job schedules.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003e$params = @{\n\u003e\u003e SqlInstance = \"localhost\"\r\n\u003e\u003e InstallJobs = $true\r\n\u003e\u003e CleanupTime = 720\r\n\u003e\u003e AutoScheduleJobs = \"DailyFull\", \"HourlyLog\"\r\n\u003e\u003e BackupLocation = \"\\\\sql\\backups\"\r\n\u003e\u003e StartTime = \"231500\"\r\n\u003e\u003e }\nPS C:\\\u003e Install-DbaMaintenanceSolution @params\nThis will create the Ola Hallengren\u0027s Solution objects and the SQL Agent Jobs.\nThe jobs will be scheduled to run daily full user backups at 11:15pm, no differential backups will be created and hourly log backups will be made.\r\nSystem databases will be backed up at 1:15 am, two hours after the user databases.\nDatabases will be backed up to a fileshare, and the backups will be deleted after 720 hours (30 days).\nSee https://blog.netnerds.net/2023/05/install-dbamaintenancesolution-now-supports-auto-scheduling/ for more information.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003e$params = @{\n\u003e\u003e SqlInstance = \"localhost\"\r\n\u003e\u003e Database = \"DBAMaintenance\"\r\n\u003e\u003e InstallJobs = $true\r\n\u003e\u003e BackupLocation = \"D:\\SQLBackups\"\r\n\u003e\u003e CleanupTime = 168\r\n\u003e\u003e ChangeBackupType = $true\r\n\u003e\u003e Compress = $true\r\n\u003e\u003e Verify = $true\r\n\u003e\u003e CheckSum = $true\r\n\u003e\u003e }\nPS C:\\\u003e Install-DbaMaintenanceSolution @params\nInstalls Ola Hallengren\u0027s Solution with backup jobs that include automatic backup type conversion, compression, verification, and checksum validation.\r\nThe ChangeBackupType parameter ensures differential and log backups automatically become full backups if a full backup is missing.\r\nBackups are compressed, verified after creation, and validated with checksums for maximum data integrity.", "Description": "Deploys Ola Hallengren\u0027s comprehensive maintenance framework including DatabaseBackup, DatabaseIntegrityCheck, IndexOptimize, and CommandExecute stored procedures to automate backup, DBCC checks, and index maintenance tasks. Optionally creates pre-configured SQL Agent jobs with intelligent scheduling for daily, weekly, and log backup routines. Replaces manual maintenance scripting with industry-standard procedures used by thousands of SQL Server environments worldwide.", "Links": "https://dbatools.io/Install-DbaMaintenanceSolution", "Synopsis": "Installs Ola Hallengren\u0027s Maintenance Solution stored procedures and optional SQL Agent jobs for automated database maintenance", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance onto which the Maintenance Solution will be installed.", "", 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 where Ola Hallengren\u0027s maintenance solution objects will be installed. Defaults to master.\r\nConsider using a dedicated DBA or maintenance database instead of master to keep system databases clean and simplify backup strategies.", "", false, "false", "master", "" ], [ "BackupLocation", "Sets the root directory path where backup files will be stored by the maintenance jobs. Defaults to the instance\u0027s default backup location.\r\nSpecify this when you need backups in a specific location for storage policies, network shares, or disk space management.", "", false, "false", "", "" ], [ "CleanupTime", "Defines retention period in hours before backup files are automatically deleted by cleanup jobs.\r\nOnly used when InstallJobs is specified. Common values: 168 hours (1 week), 720 hours (30 days), or 2160 hours (90 days).", "", false, "false", "0", "" ], [ "OutputFileDirectory", "Sets the directory path where SQL Agent jobs will write their output log files during maintenance operations.\r\nUse this to centralize job output logs for monitoring and troubleshooting maintenance activities.", "", false, "false", "", "" ], [ "ReplaceExisting", "Forces replacement of existing Ola Hallengren objects including stored procedures and SQL Agent jobs.\r\nUse this when upgrading to newer versions of the maintenance solution or when previous installations need to be refreshed.\r\nCommandLog and Queue tables are only dropped when LogToTable or InstallParallel switches are also specified.", "", false, "false", "False", "" ], [ "LogToTable", "Enables command logging to the CommandLog table for tracking maintenance operation history and performance.\r\nEssential for monitoring backup completion times, index maintenance duration, and troubleshooting failed operations.", "", false, "false", "False", "" ], [ "Solution", "Determines which maintenance components to install: All, Backup, IntegrityCheck, or IndexOptimize.\r\nUse specific components when you only need certain maintenance functions or want to install different parts on different servers.", "", false, "false", "All", "All,Backup,IntegrityCheck,IndexOptimize" ], [ "InstallJobs", "Creates pre-configured SQL Agent jobs for automated execution of backup, integrity check, and index maintenance tasks.\r\nWithout this switch, only the stored procedures are installed and must be scheduled manually or called from custom jobs.", "", false, "false", "False", "" ], [ "AutoScheduleJobs", "Automatically creates optimized job schedules for backup operations. Valid values: WeeklyFull, DailyFull, NoDiff, FifteenMinuteLog, HourlyLog.\r\nWeeklyFull creates weekly full backups, daily differentials, and 15-minute log backups. DailyFull skips differentials. Use HourlyLog for less frequent transaction log backups.\r\nSystem databases are always backed up daily regardless of user database schedule. Automatically resolves schedule conflicts by adjusting start times.", "", false, "false", "", "WeeklyFull,DailyFull,NoDiff,FifteenMinuteLog,HourlyLog" ], [ "StartTime", "Sets the preferred start time for automatically scheduled jobs in HHMMSS format. Defaults to 011500 (1:15 AM).\r\nThe system automatically adjusts this time if conflicts exist with other scheduled jobs. Choose off-peak hours to minimize impact on production workloads.", "", false, "false", "011500", "" ], [ "LocalFile", "Specifies path to a local zip file containing Ola Hallengren\u0027s maintenance solution instead of downloading from GitHub.\r\nUse this in environments without internet access or when you need to install a specific version for consistency across multiple servers.", "", false, "false", "", "" ], [ "Force", "Forces fresh download of the maintenance solution from GitHub, bypassing any locally cached version.\r\nUse this to ensure you\u0027re installing the latest version when the cache might contain an older release.", "", false, "false", "False", "" ], [ "InstallParallel", "Creates Queue and QueueDatabase tables required for parallel execution of maintenance operations across multiple databases.\r\nEnable this when you have many databases and want to run maintenance tasks concurrently to reduce overall completion time.", "", false, "false", "False", "" ], [ "ChangeBackupType", "Enables automatic backup type conversion when a full backup is missing. When enabled, differential backups automatically become full backups,\r\nand log backups become full or differential backups as appropriate. Only applies when InstallJobs is specified.\r\nThis ensures backup chains remain valid even if scheduled full backups fail or are missed.", "", false, "false", "False", "" ], [ "Compress", "Controls backup compression for all backup operations. When not specified, uses the SQL Server instance\u0027s default compression setting.\r\nSet to enable compression (recommended for reducing backup size and network transfer time) or disable for compatibility with older restore targets.\r\nOnly applies when InstallJobs is specified.", "", false, "false", "False", "" ], [ "CopyOnly", "Creates copy-only backups that do not affect the normal backup sequence. Copy-only backups do not break the differential backup chain\r\nand are ideal for ad-hoc backups, backup verification, or sending backups to external systems without impacting regular backup schedules.\r\nOnly applies when InstallJobs is specified.", "", false, "false", "False", "" ], [ "Verify", "Verifies backup integrity immediately after creation by performing a RESTORE VERIFYONLY operation.\r\nDefaults to enabled (Y) if not specified. Verification adds time to backup operations but ensures backups are restorable.\r\nOnly applies when InstallJobs is specified.", "", false, "false", "False", "" ], [ "CheckSum", "Enables checksum validation during backup operations to detect data corruption.\r\nDefaults to enabled (Y) if not specified. Checksums provide additional data integrity verification with minimal performance impact.\r\nOnly applies when InstallJobs is specified.", "", false, "false", "False", "" ], [ "ModificationLevel", "Specifies minimum modification percentage required before ChangeBackupType converts a differential or log backup to full backup.\r\nValid range: 0-100. Use this with ChangeBackupType to control when backup type changes occur based on data modification levels.\r\nOnly applies when InstallJobs is specified.", "", 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", "" ], [ "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": [ "Community", "DbaMultiTool" ], "CommandName": "Install-DbaMultiTool", "Name": "Install-DbaMultiTool", "Author": "John McCall (@lowlydba), lowlydba.com", "Syntax": "Install-DbaMultiTool [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Branch] \u003cString\u003e] [[-Database] \u003cObject\u003e] [[-LocalFile] \u003cString\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per stored procedure installed, providing installation details and 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 (computer\\instance)\r\n- Database: The target database where the stored procedures were installed\r\n- Name: The name of the installed stored procedure (sp_helpme, sp_doc, sp_sizeoptimiser, sp_estindex, or sp_help_revlogin)\r\n- Status: The installation status - \"Installed\" for newly installed procedures, \"Updated\" for procedures that were updated, or \"Error\" if the installation failed", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInstall-DbaMultiTool -SqlInstance server1 -Database main\nLogs into server1 with Windows authentication and then installs the DBA MultiTool in the main database.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInstall-DbaMultiTool -SqlInstance server1\\instance1 -Database DBA\nLogs into server1\\instance1 with Windows authentication and then installs the DBA MultiTool in the DBA database.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eInstall-DbaMultiTool -SqlInstance server1\\instance1 -Database main -SqlCredential $cred\nLogs into server1\\instance1 with SQL authentication and then installs the DBA MultiTool in the main database.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eInstall-DbaMultiTool -SqlInstance sql2016\\standardrtm, sql2016\\sqlexpress, sql2014\nLogs into sql2016\\standardrtm, sql2016\\sqlexpress and sql2014 with Windows authentication and then installs the DBA MultiTool in the main database.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$servers = \"sql2016\\standardrtm\", \"sql2016\\sqlexpress\", \"sql2014\"\nPS C:\\\u003e $servers | Install-DbaMultiTool\nLogs into sql2016\\standardrtm, sql2016\\sqlexpress and sql2014 with Windows authentication and then installs the DBA MultiTool in the main database.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eInstall-DbaMultiTool -SqlInstance sql2016 -Branch development\nInstalls the development branch version of the DBA MultiTool in the main database on sql2016 instance.", "Description": "Downloads and installs the DBA MultiTool collection of T-SQL stored procedures into a specified database. This toolkit provides five key utilities that help DBAs with common documentation and optimization tasks that would otherwise require manual T-SQL scripting.\n\nThe installed procedures include:\n• sp_helpme - Enhanced version of sp_help that provides detailed object information\n• sp_doc - Generates comprehensive database documentation\n• sp_sizeoptimiser - Analyzes and recommends optimal database file sizing\n• sp_estindex - Estimates potential storage savings from index compression\n• sp_help_revlogin - Creates scripts to recreate logins with their original SIDs and passwords\n\nThese procedures are particularly valuable for database migrations, compliance reporting, capacity planning, and general administrative documentation. The function automatically handles downloading the latest version from GitHub and can install across multiple instances simultaneously.\n\nDBA MultiTool links:\nhttps://dba-multitool.org\nhttps://github.com/LowlyDBA/dba-multitool/", "Links": "https://dbatools.io/Install-DbaMultiTool", "Synopsis": "Installs five essential T-SQL stored procedures for database documentation, index optimization, and administrative tasks.", "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", "", "" ], [ "Branch", "Specifies which branch of the DBA MultiTool repository to download and install. Defaults to \u0027main\u0027 for stable releases.\r\nUse \u0027development\u0027 only when you need to test upcoming features or bug fixes before they are officially released.\r\nThe development branch may contain untested code and should not be used in production environments.", "", false, "false", "main", "main,development" ], [ "Database", "Specifies the target database where the five DBA MultiTool stored procedures will be installed. Defaults to \u0027master\u0027 database if not specified.\r\nChoose a dedicated DBA or utility database to keep administrative procedures organized and separate from application databases.", "", false, "false", "master", "" ], [ "LocalFile", "Specifies the path to a local zip file containing the DBA MultiTool scripts instead of downloading from GitHub.\r\nUse this when installing in environments without internet access, when you need to install a specific version, or when your organization requires using pre-approved software packages.\r\nThe file must be the official zip distribution from the DBA MultiTool maintainers.", "", false, "false", "", "" ], [ "Force", "Forces a fresh download of the DBA MultiTool from GitHub, ignoring any locally cached version.\r\nUse this when you need to ensure you have the absolute latest version or when troubleshooting installation issues with cached files.\r\nWithout this switch, the function will use the cached version if it exists to improve performance and reduce network usage.", "", 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 to confirm actions.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Deployment", "Install" ], "CommandName": "Install-DbaSqlPackage", "Name": "Install-DbaSqlPackage", "Author": "Chrissy LeMaire and Claude", "Syntax": "Install-DbaSqlPackage [[-Path] \u003cString\u003e] [[-Scope] \u003cString\u003e] [[-Type] \u003cString\u003e] [[-LocalFile] \u003cString\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns installation details when SqlPackage is successfully installed.\nIf SqlPackage is already installed and -Force is not specified, no output is returned. If installation fails, an error is raised instead of returning an object.\nProperties:\r\n- Name: The executable name - \"sqlpackage\" on Unix platforms, \"SqlPackage.exe\" on Windows\r\n- Path: The full file path to the installed SqlPackage executable\r\n- Installed: Boolean value of $true indicating successful installation", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInstall-DbaSqlPackage\nDownloads SqlPackage ZIP and extracts it to the dbatools directory for the current user\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInstall-DbaSqlPackage -Scope AllUsers -Type Msi\nDownloads and installs SqlPackage MSI for all users (requires administrative privileges)\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eInstall-DbaSqlPackage -Path C:\\SqlPackage\nDownloads SqlPackage ZIP and extracts it to C:\\SqlPackage\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eInstall-DbaSqlPackage -LocalFile C:\\temp\\sqlpackage.zip\nInstalls SqlPackage from the local ZIP file.", "Description": "Downloads and installs Microsoft SqlPackage utility, which is essential for database deployment automation and DACPAC operations. This prerequisite tool enables you to use Import-DbaDacpac, Export-DbaDacpac, Publish-DbaDacpac and Get-DbaDacpac for automated database schema deployments and CI/CD pipelines.\n\nSqlPackage is Microsoft\u0027s command-line utility for deploying database schema changes, extracting database schemas to DACPAC files, and publishing changes across environments. DBAs use this for automated deployments, maintaining consistent database schemas between development and production, and implementing database DevOps workflows.\n\nCross-platform support:\n- Windows: Supports both ZIP (portable) and MSI installation methods\n- Linux/macOS: Supports ZIP installation method only\n\nBy default, SqlPackage is installed as a portable ZIP file to the dbatools directory for CurrentUser scope, making it immediately available for database deployment tasks without requiring system-wide installation.\nFor AllUsers (LocalMachine) scope on Windows, you can use the MSI installer which requires administrative privileges and provides system-wide access.\n\nWrites to dbatools data directory by default for CurrentUser scope.", "Links": "https://dbatools.io/Install-DbaSqlPackage", "Synopsis": "Installs Microsoft SqlPackage utility required for database deployment and DACPAC operations", "Availability": "Windows, Linux, macOS", "Params": [ [ "Path", "Specifies the custom directory path where SqlPackage will be extracted or installed.\r\nUse this when you need SqlPackage in a specific location for CI/CD pipelines, shared tools directories, or portable deployments.\r\nIf not specified, defaults to the dbatools data directory for CurrentUser scope or system location for AllUsers scope.", "", false, "false", "", "" ], [ "Scope", "Controls whether SqlPackage is installed for the current user only or system-wide for all users.\r\nUse CurrentUser (default) for personal use or when you lack admin rights. Use AllUsers for shared servers where multiple DBAs need access to SqlPackage.\r\nAllUsers requires administrative privileges on Windows and installs to Program Files via MSI or /usr/local/sqlpackage on Unix systems.", "", false, "false", "CurrentUser", "CurrentUser,AllUsers" ], [ "Type", "Determines the installation method for SqlPackage deployment.\r\nUse Zip (default) for portable installations that don\u0027t require admin rights and work on all platforms. Use Msi for Windows system-wide installations with proper registry integration.\r\nMSI installations require AllUsers scope and administrative privileges but provide better integration with Windows software management.", "", false, "false", "Zip", "Zip,Msi" ], [ "LocalFile", "Specifies the path to a pre-downloaded SqlPackage installation file (MSI or ZIP format).\r\nUse this in air-gapped environments or when you\u0027ve already downloaded SqlPackage for offline installation.\r\nUseful for corporate environments where direct internet downloads are restricted or when installing the same version across multiple servers.", "", false, "false", "", "" ], [ "Force", "Forces re-download and reinstallation of SqlPackage even if it already exists in the target location.\r\nUse this when you need to update to the latest version, fix a corrupted installation, or ensure you have a clean SqlPackage deployment.\r\nWithout this switch, the function will skip installation if SqlPackage is already detected in the destination path.", "", 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": [ "Community", "SqlWatch" ], "CommandName": "Install-DbaSqlWatch", "Name": "Install-DbaSqlWatch", "Author": "Ken K (github.com/koglerk)", "Syntax": "Install-DbaSqlWatch [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString\u003e] [[-LocalFile] \u003cString\u003e] [-PreRelease] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance where SqlWatch is installed or updated.\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 in computer\\instance format\r\n- Database: The target database where SqlWatch was installed or updated\r\n- Status: The deployment status extracted from DACPAC publication results\r\n- DashboardPath: The full local file system path to the SqlWatch Dashboard directory for web UI access", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInstall-DbaSqlWatch -SqlInstance server1\nLogs into server1 with Windows authentication and then installs SqlWatch in the SQLWATCH database.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInstall-DbaSqlWatch -SqlInstance server1\\instance1 -Database DBA\nLogs into server1\\instance1 with Windows authentication and then installs SqlWatch in the DBA database.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eInstall-DbaSqlWatch -SqlInstance server1\\instance1 -Database DBA -SqlCredential $cred\nLogs into server1\\instance1 with SQL authentication and then installs SqlWatch in the DBA database.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eInstall-DbaSqlWatch -SqlInstance sql2016\\standardrtm, sql2016\\sqlexpress, sql2014\nLogs into sql2016\\standardrtm, sql2016\\sqlexpress and sql2014 with Windows authentication and then installs SqlWatch in the SQLWATCH database.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$servers = \"sql2016\\standardrtm\", \"sql2016\\sqlexpress\", \"sql2014\"\n$servers | Install-DbaSqlWatch\nLogs into sql2016\\standardrtm, sql2016\\sqlexpress and sql2014 with Windows authentication and then installs SqlWatch in the SQLWATCH database.", "Description": "Deploys SqlWatch, an open-source SQL Server monitoring and performance collection tool, to one or more SQL Server instances. SqlWatch continuously gathers performance metrics, wait statistics, and system information into dedicated tables for historical analysis and alerting.\n\nThis function automatically downloads the latest SqlWatch release from GitHub (or uses a local file), then deploys it to the specified database using DACPAC technology. SqlWatch creates its own database objects to collect and store performance data, making it useful for DBAs who need ongoing monitoring without third-party agents or expensive monitoring solutions.\n\nThe installed SqlWatch system runs autonomously via SQL Agent jobs, collecting data at regular intervals. It includes a web dashboard for viewing metrics and can be customized for specific monitoring requirements.\n\nMore information: https://sqlwatch.io/", "Links": "https://dbatools.io/Install-DbaSqlWatch", "Synopsis": "Installs or updates SqlWatch monitoring solution on SQL Server instances.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "SQL Server name or SMO object representing the SQL Server to connect to.", "", 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 target database where SqlWatch objects will be created and performance data will be stored. Defaults to SQLWATCH.\r\nUse this when you want to install SqlWatch into an existing database alongside other monitoring tools or when following specific naming conventions.", "", false, "false", "SQLWATCH", "" ], [ "LocalFile", "Specifies the path to a local SqlWatch zip file to install instead of downloading from GitHub. Must be the official zip file distributed by SqlWatch maintainers.\r\nUse this when you have offline environments, want to control the specific version being deployed, or need to install from a pre-approved software repository.", "", false, "false", "", "" ], [ "PreRelease", "Downloads and installs the latest pre-release (beta) version of SqlWatch instead of the stable release branch.\r\nUse this when you need to test new features or bug fixes that haven\u0027t been released yet, but avoid in production environments.", "", false, "false", "False", "" ], [ "Force", "Forces re-download of SqlWatch from GitHub even if a cached copy already exists locally in the dbatools data directory.\r\nUse this when you need to ensure you have the absolute latest version or when troubleshooting installation issues with potentially corrupted cached 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", "" ], [ "WhatIf", "Shows what would happen if the command were to run. No actions are actually performed.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts to confirm actions", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Community", "WhoIsActive" ], "CommandName": "Install-DbaWhoIsActive", "Name": "Install-DbaWhoIsActive", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Install-DbaWhoIsActive [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-LocalFile \u003cString\u003e] [-Database \u003cObject\u003e] [-EnableException] [-Force] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance where sp_WhoIsActive was installed or updated.\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- Database: The database where sp_WhoIsActive was installed\r\n- Name: Always \u0027sp_WhoisActive\u0027, the name of the installed stored procedure\r\n- Version: The version of sp_WhoIsActive that was installed (extracted from the procedure source code)\r\n- Status: String indicating \u0027Installed\u0027 for new installations or \u0027Updated\u0027 if the procedure already existed", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInstall-DbaWhoIsActive -SqlInstance sqlserver2014a -Database master\nDownloads sp_WhoisActive from the internet and installs to sqlserver2014a\u0027s master database. Connects to SQL Server using Windows Authentication.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInstall-DbaWhoIsActive -SqlInstance sqlserver2014a -SqlCredential $cred\nPops up a dialog box asking which database on sqlserver2014a you want to install the procedure into. Connects to SQL Server using SQL Authentication.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eInstall-DbaWhoIsActive -SqlInstance sqlserver2014a -Database master -LocalFile c:\\SQLAdmin\\sp_WhoIsActive.sql\nInstalls sp_WhoisActive to sqlserver2014a\u0027s master database from the local file sp_WhoIsActive.sql.\r\nYou can download this file from https://github.com/amachanic/sp_whoisactive/blob/master/sp_WhoIsActive.sql\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eInstall-DbaWhoIsActive -SqlInstance sqlserver2014a -Database master -LocalFile c:\\SQLAdmin\\sp_whoisactive-12.00.zip\nInstalls sp_WhoisActive to sqlserver2014a\u0027s master database from the local file sp_whoisactive-12.00.zip.\r\nYou can download this file from https://github.com/amachanic/sp_whoisactive/releases\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$instances = Get-DbaRegServer sqlserver\nPS C:\\\u003e Install-DbaWhoIsActive -SqlInstance $instances -Database master\nInstalls sp_WhoisActive to all servers within CMS", "Description": "Installs Adam Machanic\u0027s sp_WhoIsActive stored procedure, the most widely-used tool for monitoring active SQL Server sessions in real-time. This procedure provides detailed information about currently running queries, blocking chains, wait statistics, and resource consumption without the overhead of SQL Server Profiler.\n\nThe function automatically downloads the latest version from GitHub or uses a local file you specify. It handles installation to any database you choose, though master is recommended for server-wide availability. When sp_WhoIsActive already exists, the function performs an update instead.\n\nThis eliminates the manual process of downloading, extracting, and deploying the procedure across multiple SQL Server instances. Essential for DBAs who need to quickly troubleshoot performance issues, identify blocking sessions, or monitor query execution in production environments.\n\nFor more information about sp_WhoIsActive, visit http://whoisactive.com and http://sqlblog.com/blogs/adam_machanic/archive/tags/who+is+active/default.aspx\n\nPlease consider donating to Adam if you find this stored procedure helpful: http://tinyurl.com/WhoIsActiveDonate", "Links": "https://dbatools.io/Install-DbaWhoIsActive", "Synopsis": "Downloads and installs sp_WhoIsActive stored procedure for real-time SQL Server session monitoring", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. 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", "", "" ], [ "LocalFile", "Specifies the path to a local copy of sp_WhoIsActive instead of downloading from GitHub. Accepts either the zip file or the extracted SQL script.\r\nUse this when your SQL Server instances don\u0027t have internet access, when you need to deploy a specific version, or when you have customized the procedure.\r\nIf not specified, the function automatically downloads the latest version from the official GitHub repository.", "", false, "false", "", "" ], [ "Database", "Specifies the database where sp_WhoIsActive will be installed. Defaults to master database if not specified in interactive mode.\r\nInstalling in master makes the procedure available server-wide, while installing in a user database limits access to that database only.\r\nWhen running unattended or in scripts, this parameter is mandatory to avoid interactive prompts.", "", 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", "" ], [ "Force", "Forces a fresh download of sp_WhoIsActive from GitHub, bypassing any locally cached version.\r\nUse this when you need to ensure you have the absolute latest version or when troubleshooting installation issues with cached files.", "", 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": [ "Deployment", "Install", "Patching" ], "CommandName": "Invoke-DbaAdvancedInstall", "Name": "Invoke-DbaAdvancedInstall", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Invoke-DbaAdvancedInstall [[-ComputerName] \u003cString\u003e] [[-InstanceName] \u003cString\u003e] [[-Port] \u003cNullable`1\u003e] [[-InstallationPath] \u003cString\u003e] [[-ConfigurationPath] \u003cString\u003e] [[-ArgumentList] \u003cString[]\u003e] [[-Version] \u003cVersion\u003e] [[-Configuration] \u003cHashtable\u003e] [[-Restart] \u003cBoolean\u003e] [[-PerformVolumeMaintenanceTasks] \u003cBoolean\u003e] [[-SaveConfiguration] \u003cString\u003e] [[-Authentication] \u003cString\u003e] [[-Credential] \u003cPSCredential\u003e] [[-SaCredential] \u003cPSCredential\u003e] [-NoPendingRenameCheck] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object with detailed installation results and status information.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The target computer where SQL Server was installed\r\n- InstanceName: The SQL Server instance name\r\n- Version: The SQL Server version being installed\r\n- Port: The TCP port configured for the instance (nullable int)\r\n- Successful: Boolean indicating if the installation completed successfully\r\n- Restarted: Boolean indicating if the computer was restarted during installation\r\n- Installer: The path to the SQL Server setup.exe file used\r\n- ExitCode: The exit code returned by setup.exe (nullable int, 0 = success, 3010 = reboot required)\r\n- LogFile: The full path to the installation Summary.txt log file\r\n- Notes: Array of messages about installation warnings, errors, or post-installation actions\nAdditional properties available:\r\n- SACredential: The SA credential provided (if mixed-mode authentication was used)\r\n- Configuration: The hashtable of configuration settings used for installation\r\n- ExitMessage: Detailed exit message extracted from the installation summary\r\n- Log: Full contents of the installation Summary.txt file (array of strings)\r\n- ConfigurationFile: Path to the ConfigurationFile.ini used during installation", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaAdvancedUpdate -ComputerName SQL1 -Action $actions\nInvokes update actions on SQL1 after restarting it.", "Description": "Performs the complete SQL Server installation workflow on a target computer, including pre and post-installation restart management. This internal function handles copying configuration files to remote machines, executing setup.exe with specified parameters, configuring TCP ports, enabling volume maintenance tasks, and managing required system restarts. It provides detailed installation logging and error reporting to track the success or failure of each installation attempt.", "Links": "https://dbatools.io/Invoke-DbaAdvancedInstall", "Synopsis": "Executes SQL Server installation on a single computer with automated restart handling.", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the target computer where SQL Server will be installed.\r\nCan be a hostname, FQDN, or IP address for remote installations.", "", false, "false", "", "" ], [ "InstanceName", "Specifies the name for the SQL Server instance being installed.\r\nUse \u0027MSSQLSERVER\u0027 for the default instance or provide a custom name for named instances.\r\nThis parameter is used for post-installation configuration like port changes and service restarts.", "", false, "false", "", "" ], [ "Port", "Sets the TCP port for the SQL Server instance after installation completes.\r\nUse this when you need a specific port for firewall rules or application connectivity requirements.\r\nThe service will be automatically restarted to apply the new port setting.", "", false, "false", "", "" ], [ "InstallationPath", "Specifies the full path to the SQL Server setup.exe file.\r\nThis should point to the setup.exe in your SQL Server installation media or extracted ISO.", "", false, "false", "", "" ], [ "ConfigurationPath", "Specifies the path to the SQL Server configuration file (Configuration.ini) on the local machine.\r\nThis file contains all installation settings and will be copied to the target computer during remote installations.\r\nGenerate this file using SQL Server Installation Center or create it manually with your desired settings.", "", false, "false", "", "" ], [ "ArgumentList", "Provides additional command-line arguments to pass directly to setup.exe.\r\nUse this for installation options not covered by other parameters, such as /IACCEPTSQLSERVERLICENSETERMS.\r\nThese arguments supplement the configuration file settings.", "", false, "false", "", "" ], [ "Version", "Specifies the SQL Server version being installed using the canonical version number.\r\nExamples: 10.50 for SQL Server 2008 R2, 11.0 for SQL Server 2012, 13.0 for SQL Server 2016.\r\nThis helps the function locate installation logs and perform version-specific operations.", "", false, "false", "", "" ], [ "Configuration", "A hashtable with custom configuration items that you want to use during the installation.\r\nOverrides all other parameters.\r\nFor example, to define a custom server collation you can use the following parameter:\r\nPS\u003e Install-DbaInstance -Version 2017 -Configuration @{ SQLCOLLATION = \u0027Latin1_General_BIN\u0027 }\nFull list of parameters can be found here: https://docs.microsoft.com/en-us/sql/database-engine/install-windows/install-sql-server-from-the-command-prompt#Install", "", false, "false", "", "" ], [ "Restart", "Automatically restarts the target computer when required by the SQL Server installation and waits for it to come back online.\r\nEssential for multi-instance installations since most SQL Server components require a restart to complete installation.\r\nWithout this parameter, you must manually restart the computer when installation exit code 3010 is returned.", "", false, "false", "False", "" ], [ "PerformVolumeMaintenanceTasks", "Grants the SQL Server service account the \u0027Perform Volume Maintenance Tasks\u0027 privilege after installation.\r\nThis enables instant file initialization, significantly improving database file creation and growth performance.\r\nRecommended for production environments where large databases are created or restored frequently.", "", false, "false", "False", "" ], [ "SaveConfiguration", "Specifies a path where the installation configuration file will be saved for future reference.\r\nUse this to preserve your installation settings for documentation or to replicate the same configuration on other servers.\r\nThe temporary configuration file is normally deleted after installation completes.", "", false, "false", "", "" ], [ "Authentication", "Specifies the authentication protocol for PowerShell remoting to the target computer.\r\nCredSSP is used by default when credentials are provided to handle network share access during installation.\r\nChange to Kerberos or Negotiate if your environment restricts CredSSP usage.", "", false, "false", "Credssp", "Default,Basic,Negotiate,NegotiateWithImplicitCredential,Credssp,Digest,Kerberos" ], [ "Credential", "Windows Credential with permission to log on to the remote server.\r\nMust be specified for any remote connection if installation media is located on a network folder.", "", false, "false", "", "" ], [ "SaCredential", "Provides the sa account password when installing SQL Server with mixed mode authentication.\r\nPass a PSCredential object with \u0027sa\u0027 as the username and your desired password.\r\nRequired only when your configuration file specifies mixed mode authentication (SECURITYMODE=SQL).", "", false, "false", "", "" ], [ "NoPendingRenameCheck", "Skips the check for pending file rename operations when determining if a reboot is required.\r\nUse this switch if you encounter false positive reboot requirements due to pending renames that don\u0027t affect SQL Server installation.\r\nOnly disable this check if you\u0027re certain no critical system files are waiting to be renamed.", "", 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": [ "Restore", "Backup" ], "CommandName": "Invoke-DbaAdvancedRestore", "Name": "Invoke-DbaAdvancedRestore", "Author": "Stuart Moore (@napalmgram), stuart-moore.com", "Syntax": "Invoke-DbaAdvancedRestore [-BackupHistory] \u003cObject[]\u003e [[-SqlInstance] \u003cDbaInstanceParameter\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [-OutputScriptOnly] [-VerifyOnly] [[-RestoreTime] \u003cDateTime\u003e] [[-StandbyDirectory] \u003cString\u003e] [-NoRecovery] [[-MaxTransferSize] \u003cInt32\u003e] [[-BlockSize] \u003cInt32\u003e] [[-BufferCount] \u003cInt32\u003e] [-Continue] [[-StorageCredential] \u003cString\u003e] [-WithReplace] [-KeepReplication] [-KeepCDC] [[-PageRestore] \u003cObject[]\u003e] [[-ExecuteAs] \u003cString\u003e] [-StopBefore] [[-StopMark] \u003cString\u003e] [[-StopAfterDate] \u003cDateTime\u003e] [-Checksum] [-Restart] [-EnableException] [-WhatIf] [-Confirm] \r\n[\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject (default operation)\nReturns one object per backup file processed in the restore sequence, containing comprehensive restore operation details and status.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance where the restore occurred\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- BackupFile: Comma-separated list of backup file paths processed in this restore operation\r\n- BackupFilesCount: Number of backup files included in the restore operation (int)\r\n- BackupSize: Total size of backup files; dbasize object convertible to Bytes, KB, MB, GB, TB\r\n- CompressedBackupSize: Compressed size of backup files if available in backup metadata\r\n- Database: The name of the database being restored\r\n- Owner: The database owner, typically the login that performed the restore\r\n- DatabaseRestoreTime: Total elapsed time for the complete database restore operation (TimeSpan)\r\n- FileRestoreTime: Elapsed time for the current backup file restore (TimeSpan)\r\n- NoRecovery: Boolean indicating if the database was left in RESTORING state for log restore sequences\r\n- RestoreComplete: Boolean indicating if the restore operation completed successfully\r\n- RestoredFile: Comma-separated list of logical file names restored to the database\r\n- RestoredFilesCount: Number of files restored in the database (int)\r\n- Script: The T-SQL RESTORE script executed or generated (populated when actual T-SQL is run or when OutputScriptOnly is used)\r\n- RestoreDirectory: Directory path(s) where the restored database files are located on the target server\r\n- WithReplace: Boolean indicating if the restore was performed with the REPLACE option to overwrite existing database\nAdditional properties available:\r\n- DatabaseName: Alternate property containing the database name (duplicate of Database)\r\n- DatabaseOwner: Alternate property containing the database owner (duplicate of Owner)\r\n- BackupSizeMB: Backup size expressed in megabytes (double)\r\n- CompressedBackupSizeMB: Compressed backup size expressed in megabytes (double)\r\n- RestoredFileFull: Full physical paths of all restored files separated by commas\r\n- BackupStartTime: DateTime when the backup operation started\r\n- BackupEndTime: DateTime when the backup operation completed\r\n- RestoreTargetTime: Target point-in-time for log recovery operations, or string \"Latest\" if restoring to current time\r\n- BackupFileRaw: Raw array of all backup file paths without string conversion\r\n- ExitError: Any exception object that occurred during restoration\r\n- KeepReplication: Boolean indicating if replication settings were preserved during restore\r\n- SACredential: The SA credential passed (if applicable)\nSystem.String (when -VerifyOnly is specified)\nReturns verification result strings: \"Verify successful\" or \"Verify failed\"\nSystem.String (when -OutputScriptOnly is specified)\nReturns the generated T-SQL RESTORE script as a string without executing the restore operation. Script can include EXECUTE AS LOGIN clause if ExecuteAs parameter was specified.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$BackupHistory | Invoke-DbaAdvancedRestore -SqlInstance MyInstance\nWill restore all the backups in the BackupHistory object according to the transformations it contains\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$BackupHistory | Invoke-DbaAdvancedRestore -SqlInstance MyInstance -OutputScriptOnly\nPS C:\\\u003e $BackupHistory | Invoke-DbaAdvancedRestore -SqlInstance MyInstance\nFirst generates just the T-SQL restore scripts so they can be sanity checked, and then if they are good perform the full restore.\r\nBy reusing the BackupHistory object there is no need to rescan all the backup files again", "Description": "This is the final execution step in the dbatools restore pipeline. It takes pre-processed BackupHistory objects and performs the actual SQL Server database restoration with support for complex scenarios that aren\u0027t handled by the standard Restore-DbaDatabase command.\n\nThe typical pipeline flow is: Get-DbaBackupInformation | Select-DbaBackupInformation | Format-DbaBackupInformation | Test-DbaBackupInformation | Invoke-DbaAdvancedRestore\n\nThis function handles advanced restore scenarios including point-in-time recovery, page-level restores, Azure blob storage backups, custom file relocations, and specialized options like CDC preservation or standby mode. It can generate T-SQL scripts for review before execution, verify backup integrity, or perform the actual restore operations.\n\nMost DBAs should use Restore-DbaDatabase for standard scenarios. This function is designed for situations requiring custom backup processing logic, complex migrations with file redirection, or when you need granular control over the restore process that isn\u0027t available in the simplified commands.\n\nAlways validate your BackupHistory objects with Test-DbaBackupInformation before using this function to ensure the restore chain is logically consistent.", "Links": "https://dbatools.io/Invoke-DbaAdvancedRestore", "Synopsis": "Executes database restores from processed BackupHistory objects with advanced customization options", "Availability": "Windows, Linux, macOS", "Params": [ [ "BackupHistory", "Processed BackupHistory objects from the dbatools restore pipeline containing backup file metadata and restore instructions.\r\nTypically comes from Format-DbaBackupInformation after running Get-DbaBackupInformation and Select-DbaBackupInformation.\r\nEach object contains the backup file paths, database name, file relocations, and sequencing information needed for the restore operation.", "", true, "true (ByValue)", "", "" ], [ "SqlInstance", "The SqlInstance to which the backups should be restored", "", 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", "", "" ], [ "OutputScriptOnly", "Generates T-SQL RESTORE scripts without executing them, allowing you to review the commands before running.\r\nUseful for validating complex restores, creating deployment scripts, or troubleshooting restore logic.\r\nThe generated scripts can be saved and executed manually or through other automation tools.", "", false, "false", "False", "" ], [ "VerifyOnly", "Performs RESTORE VERIFYONLY operations to check backup file integrity without actually restoring the database.\r\nUse this to validate backup files are readable and not corrupted before attempting a full restore.\r\nParticularly valuable when testing backup files from different environments or after transferring backup files.", "", false, "false", "False", "" ], [ "RestoreTime", "Specifies the exact point-in-time for log restore operations when performing point-in-time recovery.\r\nUse this for recovering to a specific moment before data corruption or unwanted changes occurred.\r\nMust be within the timeframe covered by your transaction log backups and should match the value used in earlier pipeline stages.", "", false, "false", "(Get-Date).AddDays(2)", "" ], [ "StandbyDirectory", "Directory path where SQL Server creates standby files for read-only access during restore operations.\r\nPuts the database in standby mode, allowing read-only queries while maintaining the ability to apply additional transaction log restores.\r\nCommonly used for log shipping warm standby servers or when you need to query data during a staged restore process.", "", false, "false", "", "" ], [ "NoRecovery", "Leaves the database in RESTORING state after the operation, allowing additional transaction log restores to be applied.\r\nEssential for point-in-time recovery scenarios where you need to apply multiple transaction log backups sequentially.\r\nThe database remains inaccessible until a final restore operation is performed WITH RECOVERY.", "", false, "false", "False", "" ], [ "MaxTransferSize", "Sets the maximum amount of data transferred between SQL Server and backup devices in each read operation.\r\nSpecify in bytes as a multiple of 64KB to optimize restore performance for large databases or slow storage.\r\nHigher values can improve performance but use more memory; typically ranges from 64KB to 4MB depending on your system.", "", false, "false", "0", "" ], [ "BlockSize", "Physical block size used for backup device I/O operations, must be 512, 1024, 2048, 4096, 8192, 16384, 32768, or 65536 bytes.\r\nShould match the block size used when the backup was created to avoid performance issues.\r\nMost backups use the default 64KB unless created with specific block size requirements for tape devices or storage optimization.", "", false, "false", "0", "" ], [ "BufferCount", "Number of I/O buffers SQL Server uses during the restore operation to improve throughput.\r\nHigher buffer counts can speed up restores for large databases, especially when reading from multiple backup files.\r\nTypically ranges from 2 to 64 buffers depending on available memory and restore performance requirements.", "", false, "false", "0", "" ], [ "Continue", "Continues a previously started restore sequence where the database is already in RESTORING or STANDBY state.\r\nUse this when applying additional transaction log backups to a database that was restored WITH NORECOVERY.\r\nAutomatically enables WithReplace to allow the operation on existing database objects.", "", false, "false", "False", "" ], [ "StorageCredential", "Name of the SQL Server credential object required to access backup files stored in Azure Blob Storage or S3-compatible object storage.\r\nThe credential must already exist on the target SQL Server instance with proper access keys for the storage account.\r\nFor Azure: The credential must contain valid Azure storage account keys or SAS tokens.\r\nFor S3: The credential must use Identity = \u0027S3 Access Key\u0027 and Secret = \u0027AccessKeyID:SecretKeyID\u0027. Requires SQL Server 2022 or higher.", "AzureCredential,S3Credential", false, "false", "", "" ], [ "WithReplace", "Allows the restore operation to overwrite an existing database with the same name.\r\nWithout this parameter, the restore will fail if a database with the target name already exists on the instance.\r\nCommonly used during database migrations, refresh operations, or when restoring over development/test databases.", "", false, "false", "False", "" ], [ "KeepReplication", "Preserves replication settings when restoring a database that was part of a replication topology.\r\nUse this when restoring a replicated database to maintain publisher, subscriber, or distributor configurations.\r\nWithout this parameter, replication metadata is removed during the restore process.", "", false, "false", "False", "" ], [ "KeepCDC", "Preserves Change Data Capture (CDC) configuration and metadata during database restore operations.\r\nEssential when restoring databases where CDC is actively capturing data changes for auditing or ETL processes.\r\nCannot be combined with NoRecovery or StandbyDirectory parameters as CDC requires the database to be fully recovered.", "", false, "false", "False", "" ], [ "PageRestore", "Array of page objects from Get-DbaSuspectPage specifying corrupted pages to restore using page-level restore.\r\nUse this for targeted repair of specific corrupted pages without restoring the entire database.\r\nEach object should contain FileId and PageID properties identifying the exact pages needing restoration.", "", false, "false", "", "" ], [ "ExecuteAs", "SQL Server login name to impersonate during the restore operation, affecting database ownership.\r\nWhen specified, the restore runs under this login context, making them the database owner.\r\nTypically used to ensure specific ownership patterns or when the current login lacks sufficient permissions.", "", false, "false", "", "" ], [ "StopBefore", "Stops the restore operation just before the specified StopMark rather than after it.\r\nUse this when you need to exclude a particular marked transaction from the restored database.\r\nOnly effective when used in combination with the StopMark parameter for mark-based recovery scenarios.", "", false, "false", "False", "" ], [ "StopMark", "Named transaction mark in the transaction log where the restore operation should stop.\r\nUse this for precise point-in-time recovery to a specific marked transaction, typically created with BEGIN TRAN WITH MARK.\r\nProvides more granular control than timestamp-based recovery for critical business operations.", "", false, "false", "", "" ], [ "StopAfterDate", "DateTime value specifying that only StopMark occurrences after this date should be considered for restore termination.\r\nUse this when the same mark name appears multiple times in your transaction log backups.\r\nEnsures the restore stops at the correct instance of the mark when identical mark names exist at different times.", "", false, "false", "", "" ], [ "Checksum", "Enables backup checksum verification during restore operations. Forces the restore to verify backup checksums and fail if checksums are not present.\r\nUse this to ensure backup files contain checksums and validate them during restore, following backup best practices.\r\nWithout this parameter, SQL Server verifies checksums if present but doesn\u0027t fail if checksums are missing. With this parameter, the operation fails if checksums are not present in the backup.", "", false, "false", "False", "" ], [ "Restart", "Instructs the restore operation to restart an interrupted restore sequence.\r\nUse this when a previous restore operation was interrupted due to a reboot, service failure, or other system event.\r\nAllows resuming large transaction log restores that were partially completed before interruption.", "", 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 cmdlet runs. The cmdlet is not run.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before running the cmdlet.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Deployment", "Install", "Patching", "Update" ], "CommandName": "Invoke-DbaAdvancedUpdate", "Name": "Invoke-DbaAdvancedUpdate", "Author": "Kirill Kravtsov (@nvarscar)", "Syntax": "Invoke-DbaAdvancedUpdate [[-ComputerName] \u003cString\u003e] [[-Action] \u003cObject[]\u003e] [[-Restart] \u003cBoolean\u003e] [[-Authentication] \u003cString\u003e] [[-Credential] \u003cPSCredential\u003e] [[-ExtractPath] \u003cString\u003e] [[-ArgumentList] \u003cString[]\u003e] [-NoPendingRenameCheck] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per action processed, with the following properties:\n- TargetLevel: The target SQL Server patch level that was installed\r\n- KB: The KB number of the patch that was applied\r\n- Installer: Path to the KB installer file that was used\r\n- MajorVersion: The major version of SQL Server (e.g., 2019, 2022)\r\n- Build: The specific build number of the installation\r\n- InstanceName: Name of the SQL Server instance targeted, or null if all instances were updated\r\n- Successful: Boolean indicating whether the update installation completed successfully\r\n- Restarted: Boolean indicating whether the computer was restarted as part of this update\r\n- ExitCode: The exit code returned by the SQL Server setup.exe program\r\n- ExtractPath: The directory path where update files were extracted on the target computer\r\n- Log: The output log from the setup.exe installation process\r\n- Notes: Array of error messages, warnings, or status notes encountered during installation", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaAdvancedUpdate -ComputerName SQL1 -Action $actions\nInvokes update actions on SQL1 after restarting it.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInvoke-DbaAdvancedUpdate -ComputerName SQL1 -Action $actions -ExtractPath C:\\temp\nExtracts required files to the specific location \"C:\\temp\". Invokes update actions on SQL1 after restarting it.", "Description": "Executes SQL Server KB updates on a target computer by extracting patch files, running setup.exe with appropriate parameters, and managing system restarts as needed. This function handles the core installation logic for Update-DbaInstance, processing update actions for specific SQL Server instances or all instances on a machine. It automatically detects the drive with most free space for extraction, validates pending reboots, and coordinates restart sequences to ensure patches install successfully across multiple update cycles.", "Links": "https://dbatools.io/Invoke-DbaAdvancedUpdate", "Synopsis": "Installs SQL Server updates and patches on remote computers with automatic restart management", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the remote computer where SQL Server updates will be installed.\r\nThis function handles the actual installation process after Update-DbaInstance creates the action plan.\r\nMust have WinRM enabled and accessible for remote operations including file extraction and system restarts.", "", false, "false", "", "" ], [ "Action", "Contains the update action plan objects created by Update-DbaInstance with details for each KB to install.\r\nEach action includes properties like TargetLevel, KB number, Installer path, MajorVersion, Build, and InstanceName.\r\nMultiple actions can be processed sequentially to chain-install several updates with automatic restarts between each.", "", false, "false", "", "" ], [ "Restart", "Automatically restarts the target computer after successful patch installation and waits for it to come back online.\r\nRequired for installing multiple patches in sequence, as each SQL Server update typically requires a system restart to complete.\r\nAlso handles pre-installation restarts when pending reboots are detected before beginning the update process.", "", false, "false", "False", "" ], [ "Authentication", "Specifies the WinRM authentication protocol for remote connections to the target computer.\r\nDefaults to CredSSP when credentials are provided to handle network share access and avoid double-hop authentication issues.\r\nUse Default authentication only for local operations, as network-based update repositories require credential delegation.", "", false, "false", "Credssp", "Default,Basic,Negotiate,NegotiateWithImplicitCredential,Credssp,Digest,Kerberos" ], [ "Credential", "Windows Credential with permission to log on to the remote server.\r\nMust be specified for any remote connection if update Repository is located on a network folder.", "", false, "false", "", "" ], [ "ExtractPath", "Specifies the directory path where update files will be extracted on the target computer.\r\nIf not specified, automatically selects the drive with the most free space for extraction.\r\nUse this when you need to control extraction location for space management or security requirements.", "", false, "false", "", "" ], [ "ArgumentList", "Additional command-line arguments passed to the SQL Server setup.exe during installation.\r\nCommonly used for setup customization like \"/SkipRules=RebootRequiredCheck\" to bypass reboot validation or \"/Q\" for quiet mode.\r\nArguments are automatically combined with required parameters like /quiet, /allinstances or /instancename, and /IAcceptSQLServerLicenseTerms.", "", false, "false", "", "" ], [ "NoPendingRenameCheck", "Skips the pending file rename check when determining if a system restart is required before installation.\r\nUse this when the pending rename detection produces false positives that prevent updates from proceeding.\r\nThe function will still check other restart conditions like registry entries and exit codes from previous installations.", "", 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": [ "AG", "HA" ], "CommandName": "Invoke-DbaAgFailover", "Name": "Invoke-DbaAgFailover", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Invoke-DbaAgFailover [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-AvailabilityGroup] \u003cString[]\u003e] [[-InputObject] \u003cAvailabilityGroup[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.AvailabilityGroup\nReturns one AvailabilityGroup object per availability group that was failed over. The object reflects the new state after the failover operation completes.\nDefault properties visible when displayed:\r\n- Name: The name of the availability group\r\n- PrimaryReplicaServerName: The server hosting the primary replica after failover\r\n- LocalReplicaRole: The role of the local replica (Primary or Secondary)\r\n- AutomatedBackupPreference: Preference for which replicas perform backups (Primary, Secondary, etc.)\r\n- FailureConditionLevel: The condition level that triggers automatic failover\r\n- HealthCheckTimeout: The health check interval in milliseconds\r\n- BasicAvailabilityGroup: Boolean indicating if this is a basic (Enterprise-only) availability group\r\n- ClusterType: The cluster type used (WSFC, External, or None)\nAdditional properties available from the SMO AvailabilityGroup object:\r\n- ID: Unique identifier for the availability group\r\n- UniqueId: The globally unique identifier for the availability group\r\n- AvailabilityReplicas: Collection of all replica objects in the availability group\r\n- AvailabilityDatabases: Collection of databases participating in the availability group\r\n- AvailabilityGroupListeners: Collection of listener endpoints configured for the availability group\r\n- DatabaseReplicaStates: Collection of database states across all replicas\r\n- RequiredSynchronizedSecondariesToCommit: Number of secondaries that must be synchronized before commit\nUse Select-Object * to access all SMO properties available on the AvailabilityGroup object.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaAgFailover -SqlInstance sql2017 -AvailabilityGroup SharePoint\nSafely (no potential data loss) fails over the SharePoint AG to sql2017. Prompts for confirmation.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sql2017 | Out-GridView -Passthru | Invoke-DbaAgFailover -Confirm:$false\nSafely (no potential data loss) fails over the selected availability groups to sql2017. Does not prompt for confirmation.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eInvoke-DbaAgFailover -SqlInstance sql2017 -AvailabilityGroup SharePoint -Force\nForcefully (with potential data loss) fails over the SharePoint AG to sql2017. Prompts for confirmation.", "Description": "Performs manual failover of an availability group to make the specified SQL Server instance the new primary replica. The function connects to the target instance (which must be a secondary replica) and promotes it to primary, while the current primary becomes secondary.\n\nBy default, performs a safe failover that waits for all committed transactions to be synchronized to the target replica, preventing data loss. When the -Force parameter is used, performs a forced failover that may result in data loss if transactions haven\u0027t been synchronized to the target replica.\n\nThis is commonly used during planned maintenance windows, disaster recovery scenarios, or when rebalancing availability group workloads across replicas. The target instance must already be configured as a secondary replica in the availability group.", "Links": "https://dbatools.io/Invoke-DbaAgFailover", "Synopsis": "Performs manual failover of an availability group to make the target instance the new primary replica.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The SQL Server instance. 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 the name(s) of the availability groups to failover on the target instance. Accepts multiple availability group names.\r\nUse this when you need to failover specific availability groups rather than all groups on the instance.\r\nRequired when using SqlInstance parameter to identify which availability groups should be failed over.", "", false, "false", "", "" ], [ "InputObject", "Accepts availability group objects from Get-DbaAvailabilityGroup for pipeline operations.\r\nUse this approach when you want to filter or select specific availability groups before failover.\r\nAllows for more complex scenarios like failing over multiple groups across different instances in a single operation.", "", false, "true (ByValue)", "", "" ], [ "Force", "Performs a forced failover that allows potential data loss by not waiting for transaction synchronization.\r\nUse this during disaster recovery scenarios when the primary replica is unavailable and you need immediate failover.\r\nWithout this switch, the function performs a safe failover that waits for all committed transactions to synchronize, preventing 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": [ "Database", "FileManagement", "File", "Utility" ], "CommandName": "Invoke-DbaBalanceDataFiles", "Name": "Invoke-DbaBalanceDataFiles", "Author": "Sander Stad (@sqlstad), sqlstad.nl", "Syntax": "Invoke-DbaBalanceDataFiles [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-Table \u003cObject[]\u003e] [-RebuildOffline] [-EnableException] [-Force] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nInvoke-DbaBalanceDataFiles -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-Table \u003cObject[]\u003e] [-RebuildOffline] [-EnableException] [-Force] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database processed with data file balancing results.\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 that was balanced\r\n- Start: DateTime when the data file balancing operation started\r\n- End: DateTime when the data file balancing operation completed\r\n- Elapsed: The elapsed time formatted as HH:mm:ss\r\n- Success: Boolean indicating if the data file balancing was successful\r\n- Unsuccessful: Comma-separated list of table names that could not be balanced (empty string if all successful)\r\n- DataFilesStart: Array of file objects before balancing, each containing ID, LogicalName, PhysicalName, Size, UsedSpace, AvailableSpace\r\n- DataFilesEnd: Array of file objects after balancing, each containing ID, LogicalName, PhysicalName, Size, UsedSpace, AvailableSpace", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaBalanceDataFiles -SqlInstance sql1 -Database db1\nThis command will distribute the data in database db1 on instance sql1\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInvoke-DbaBalanceDataFiles -SqlInstance sql1 -Database db1 | Select-Object -ExpandProperty DataFilesEnd\nThis command will distribute the data in database db1 on instance sql1\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eInvoke-DbaBalanceDataFiles -SqlInstance sql1 -Database db1 -Table table1,table2,table5\nThis command will distribute the data for only the tables table1,table2 and table5\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eInvoke-DbaBalanceDataFiles -SqlInstance sql1 -Database db1 -RebuildOffline\nThis command will consider the fact that there might be a SQL Server edition that does not support online rebuilds of indexes.\r\nBy supplying this parameter you give permission to do the rebuilds offline if the edition does not support it.", "Description": "When you have a large database with a single data file and add another file, SQL Server will only use the new file until it\u0027s about the same size.\nYou may want to balance the data between all the data files.\n\nThe function will check the server version and edition to see if the it allows for online index rebuilds.\nIf the server does support it, it will try to rebuild the index online.\nIf the server doesn\u0027t support it, it will rebuild the index offline. Be carefull though, this can cause downtime\n\nThe tables must have a clustered index to be able to balance out the data.\nThe function does NOT yet support heaps.\n\nThe function will also check if the file groups are subject to balance out.\nA file group would have at least have 2 data files and should be writable.\nIf a table is within such a file group it will be subject for processing. If not the table will be skipped.\n\nNote: this command does not perform a disk space check for non-Windows machines so make sure you have enough space on the disk.", "Links": "https://dbatools.io/Invoke-DbaBalanceDataFiles", "Synopsis": "Re-balance data between data files", "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 balance data files for. Only databases with multiple data files can be balanced.\r\nThis parameter is required since the function needs specific databases to process for data file balancing.", "", false, "false", "", "" ], [ "Table", "Specifies which tables to balance data for within the target databases. Only tables with clustered indexes in file groups containing multiple data files will be processed.\r\nWhen omitted, all eligible tables in the database will be processed. Use this to target specific large tables that need data redistribution.", "Tables", false, "false", "", "" ], [ "RebuildOffline", "Forces all clustered index rebuilds to occur offline, which redistributes data between files but blocks table access during the operation.\r\nUse this switch when you need to balance data files but can accept downtime, or when working with SQL Server editions that don\u0027t support online index operations (Standard, Express, Web).", "", 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", "" ], [ "Force", "Bypasses the disk space validation check that ensures sufficient free space exists before balancing data files.\r\nUse this when you\u0027re confident about available disk space or when working with non-Windows SQL Server instances where disk space checks may not work properly.", "", 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": [ "Instance", "ErrorLog", "Logging" ], "CommandName": "Invoke-DbaCycleErrorLog", "Name": "Invoke-DbaCycleErrorLog", "Author": "Shawn Melton (@wsmelton), wsmelton.github.io", "Syntax": "Invoke-DbaCycleErrorLog [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Type] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per instance processed with error log cycling results.\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- LogType: String array of log types that were cycled (contains \u0027instance\u0027, \u0027agent\u0027, or both)\r\n- IsSuccessful: Boolean indicating if the error log cycling was successful\r\n- Notes: Exception object if operation failed, null if successful", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaCycleLog -SqlInstance sql2016 -Type agent\nCycles the current error log for the SQL Server Agent on SQL Server instance sql2016\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInvoke-DbaCycleLog -SqlInstance sql2016 -Type instance\nCycles the current error log for the SQL Server instance on SQL Server instance sql2016\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eInvoke-DbaCycleLog -SqlInstance sql2016\nCycles the current error log for both SQL Server instance and SQL Server Agent on SQL Server instance sql2016", "Description": "Archives the current error log files and creates new ones for SQL Server instance and/or SQL Agent. This operation is typically performed during maintenance windows to manage log file sizes and establish clean baselines for troubleshooting. When cycled, the current error log becomes the archived log (errorlog.1) and a new error log starts capturing events.", "Links": "https://dbatools.io/Invoke-DbaCycleErrorLog", "Synopsis": "Cycles the current SQL Server error log and/or SQL Agent error log to start fresh log files", "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", "", "" ], [ "Type", "Specifies which error log to cycle: \u0027instance\u0027 for SQL Server instance log, \u0027agent\u0027 for SQL Agent log.\r\nWhen omitted, cycles both logs simultaneously which is the typical maintenance approach.\r\nUse specific values when you need to manage log sizes independently or troubleshoot specific services.", "", false, "false", "", "instance,agent" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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": [ "Azure", "Database" ], "CommandName": "Invoke-DbaDbAzSqlTip", "Name": "Invoke-DbaDbAzSqlTip", "Author": "Jess Pomfret (@jpomfret), jesspomfret.com", "Syntax": "Invoke-DbaDbAzSqlTip [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-AzureDomain] \u003cString\u003e] [[-Tenant] \u003cString\u003e] [[-LocalFile] \u003cString\u003e] [[-Database] \u003cString[]\u003e] [[-ExcludeDatabase] \u003cString[]\u003e] [-AllUserDatabases] [-ReturnAllTips] [-Compat100] [[-StatementTimeout] \u003cInt32\u003e] [-EnableException] [-Force] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per tip recommendation generated by the Azure SQL Tips analysis script. Each object contains the recommendation details including the tip identifier, description, confidence level, \r\nand supporting information.\nProperties:\r\n- ComputerName: The computer name of the Azure SQL instance\r\n- InstanceName: The Azure SQL instance name\r\n- SqlInstance: The full Azure SQL instance name (typically servername.database.windows.net)\r\n- Database: The name of the database analyzed for the tip\r\n- tip_id: Unique identifier for the specific performance recommendation\r\n- description: Text description of the performance optimization being recommended\r\n- confidence_percent: Confidence level percentage (0-100) indicating how likely the recommendation is applicable to the analyzed database\r\n- additional_info_url: URL to Microsoft documentation or additional resources explaining the tip in detail\r\n- details: Additional context or detailed explanation specific to the tip", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaDbAzSqlTip -SqlInstance dbatools1.database.windows.net -SqlCredential (Get-Credential) -Database ImportantDb\nRuns the Azure SQL Tips script against the dbatools1.database.windows.net using the specified credentials for the ImportantDb.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInvoke-DbaDbAzSqlTip -SqlInstance dbatools1.database.windows.net -SqlCredential (Get-Credential) -Database ImportantDb -ReturnAllTips\nRuns the Azure SQL Tips script against the dbatools1.database.windows.net using the specified credentials for the ImportantDb and\r\nwill return all the tips regardless of database state.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eInvoke-DbaDbAzSqlTip -SqlInstance dbatools1.database.windows.net -SqlCredential (Get-Credential) -Database ImportantDb -LocalFile \u0027C:\\temp\\get-sqldb-tips.sql\u0027\nRuns the Azure SQL Tips script that is available locally at \u0027C:\\temp\\get-sqldb-tips.sql\u0027 against the dbatools1.database.windows.net using the specified\r\ncredentials for the ImportantDb and will return all the tips regardless of database state.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eInvoke-DbaDbAzSqlTip -SqlInstance dbatools1.database.windows.net -SqlCredential (Get-Credential) -ExcludeDatabase TestDb\nRuns the Azure SQL Tips script against all the databases on the dbatools1.database.windows.net using the specified credentials except for TestDb.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eInvoke-DbaDbAzSqlTip -SqlInstance dbatools1.database.windows.net -SqlCredential (Get-Credential) -AllUserDatabases\nRuns the Azure SQL Tips script against all the databases on the dbatools1.database.windows.net using the specified credentials.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e$cred = Get-Credential\nPS C:\\\u003e Invoke-DbaDbAzSqlTip -SqlInstance dbatools1.database.windows.net -SqlCredential $cred -Database ImportantDb\nEnter Azure AD username\\password into Get-Credential, and then Invoke-DbaDbAzSqlTip will runs the Azure SQL Tips\r\nscript against the ImportantDb database on the dbatools1.database.windows.net server using Azure AD.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eInvoke-DbaDbAzSqlTip -SqlInstance dbatools1.database.windows.net -SqlCredential (Get-Credential) -Database ImportantDb -Tenant GUID-GUID-GUID\nRun the Azure SQL Tips script against the ImportantDb database on the dbatools1.database.windows.net server specifying the Azure Tenant Id.", "Description": "Executes Microsoft\u0027s Azure SQL Tips script against Azure SQL Database instances to identify performance optimization opportunities and design recommendations. This function runs the get-sqldb-tips.sql script developed by the Azure SQL Product Management team, which analyzes your database configuration, query patterns, and resource utilization to provide actionable improvement suggestions.\n\nThe script examines database settings, index usage, query performance metrics, and configuration parameters to generate targeted recommendations with confidence percentages. Each tip includes detailed explanations and links to Microsoft documentation for implementation guidance.\n\nBy default, the latest version of the tips script is automatically downloaded from the Microsoft GitHub repository at https://github.com/microsoft/azure-sql-tips. You can also specify a local copy using the -LocalFile parameter if you prefer to use a cached or customized version of the script.", "Links": "https://dbatools.io/Invoke-DbaDbAzSqlTip", "Synopsis": "Executes Microsoft\u0027s Azure SQL performance recommendations script against Azure SQL Database instances.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target Azure SQL instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\nSQL Server Authentication and Azure Active Directory are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "AzureDomain", "Specifies the Azure SQL domain for connection. Defaults to database.windows.net for standard Azure SQL Database instances.\r\nUse this when connecting to Azure SQL instances in sovereign clouds like Azure Government (.usgovcloudapi.net) or Azure China (.chinacloudapi.cn).", "", false, "false", "database.windows.net", "" ], [ "Tenant", "Specifies the Azure AD tenant ID (GUID) for authentication to Azure SQL Database.\r\nRequired when using Azure Active Directory authentication with multi-tenant applications or when the default tenant cannot be determined automatically.", "", false, "false", "", "" ], [ "LocalFile", "Specifies the path to a local copy of the Azure SQL Tips script files instead of downloading from GitHub.\r\nUse this when you need to run a specific version, work in environments without internet access, or have customized the tips script for your organization.", "", false, "false", "", "" ], [ "Database", "Specifies which Azure SQL databases to analyze for performance recommendations.\r\nUse this when you want to target specific databases rather than analyzing all user databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies which Azure SQL databases to skip when running performance analysis.\r\nUse this with -AllUserDatabases to exclude specific databases like development or test environments from the tips analysis.", "", false, "false", "", "" ], [ "AllUserDatabases", "Analyzes all user databases on the Azure SQL instance for performance recommendations.\r\nExcludes the master database and automatically discovers all other databases, making it ideal for comprehensive performance audits.", "", false, "false", "False", "" ], [ "ReturnAllTips", "Returns all available performance tips regardless of current database state or configuration.\r\nBy default, the script only shows relevant tips based on your database\u0027s current settings and usage patterns.", "", false, "false", "False", "" ], [ "Compat100", "Uses a specialized version of the tips script designed for databases running compatibility level 100 (SQL Server 2008).\r\nOnly use this when analyzing legacy Azure SQL databases that cannot be upgraded to newer compatibility levels.", "", false, "false", "False", "" ], [ "StatementTimeout", "Sets the query timeout in minutes for the Azure SQL Tips analysis script.\r\nIncrease this value when analyzing large databases or instances with heavy workloads that may cause the default timeout to be exceeded.", "", 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", "" ], [ "Force", "Forces a fresh download of the Azure SQL Tips script from GitHub, bypassing any locally cached version.\r\nUse this when you want to ensure you\u0027re running the latest version or when troubleshooting issues with cached files.", "", false, "false", "False", "" ] ] }, { "Tags": "DBCC", "CommandName": "Invoke-DbaDbccDropCleanBuffer", "Name": "Invoke-DbaDbccDropCleanBuffer", "Author": "Patrick Flynn (@sqllensman)", "Syntax": "Invoke-DbaDbccDropCleanBuffer [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-NoInformationalMessages] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance executed against. Each object contains the command executed and its output from the DBCC DROPCLEANBUFFERS statement.\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- Cmd: The DBCC command that was executed (e.g., \"DBCC DROPCLEANBUFFERS\" or \"DBCC DROPCLEANBUFFERS WITH NO_INFOMSGS\")\r\n- Output: The message output from executing the DBCC DROPCLEANBUFFERS command, if any", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaDbccDropCleanBuffer -SqlInstance SqlServer2017\nRuns the command DBCC DROPCLEANBUFFERS against the instance SqlServer2017 using Windows Authentication\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInvoke-DbaDbccDropCleanBuffer -SqlInstance SqlServer2017 -NoInformationalMessages\nRuns the command DBCC DROPCLEANBUFFERS WITH NO_INFOMSGS against the instance SqlServer2017 using Windows Authentication\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Invoke-DbaDbccDropCleanBuffer -WhatIf\nDisplays what will happen if command DBCC DROPCLEANBUFFERS is called against Sql1 and Sql2/sqlexpress\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Invoke-DbaDbccDropCleanBuffer -SqlInstance Server1 -SqlCredential $cred\nConnects using sqladmin credential and executes command DBCC DROPCLEANBUFFERS for instance Server1", "Description": "Executes DBCC DROPCLEANBUFFERS to remove all clean data pages from the buffer pool and columnstore objects from memory. This forces SQL Server to read data from disk on subsequent queries, simulating a \"cold cache\" environment for accurate performance testing and query optimization scenarios. DBAs use this command when they need to test query performance without the benefit of cached data pages, ensuring consistent baseline measurements across multiple test runs.\n\nRead more:\n - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-dropcleanbuffers-transact-sql", "Links": "https://dbatools.io/Invoke-DbaDbccDropCleanBuffer", "Synopsis": "Clears SQL Server buffer pool cache and columnstore object pool for performance testing", "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", "", "" ], [ "NoInformationalMessages", "Suppresses informational messages from the DBCC DROPCLEANBUFFERS command output.\r\nUse this when running automated scripts where you only want to capture errors or when you need cleaner output for logging 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", "" ], [ "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": "DBCC", "CommandName": "Invoke-DbaDbccFreeCache", "Name": "Invoke-DbaDbccFreeCache", "Author": "Patrick Flynn (@sqllensman)", "Syntax": "Invoke-DbaDbccFreeCache [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Operation] \u003cString\u003e] [[-InputValue] \u003cString\u003e] [-NoInformationalMessages] [-MarkInUseForRemoval] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance processed, containing the DBCC command that was executed and the resulting output from the SQL Server cache clearing operation.\nProperties:\r\n- ComputerName: The computer name of the SQL Server instance where the cache was cleared\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance format)\r\n- Operation: The cache clearing operation executed (FreeProcCache, FreeSessionCache, or FreeSystemCache)\r\n- Cmd: The complete DBCC command that was executed (e.g., \"DBCC FREEPROCCACHE WITH NO_INFOMSGS\")\r\n- Output: The informational messages or output returned by the DBCC command; $null if -NoInformationalMessages was specified", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaDbccFreeCache -SqlInstance SqlServer2017 -Operation FREEPROCCACHE\nRuns the command DBCC FREEPROCCACHE against the instance SqlServer2017 using Windows Authentication\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInvoke-DbaDbccFreeCache -SqlInstance SqlServer2017 -Operation FREESESSIONCACHE -NoInformationalMessages\nRuns the command DBCC FREESESSIONCACHE WITH NO_INFOMSGS against the instance SqlServer2017 using Windows Authentication\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eInvoke-DbaDbccFreeCache -SqlInstance SqlServer2017 -Operation FREESYSTEMCACHE -NoInformationalMessages\nRuns the command DBCC FREESYSTEMCACHE WITH NO_INFOMSGS against the instance SqlServer2017 using Windows Authentication\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eInvoke-DbaDbccFreeCache -SqlInstance SqlServer2017 -Operation FREEPROCCACHE -InputValue 0x060006001ECA270EC0215D05000000000000000000000000\nRemove a specific plan with plan_handle 0x060006001ECA270EC0215D05000000000000000000000000 from the cache via the command DBCC FREEPROCCACHE(0x060006001ECA270EC0215D05000000000000000000000000) \r\nagainst the instance SqlServer2017 using Windows Authentication\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eInvoke-DbaDbccFreeCache -SqlInstance SqlServer2017 -Operation FREEPROCCACHE -InputValue default\nRuns the command DBCC FREEPROCCACHE(\u0027default\u0027) against the instance SqlServer2017 using Windows Authentication. This clears all cache entries associated with a resource pool \u0027default\u0027.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eInvoke-DbaDbccFreeCache -SqlInstance SqlServer2017 -Operation FREESYSTEMCACHE -InputValue default\nRuns the command DBCC FREESYSTEMCACHE (\u0027ALL\u0027, default) against the instance SqlServer2017 using Windows Authentication. This will clean all the caches with entries specific to the resource pool named \r\n\"default\".\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eInvoke-DbaDbccFreeCache -SqlInstance SqlServer2017 -Operation FREESYSTEMCACHE -InputValue default -MarkInUseForRemoval\nRuns the command DBCC FREESYSTEMCACHE (\u0027ALL\u0027, default) WITH MARK_IN_USE_FOR_REMOVAL against the instance SqlServer2017 using Windows Authentication. This will to release entries once the entries \r\nbecome unused for all the caches with entries specific to the resource pool named \"default\".", "Description": "Executes DBCC commands to clear various SQL Server memory caches when troubleshooting performance problems or freeing memory on resource-constrained systems. This function helps DBAs resolve issues like parameter sniffing, plan cache bloat, or memory pressure without restarting the SQL Server service.\n\nSupports three cache-clearing operations:\n- DBCC FREEPROCCACHE: Clears procedure cache (all plans or specific plan handles/resource pools)\n- DBCC FREESESSIONCACHE: Clears distributed query connection cache for linked servers\n- DBCC FREESYSTEMCACHE: Clears system caches like token cache and ring buffers\n\nUse FREEPROCCACHE to resolve parameter sniffing issues or when query plans become inefficient. Use FREESESSIONCACHE when experiencing linked server connection problems. Use FREESYSTEMCACHE to clear authentication tokens and other system-level cached data.\n\nRead more:\n - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-freeproccache-transact-sql\n - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-freesessioncache-transact-sql\n - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-freesystemcache-transact-sql", "Links": "https://dbatools.io/Invoke-DbaDbccFreeCache", "Synopsis": "Clears SQL Server memory caches using DBCC commands to resolve performance issues and free 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", "", "" ], [ "Operation", "Specifies which cache clearing operation to perform: FreeProcCache, FreeSessionCache, or FreeSystemCache.\r\nUse FreeProcCache to resolve parameter sniffing or clear inefficient query plans, FreeSessionCache to clear linked server connections, or FreeSystemCache to clear authentication tokens and \r\nsystem-level caches.", "", false, "false", "FreeProcCache", "FreeProcCache,FreeSessionCache,FreeSystemCache" ], [ "InputValue", "Specifies a target value to limit the cache clearing operation instead of clearing all cache entries.\r\nFor FreeProcCache: provide a specific plan_handle (0x...), sql_handle (0x...), or Resource Governor pool name to clear only those entries. For FreeSystemCache: provide a Resource Governor pool name \r\nto clear only that pool\u0027s cache entries.\r\nWhen omitted, clears all entries for the specified operation which is the typical DBA use case.", "", false, "false", "", "" ], [ "NoInformationalMessages", "Suppresses informational messages returned by the DBCC commands.\r\nUse this in scripts or automated processes where you only want to capture errors and warnings.", "", false, "false", "False", "" ], [ "MarkInUseForRemoval", "Marks currently active cache entries for removal once they become unused, rather than waiting for them to be released.\r\nOnly applies to FreeSystemCache operations and helps ensure memory is freed more aggressively on systems under memory pressure.", "", 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 cmdlet runs. The cmdlet is not run.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before running the cmdlet.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Statistics", "Performance", "Clone" ], "CommandName": "Invoke-DbaDbClone", "Name": "Invoke-DbaDbClone", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Invoke-DbaDbClone [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [[-CloneDatabase] \u003cString[]\u003e] [-ExcludeStatistics] [-ExcludeQueryStore] [-UpdateStatistics] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Database\nReturns one Database object for each cloned database created. When cloning a source database to multiple clone names (via -CloneDatabase parameter with multiple values), one Database object is \r\nreturned per clone created.\nDefault display properties (via Select-DefaultView from Get-DbaDatabase):\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 cloned database\r\n- Status: Current database status (Normal, Offline, Recovering, etc.)\r\n- IsAccessible: Boolean indicating if the database is currently accessible\r\n- RecoveryModel: Database recovery model (Full, Simple, or BulkLogged)\r\n- LogReuseWaitStatus: Status of transaction log reuse\r\n- Size: Database size in megabytes\r\n- Owner: Database owner login name\r\n- Collation: Database collation setting\r\n- Encrypted: Boolean indicating if Transparent Data Encryption (TDE) is enabled\nAdditional properties available from the SMO Database object using Select-Object *:\r\n- CreateDate: DateTime when the database was created\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\r\n- DatabaseEngineEdition: Edition of SQL Server (Enterprise, Standard, Express, etc.)\r\n- ID: Database ID assigned by SQL Server\r\n- And many other SMO Database properties (see https://learn.microsoft.com/en-us/dotnet/api/microsoft.sqlserver.management.smo.database)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaDbClone -SqlInstance sql2016 -Database mydb -CloneDatabase myclone\nClones mydb to myclone on sql2016\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2016 -Database mydb | Invoke-DbaDbClone -CloneDatabase myclone, myclone2 -UpdateStatistics\nUpdates the statistics of mydb then clones to myclone and myclone2", "Description": "Creates schema-only database clones using SQL Server\u0027s DBCC CLONEDATABASE command. The cloned database contains all database objects (tables, indexes, views, procedures) and statistics, but no actual table data.\n\nThis is particularly valuable for performance troubleshooting scenarios where you need to analyze query execution plans and optimizer behavior without the storage overhead of copying entire tables. DBAs commonly use this for reproducing performance issues in test environments or sharing database structures with vendors for support cases.\n\nRead more:\n - https://sqlperformance.com/2016/08/sql-statistics/expanding-dbcc-clonedatabase\n - https://support.microsoft.com/en-us/help/3177838/how-to-use-dbcc-clonedatabase-to-generate-a-schema-and-statistics-only\n\nThanks to Microsoft Tiger Team for the code and idea https://github.com/Microsoft/tigertoolbox/", "Links": "https://dbatools.io/Invoke-DbaDbClone", "Synopsis": "Creates lightweight database clones containing schema and statistics but no table data", "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 source database(s) to clone from the SQL Server instance. Accepts multiple database names for batch operations.\r\nUse this when connecting directly to an instance rather than piping database objects from Get-DbaDatabase.", "", false, "false", "", "" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase through the pipeline, allowing for filtered operations.\r\nThis method provides more flexibility than the Database parameter for complex database selection scenarios.", "", false, "true (ByValue)", "", "" ], [ "CloneDatabase", "Specifies the name(s) for the new cloned database(s). If not provided, defaults to adding \u0027_clone\u0027 suffix to the source database name.\r\nEach clone must have a unique name on the target instance and cannot already exist.", "", false, "false", "", "" ], [ "ExcludeStatistics", "Excludes table and index statistics from the cloned database, creating only the schema structure without statistical metadata.\r\nUse this when you only need the database structure for schema comparison or when statistics would interfere with your testing scenario. Requires SQL Server 2014 SP2 CU3+ or SQL Server 2016 SP1+.", "", false, "false", "False", "" ], [ "ExcludeQueryStore", "Excludes Query Store data from the cloned database, preventing historical query execution data from being copied.\r\nUse this when you want a clean slate for query performance analysis or when Query Store data is not relevant to your testing scenario. Requires SQL Server 2016 SP1 or higher.", "", false, "false", "False", "" ], [ "UpdateStatistics", "Updates column store index statistics in the source database before cloning using Microsoft Tiger Team methodology.\r\nUse this when working with column store indexes to ensure the clone contains current statistical information for accurate query plan generation.", "", 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": "DataGeneration", "CommandName": "Invoke-DbaDbDataGenerator", "Name": "Invoke-DbaDbDataGenerator", "Author": "Sander Stad (@sqlstad, sqlstad.nl)", "Syntax": "Invoke-DbaDbDataGenerator [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [-FilePath] \u003cObject\u003e [[-Locale] \u003cString\u003e] [[-CharacterString] \u003cString\u003e] [[-Table] \u003cString[]\u003e] [[-Column] \u003cString[]\u003e] [[-ExcludeTable] \u003cString[]\u003e] [[-ExcludeColumn] \u003cString[]\u003e] [[-MaxValue] \u003cInt32\u003e] [-ExactLength] [[-ModulusFactor] \u003cInt32\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per table that had data generated, providing a summary of the data generation operation.\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: The name of the database where data was generated\r\n- Schema: The schema name containing the table\r\n- Table: The name of the table that was populated with generated data\r\n- Columns: Array of column names that received generated data\r\n- Rows: Integer count of rows generated and inserted into the table\r\n- Elapsed: TimeSpan of the time taken to generate and insert data (formatted as prettytimespan for display)\r\n- Status: String indicating the result of the operation - \"Done\" for successful completion", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaDbDataGenerator -SqlInstance sqldb2 -Database DB1 -FilePath C:\\temp\\sqldb1.db1.tables.json\nApply the data generation configuration from the file \"sqldb1.db1.tables.json\" to the db1 database on sqldb2. Prompt for confirmation for each table.", "Description": "Populates database tables with randomly generated but realistic test data based on JSON configuration files. Uses the Bogus library to create fake but believable data like names, addresses, phone numbers, and dates that respect column constraints and data types. Perfect for creating development environments, testing scenarios, or demo databases without using production data. Handles identity columns, unique indexes, nullable fields, and foreign key relationships while maintaining data integrity.", "Links": "https://dbatools.io/Invoke-DbaDbDataGenerator", "Synopsis": "Generates realistic test data for SQL Server database tables using configuration-driven rules", "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 generate data for. If not provided, uses database names from the configuration file.\r\nUse this to limit data generation to specific databases when your config file covers multiple databases.", "", false, "false", "", "" ], [ "FilePath", "Path to the JSON configuration file that defines data generation rules for tables and columns. Accepts local file paths or HTTP URLs.\r\nThis file specifies which tables to populate, how many rows to generate, and the data generation rules for each column.", "Path,FullName", true, "true (ByValue)", "", "" ], [ "Locale", "Sets the locale for generating culture-specific fake data like names, addresses, and phone numbers. Defaults to \u0027en\u0027 for English.\r\nChange this when you need realistic data for specific regions, such as \u0027de\u0027 for German or \u0027fr\u0027 for French test data.", "", false, "false", "en", "" ], [ "CharacterString", "Defines the character set used for generating random string values. Defaults to alphanumeric characters.\r\nCustomize this when you need specific character patterns for testing, such as restricting to only uppercase letters or including special characters.", "", false, "false", "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", "" ], [ "Table", "Limits data generation to specific tables only, overriding the full table list in the configuration file.\r\nUseful when you need to populate just certain tables for testing or during incremental development work.", "", false, "false", "", "" ], [ "Column", "Restricts data generation to specific columns within the processed tables.\r\nUse this to generate data for only certain columns during testing or when troubleshooting specific column configurations.", "", false, "false", "", "" ], [ "ExcludeTable", "Skips specific tables even if they\u0027re included in the configuration file.\r\nUse this to temporarily exclude problematic tables during testing or when you want to process most tables but skip a few.", "", false, "false", "", "" ], [ "ExcludeColumn", "Skips specific columns even if they\u0027re included in the configuration file.\r\nHelpful when troubleshooting column-specific issues or when you want to exclude sensitive columns temporarily.", "", false, "false", "", "" ], [ "MaxValue", "Overrides the maximum length for string columns, ignoring the data type\u0027s natural limits. Lower data type limits still take precedence.\r\nUseful for testing with shorter strings or when you need consistent string lengths across different environments.", "", false, "false", "0", "" ], [ "ExactLength", "Forces generated strings to match the exact length of existing data in the column.\r\nUse this when you need to preserve string length patterns for testing applications that expect specific data formats.", "", false, "false", "False", "" ], [ "ModulusFactor", "Controls how frequently nullable columns receive NULL values by using modulus calculation. Default is every 10th row gets NULL.\r\nAdjust this to increase or decrease NULL frequency in your test data to match realistic data distribution patterns.", "", false, "false", "10", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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": [ "Masking", "DataMasking" ], "CommandName": "Invoke-DbaDbDataMasking", "Name": "Invoke-DbaDbDataMasking", "Author": "Sander Stad (@sqlstad, sqlstad.nl) | Chrissy LeMaire (@cl, netnerds.net)", "Syntax": "Invoke-DbaDbDataMasking [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [-FilePath] \u003cObject\u003e [[-Locale] \u003cString\u003e] [[-CharacterString] \u003cString\u003e] [[-Table] \u003cString[]\u003e] [[-Column] \u003cString[]\u003e] [[-ExcludeTable] \u003cString[]\u003e] [[-ExcludeColumn] \u003cString[]\u003e] [[-MaxValue] \u003cInt32\u003e] [[-ModulusFactor] \u003cInt32\u003e] [-ExactLength] [[-CommandTimeout] \u003cInt32\u003e] [[-BatchSize] \u003cInt32\u003e] [[-Retry] \u003cInt32\u003e] [[-DictionaryFilePath] \u003cString[]\u003e] [[-DictionaryExportPath] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per table that was processed by the masking operation. Each object contains the results of masking that specific table.\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- Database: The database where masking was performed\r\n- Schema: The schema name of the masked table\r\n- Table: The name of the masked table\r\n- Columns: Array of column names that were masked\r\n- Rows: Integer count of rows that were masked in the table\r\n- Elapsed: TimeSpan object showing how long the masking operation took for this table\r\n- Status: String indicating if masking was \"Successful\" or \"Failed\" for this table", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaDbDataMasking -SqlInstance SQLDB2 -Database DB1 -FilePath C:\\Temp\\sqldb1.db1.tables.json\nApply the data masking configuration from the file \"sqldb1.db1.tables.json\" to the db1 database on sqldb2. Prompt for confirmation for each table.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-ChildItem -Path C:\\Temp\\sqldb1.db1.tables.json | Invoke-DbaDbDataMasking -SqlInstance SQLDB2 -Database DB1 -Confirm:$false\nApply the data masking configuration from the file \"sqldb1.db1.tables.json\" to the db1 database on sqldb2. Do not prompt for confirmation.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eNew-DbaDbMaskingConfig -SqlInstance SQLDB1 -Database DB1 -Path C:\\Temp\\clone -OutVariable file\n$file | Invoke-DbaDbDataMasking -SqlInstance SQLDB2 -Database DB1 -Confirm:$false\nCreate the data masking configuration file \"sqldb1.db1.tables.json\", then use it to mask the db1 database on sqldb2. Do not prompt for confirmation.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-ChildItem -Path C:\\Temp\\sqldb1.db1.tables.json | Invoke-DbaDbDataMasking -SqlInstance SQLDB2, sqldb3 -Database DB1 -Confirm:$false\nSee what would happen if you the data masking configuration from the file \"sqldb1.db1.tables.json\" to the db1 database on sqldb2 and sqldb3. Do not prompt for confirmation.", "Description": "Replaces sensitive data in SQL Server databases with randomized values based on a JSON configuration file. This enables DBAs to create safe, non-production datasets for development, testing, and training environments without exposing real customer data.\n\nThe function processes tables row-by-row, applying masking rules like generating fake names, addresses, phone numbers, or random strings while preserving data relationships and referential integrity. It supports deterministic masking to maintain consistency across related records and can handle unique constraints.\n\nUse New-DbaDbMaskingConfig to generate the required configuration file, which defines which columns to mask and what type of replacement data to generate. The masking process creates temporary tables and indexes to optimize performance during large data transformations.\n\nNote that the following column and data types are not currently supported:\nIdentity\nForeignKey\nComputed\nHierarchyid\nGeography\nGeometry\nXml", "Links": "https://dbatools.io/Invoke-DbaDbDataMasking", "Synopsis": "Replaces sensitive production data with randomized values using configurable masking rules", "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 mask on the target instance. Accepts wildcards for pattern matching.\r\nIf omitted, uses the database name from the configuration file. Essential for targeting specific databases when the same config applies to multiple environments.", "", false, "false", "", "" ], [ "FilePath", "Path to the JSON configuration file that defines masking rules for tables and columns. Accepts pipeline input from New-DbaDbMaskingConfig.\r\nThis file specifies which columns to mask, what type of fake data to generate, and handles relationships between tables to maintain referential integrity.", "Path,FullName", true, "true (ByValue)", "", "" ], [ "Locale", "Sets the locale for generating culture-specific fake data like names, addresses, and phone numbers. Defaults to \u0027en\u0027 (English).\r\nChange this when masking data for specific regions to ensure realistic replacement values that match your target environment\u0027s cultural context.", "", false, "false", "en", "" ], [ "CharacterString", "Defines the character set used when generating random strings for masked data. Defaults to alphanumeric characters.\r\nCustomize this to match your application\u0027s validation rules, such as excluding certain characters that might cause issues with your systems.", "", false, "false", "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", "" ], [ "Table", "Limits masking to specific tables within the configuration file. Accepts wildcards for pattern matching.\r\nUse this when you need to mask only certain tables during testing or phased rollouts, rather than processing all tables defined in the config.", "", false, "false", "", "" ], [ "Column", "Restricts masking to specific columns within the selected tables. Accepts wildcards for pattern matching.\r\nUseful for testing individual column masks or when you need to re-mask specific columns without affecting others.", "", false, "false", "", "" ], [ "ExcludeTable", "Skips masking for specified tables even if they\u0027re defined in the configuration file. Accepts wildcards.\r\nUse this to temporarily exclude problematic tables during troubleshooting or when certain tables need to remain unchanged in specific environments.", "", false, "false", "", "" ], [ "ExcludeColumn", "Skips masking for specified columns even if they\u0027re defined in the configuration file. Accepts wildcards.\r\nHelpful for excluding columns that are part of unique indexes or when specific columns need to remain unchanged during testing phases.", "", false, "false", "", "" ], [ "MaxValue", "Overrides the maximum length for generated string values, useful for testing with shorter data than production allows.\r\nThe smaller value between this parameter and the column\u0027s actual maximum length will be used. Primarily useful for development and testing scenarios rather than production masking.", "", false, "false", "0", "" ], [ "ModulusFactor", "Controls how frequently nullable columns are set to NULL during masking. Default value of 10 means approximately every 10th row will be NULL.\r\nAdjust this to match your production data\u0027s NULL distribution patterns, ensuring masked data maintains realistic null value frequency.", "", false, "false", "0", "" ], [ "ExactLength", "Forces masked string values to match the exact length of the original data. For example, \u0027Smith\u0027 becomes exactly 5 random characters.\r\nEnable this when your applications have strict validation rules that depend on consistent field lengths or when maintaining data formatting is critical.", "", false, "false", "False", "" ], [ "CommandTimeout", "Sets the timeout in seconds for SQL commands during the masking process. Default is 300 seconds (5 minutes).\r\nIncrease this value when masking large tables or when working with slower storage systems to prevent timeout errors during long-running operations.", "", false, "false", "0", "" ], [ "BatchSize", "Number of rows processed in each batch during the masking operation. Default is 1000 rows per batch.\r\nAdjust based on your system\u0027s memory and transaction log capacity. Smaller batches reduce memory usage but may slow processing, while larger batches improve performance but require more resources.", "", false, "false", "0", "" ], [ "Retry", "Maximum number of attempts to generate unique values when tables have unique constraints. Default is 1000 retries.\r\nIncrease this when masking tables with many unique indexes or when the range of possible values is limited, preventing failure due to constraint violations.", "", false, "false", "0", "" ], [ "DictionaryFilePath", "Path to CSV files containing deterministic value mappings for consistent masking across multiple runs or environments.\r\nUse this when you need the same original values to always map to the same masked values, maintaining referential integrity across related systems.", "", false, "false", "", "" ], [ "DictionaryExportPath", "Directory path where deterministic value mapping files will be exported after masking. Files are named [computername]_[instancename]_[database]_Dictionary.csv.\r\nUse with extreme caution as these files can be used to reverse masked values back to originals. Store securely and delete after use if not needed for consistency across environments.", "", 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": "DBCC", "CommandName": "Invoke-DbaDbDbccCheckConstraint", "Name": "Invoke-DbaDbDbccCheckConstraint", "Author": "Patrick Flynn (@sqllensman)", "Syntax": "Invoke-DbaDbDbccCheckConstraint [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-Object] \u003cString\u003e] [-AllConstraints] [-AllErrorMessages] [-NoInformationalMessages] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database when no constraint violations are found, or one object per violating row when violations are detected.\nWhen no violations exist (Path 1):\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: Name of the database that was checked\r\n- Cmd: The DBCC CHECKCONSTRAINTS command that was executed\r\n- Output: DBCC informational or status messages, or null if no messages\r\n- Table: Always null when no violations found\r\n- Constraint: Always null when no violations found\r\n- Where: Always null when no violations found\nWhen constraint violations are found (Path 2):\r\nReturns one object per violating row 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: Name of the database containing the violation\r\n- Cmd: The DBCC CHECKCONSTRAINTS command that was executed\r\n- Output: String containing previous output information\r\n- Table: Name of the table containing the violating row\r\n- Constraint: Name of the constraint that was violated\r\n- Where: The WHERE clause or criteria identifying the violating row", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaDbDbccCheckConstraint -SqlInstance SqlServer2017\nRuns the command DBCC CHECKCONSTRAINTS to check all enabled constraints on all tables for all databases for the instance SqlServer2017. Connect using Windows Authentication\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInvoke-DbaDbDbccCheckConstraint -SqlInstance SqlServer2017 -Database CurrentDB\nConnect to instance SqlServer2017 using Windows Authentication and run the command DBCC CHECKCONSTRAINTS to check all enabled constraints on all tables in the CurrentDB database.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eInvoke-DbaDbDbccCheckConstraint -SqlInstance SqlServer2017 -Database CurrentDB -Object Sometable\nConnects to CurrentDB on instance SqlServer2017 using Windows Authentication and runs the command DBCC CHECKCONSTRAINTS(SometableId) to check all enabled constraints in the table.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eInvoke-DbaDbDbccCheckConstraint -SqlInstance SqlServer2017 -Database CurrentDB -Object ConstraintId\nConnects to CurrentDB on instance SqlServer2017 using Windows Authentication and runs the command DBCC CHECKCONSTRAINTS(ConstraintId) to check the constraint with constraint_id = ConstraintId.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Invoke-DbaDbDbccCheckConstraint -SqlInstance SqlServer2017 -SqlCredential $cred -Database CurrentDB -Object TableId -AllConstraints -AllErrorMessages -NoInformationalMessages\nConnects to CurrentDB on instance SqlServer2017 using sqladmin credential and runs the command DBCC CHECKCONSTRAINTS(TableId) WITH ALL_CONSTRAINTS, ALL_ERRORMSGS, NO_INFOMSGS to check all enabled and \r\ndisabled constraints on the table with able_id = TableId. Returns all rows that violate constraints.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Invoke-DbaDbDbccCheckConstraint -WhatIf\nDisplays what will happen if command DBCC CHECKCONSTRAINTS is called against all databases on Sql1 and Sql2/sqlexpress.", "Description": "Executes DBCC CHECKCONSTRAINTS to identify rows that violate CHECK, FOREIGN KEY, and other constraints in your databases. This command helps DBAs verify data integrity after bulk imports, constraint modifications, or when troubleshooting data quality issues. You can target specific tables, individual constraints, or scan entire databases for violations. The command returns detailed information about any rows that don\u0027t meet constraint requirements, including the table, constraint name, and violating data criteria.\n\nRead more:\n - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checkconstraints-transact-sql", "Links": "https://dbatools.io/Invoke-DbaDbDbccCheckConstraint", "Synopsis": "Validates constraint integrity by checking for constraint violations in 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 check for constraint violations. Accepts multiple database names and supports 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 checking the entire instance.", "", false, "false", "", "" ], [ "Object", "Specifies the table or constraint to check for violations. Accepts either table names, constraint names, or their numeric IDs.\r\nWhen targeting a table, all enabled constraints on that table are validated. When targeting a specific constraint, only that constraint is checked.\r\nUse this when you need to focus on a specific table after bulk data operations or when investigating a known problematic constraint.", "", false, "false", "", "" ], [ "AllConstraints", "Forces checking of both enabled and disabled constraints on the specified table or all tables in the database.\r\nBy default, only enabled constraints are validated. Use this when you need to verify data integrity against all constraint definitions, including those temporarily disabled during maintenance \r\noperations.\r\nHas no effect when checking a specific constraint by name or ID.", "", false, "false", "False", "" ], [ "AllErrorMessages", "Returns all constraint violation rows instead of limiting output to the first 200 violations per constraint.\r\nUse this when you need a complete inventory of data quality issues, especially after bulk imports or when preparing comprehensive data cleanup reports.\r\nBe cautious with large tables as this can generate extensive output.", "", false, "false", "False", "" ], [ "NoInformationalMessages", "Suppresses informational messages like \"DBCC execution completed\" and processing status updates.\r\nUse this when automating constraint checks in scripts where you only want to capture actual constraint violations, not DBCC status messages.\r\nHelpful for cleaner output when processing multiple databases or integrating results into monitoring systems.", "", 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 cmdlet runs. The cmdlet is not run.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before running the cmdlet.", "cf", false, "false", "", "" ] ] }, { "Tags": "DBCC", "CommandName": "Invoke-DbaDbDbccCleanTable", "Name": "Invoke-DbaDbDbccCleanTable", "Author": "Patrick Flynn (@sqllensman)", "Syntax": "Invoke-DbaDbDbccCleanTable [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-Object] \u003cString[]\u003e] [[-BatchSize] \u003cInt32\u003e] [-NoInformationalMessages] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per table or indexed view being cleaned across all specified databases.\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- Database: Name of the database containing the object being cleaned\r\n- Object: The table or indexed view name or object ID specified for cleaning\r\n- Cmd: The DBCC CLEANTABLE command that was executed\r\n- Output: DBCC output messages, informational status, or null if operation completed silently", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaDbDbccCleanTable -SqlInstance SqlServer2017 -Database CurrentDB -Object \u0027dbo.SomeTable\u0027\nConnects to CurrentDB on instance SqlServer2017 using Windows Authentication and runs the command DBCC CLEANTABLE(\u0027CurrentDB\u0027, \u0027dbo.SomeTable\u0027) to reclaim space after variable-length columns have \r\nbeen dropped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInvoke-DbaDbDbccCleanTable -SqlInstance SqlServer2017 -Database CurrentDB -Object 34636372 -BatchSize 5000\nConnects to CurrentDB on instance SqlServer2017 using Windows Authentication and runs the command DBCC CLEANTABLE(\u0027CurrentDB\u0027, 34636372, 5000) to reclaim space from table with Table_Id = 34636372 \r\nafter variable-length columns have been dropped.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Invoke-DbaDbDbccCleanTable -SqlInstance SqlServer2017 -SqlCredential $cred -Database CurrentDB -Object \u0027dbo.SomeTable\u0027 -NoInformationalMessages\nConnects to CurrentDB on instance SqlServer2017 using sqladmin credential and runs the command DBCC CLEANTABLE(\u0027CurrentDB\u0027, \u0027dbo.SomeTable\u0027) WITH NO_INFOMSGS to reclaim space after variable-length \r\ncolumns have been dropped.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Invoke-DbaDbDbccCleanTable -Object \u0027dbo.SomeTable\u0027 -BatchSize 5000\nRuns the command DBCC CLEANTABLE(\u0027DatabaseName\u0027, \u0027dbo.SomeTable\u0027, 5000) against all databases on Sql1 and Sql2/sqlexpress.", "Description": "Executes DBCC CLEANTABLE to reclaim disk space after variable-length columns (varchar, nvarchar, varbinary, text, ntext, image, xml, or CLR user-defined types) have been dropped from tables or indexed views.\n\nWhen you drop variable-length columns, SQL Server doesn\u0027t immediately reclaim the space those columns occupied. This function runs the necessary DBCC command to physically remove that unused space and compact the remaining data, which can significantly reduce table size and improve performance.\n\nThe function accepts either table names (like \u0027dbo.TableName\u0027) or table object IDs for processing. You can control the operation through batch processing to minimize impact on production systems, and optionally suppress informational messages for cleaner output.\n\nRead more:\n - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-cleantable-transact-sql", "Links": "https://dbatools.io/Invoke-DbaDbDbccCleanTable", "Synopsis": "Reclaims disk space from dropped variable-length columns in tables and indexed views", "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 in the clean table operation. Accepts multiple database names.\r\nWhen omitted, the operation runs against all accessible databases on the instance.\r\nUse this to target specific databases where you know variable-length columns have been dropped recently.", "", false, "false", "", "" ], [ "Object", "Specifies the table or indexed view names to clean, or their object IDs for more precise targeting.\r\nAccepts schema-qualified names like \u0027dbo.TableName\u0027 or numeric object IDs like 34636372.\r\nThis parameter is required since DBCC CLEANTABLE must target specific objects, not entire databases.", "", false, "false", "", "" ], [ "BatchSize", "Controls how many rows are processed per transaction during the clean operation.\r\nUse smaller batch sizes (like 5000-10000) on production systems to reduce lock duration and transaction log impact.\r\nWhen omitted, processes the entire table in a single transaction which is faster but holds locks longer.", "", false, "false", "0", "" ], [ "NoInformationalMessages", "Suppresses informational messages from the DBCC CLEANTABLE output, showing only errors and warnings.\r\nUse this in automated scripts or when processing multiple tables to reduce console output volume.\r\nEquivalent to adding WITH NO_INFOMSGS to the DBCC command.", "", 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 cmdlet runs. The cmdlet is not run.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before running the cmdlet.", "cf", false, "false", "", "" ] ] }, { "Tags": "DBCC", "CommandName": "Invoke-DbaDbDbccUpdateUsage", "Name": "Invoke-DbaDbDbccUpdateUsage", "Author": "Patrick Flynn (@sqllensman)", "Syntax": "Invoke-DbaDbDbccUpdateUsage [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-Table] \u003cString\u003e] [[-Index] \u003cString\u003e] [-NoInformationalMessages] [-CountRows] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per result row returned by the DBCC UPDATEUSAGE command executed against each database.\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: The database name where DBCC UPDATEUSAGE was executed\r\n- Cmd: The complete DBCC UPDATEUSAGE command that was executed\r\n- Output: The raw output message(s) from the DBCC command; usually informational messages about pages and rows updated", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaDbDbccUpdateUsage -SqlInstance SqlServer2017\nRuns the command DBCC UPDATEUSAGE to update the page or row counts or both for all objects in all databases for the instance SqlServer2017. Connect using Windows Authentication\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInvoke-DbaDbDbccUpdateUsage -SqlInstance SqlServer2017 -Database CurrentDB\nRuns the command DBCC UPDATEUSAGE to update the page or row counts or both for all objects in the CurrentDB database for the instance SqlServer2017. Connect using Windows Authentication\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eInvoke-DbaDbDbccUpdateUsage -SqlInstance SqlServer2017 -Database CurrentDB -Table Sometable\nConnects to CurrentDB on instance SqlServer2017 using Windows Authentication and runs the command DBCC UPDATEUSAGE(SometableId) to update the page or row counts for all indexes in the table.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Invoke-DbaDbDbccUpdateUsage -SqlInstance SqlServer2017 -SqlCredential $cred -Database CurrentDB -Table \u0027SometableId -Index IndexName -NoInformationalMessages -CountRows\nConnects to CurrentDB on instance SqlServer2017 using sqladmin credential and runs the command DBCC UPDATEUSAGE(SometableId, IndexName) WITH NO_INFOMSGS, COUNT_ROWS to update the page or row counts.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e\u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Invoke-DbaDbDbccUpdateUsage -WhatIf\nDisplays what will happen if command DBCC UPDATEUSAGE is called against all databases on Sql1 and Sql2/sqlexpress.", "Description": "Executes the DBCC UPDATEUSAGE command to identify and fix metadata inconsistencies in catalog views that track space usage information. When these internal counters become inaccurate, system procedures like sp_spaceused return incorrect database and table size reports, making capacity planning and troubleshooting difficult.\n\nThis command is essential when you notice discrepancies between actual database file sizes and reported space usage, or when sp_spaceused shows unexpected results after bulk operations, index rebuilds, or database migrations. The function can target entire instances, specific databases, individual tables, or even single indexes depending on your troubleshooting needs.\n\nCommon scenarios include fixing space reports after large data imports, resolving inconsistencies following database restores, and correcting metadata after index maintenance operations. The command reads actual page allocations and updates the system catalog views to reflect accurate usage statistics.\n\nRead more:\n - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-updateusage-transact-sql", "Links": "https://dbatools.io/Invoke-DbaDbDbccUpdateUsage", "Synopsis": "Corrects page and row count inaccuracies in SQL Server catalog views using DBCC UPDATEUSAGE", "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 update usage statistics for. Accepts database names or IDs.\r\nWhen omitted, DBCC UPDATEUSAGE runs against all accessible databases on the instance.\r\nUse this to target specific databases when you know which ones have inaccurate space usage reports.", "", false, "false", "", "" ], [ "Table", "Specifies a single table or indexed view to update usage statistics for. Accepts table names or object IDs.\r\nWhen omitted, DBCC UPDATEUSAGE processes all tables and indexed views in the specified database(s).\r\nUse this when sp_spaceused reports incorrect sizes for a specific table after bulk operations or index maintenance.", "", false, "false", "", "" ], [ "Index", "Specifies a single index to update usage statistics for. Accepts index names or index IDs.\r\nRequires the Table parameter to be specified and updates statistics only for that specific index.\r\nUse this for targeted correction when you know a particular index has inaccurate metadata after rebuilds or reorganization.", "", false, "false", "", "" ], [ "NoInformationalMessages", "Suppresses informational messages during DBCC UPDATEUSAGE execution using the NO_INFOMSGS option.\r\nUse this in automated scripts or when processing many objects to reduce output volume and focus on actual problems.", "", false, "false", "False", "" ], [ "CountRows", "Forces DBCC UPDATEUSAGE to recalculate and update row counts in addition to page counts using the COUNT_ROWS option.\r\nUse this when sp_spaceused shows incorrect row counts, typically after bulk insert/delete operations or database restores.\r\nNote that this option increases execution time as SQL Server must physically count all rows in affected tables.", "", 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 cmdlet runs. The cmdlet is not run.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before running the cmdlet.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Encryption", "Decrypt", "Utility" ], "CommandName": "Invoke-DbaDbDecryptObject", "Name": "Invoke-DbaDbDecryptObject", "Author": "Sander Stad (@sqlstad), sqlstad.nl", "Syntax": "Invoke-DbaDbDecryptObject [-SqlInstance] \u003cDbaInstanceParameter\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Database] \u003cObject[]\u003e [[-ObjectName] \u003cString[]\u003e] [[-EncodingType] \u003cString\u003e] [[-ExportDestination] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per encrypted database object that is successfully decrypted. If no encrypted objects are found, 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: The name of the database containing the encrypted object\r\n- Type: The type of database object (StoredProcedure, UserDefinedFunction, View, or Trigger)\r\n- Schema: The schema name containing the object\r\n- Name: The object name\r\n- FullName: The fully qualified name in schema.name format\r\n- Script: The decrypted T-SQL source code of the object\r\n- OutputFile: The file path where the script was exported; null if -ExportDestination was not specified and results were displayed in console only", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaDbDecryptObject -SqlInstance SQLDB1 -Database DB1 -ObjectName Function1\nDecrypt object \"Function1\" in DB1 of instance SQLDB1 and output the data to the user.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInvoke-DbaDbDecryptObject -SqlInstance SQLDB1 -Database DB1 -ObjectName Function1 -ExportDestination C:\\temp\\decrypt\nDecrypt object \"Function1\" in DB1 of instance SQLDB1 and output the data to the folder \"C:\\temp\\decrypt\".\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eInvoke-DbaDbDecryptObject -SqlInstance SQLDB1 -Database DB1 -ExportDestination C:\\temp\\decrypt\nDecrypt all objects in DB1 of instance SQLDB1 and output the data to the folder \"C:\\temp\\decrypt\"\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eInvoke-DbaDbDecryptObject -SqlInstance SQLDB1 -Database DB1 -ObjectName Function1, Function2\nDecrypt objects \"Function1\" and \"Function2\" and output the data to the user.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e\"SQLDB1\" | Invoke-DbaDbDecryptObject -Database DB1 -ObjectName Function1, Function2\nDecrypt objects \"Function1\" and \"Function2\" and output the data to the user using a pipeline for the instance.", "Description": "Recovers the original source code from encrypted database objects when the original scripts have been lost or are unavailable. This command uses the Dedicated Admin Connection (DAC) to access binary data from sys.sysobjvalues and performs XOR decryption to retrieve the original T-SQL code.\n\nThis is particularly useful in disaster recovery scenarios where you need to recreate objects but only have access to the encrypted versions in the database. The function can decrypt stored procedures, user-defined functions (scalar, inline, table-valued), views, and triggers.\n\nThe command outputs results to the console by default, with an option to export all decrypted objects to organized .sql files in a folder structure.\n\nTo connect to a remote SQL instance, the remote dedicated administrator connection option must be configured. The binary versions of encrypted objects can only be retrieved using a DAC connection.\nYou can check the remote DAC connection with:\n\u0027Get-DbaSpConfigure -SqlInstance [yourinstance] -ConfigName RemoteDacConnectionsEnabled\u0027\nThe ConfiguredValue should be 1.\n\nThe local DAC connection is enabled by default.\n\nTo enable remote DAC connections, use:\n\u0027Set-DbaSpConfigure -SqlInstance [yourinstance] -ConfigName RemoteDacConnectionsEnabled -Value 1\u0027\nIn some cases you may need to restart the SQL Server instance after enabling this setting.", "Links": "https://dbatools.io/Invoke-DbaDbDecryptObject", "Synopsis": "Decrypts encrypted stored procedures, functions, views, and triggers using Dedicated Admin Connection (DAC)", "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 contain the encrypted objects you want to decrypt. Accepts multiple database names.\r\nUse this to target specific databases instead of searching across all databases on the instance.", "", true, "false", "", "" ], [ "ObjectName", "Specifies the names of encrypted objects to decrypt (stored procedures, functions, views, or triggers). Accepts multiple object names.\r\nWhen omitted, all encrypted objects in the specified databases will be decrypted. Use this to target specific objects when you only need a few items recovered.", "", false, "false", "", "" ], [ "EncodingType", "Determines the text encoding used during the XOR decryption process to convert binary data back to readable T-SQL code. Defaults to ASCII.\r\nUse UTF8 when dealing with databases that contain Unicode characters in object definitions or when ASCII decryption produces garbled text.", "", false, "false", "ASCII", "ASCII,UTF8" ], [ "ExportDestination", "Specifies the folder path where decrypted T-SQL scripts will be saved as individual .sql files.\r\nWhen specified, creates an organized folder structure by instance, database, and object type (e.g., C:\\temp\\decrypt\\SQLDB1\\DB1\\StoredProcedure). When omitted, results are displayed in the console \r\nonly.", "", 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": "LogShipping", "CommandName": "Invoke-DbaDbLogShipping", "Name": "Invoke-DbaDbLogShipping", "Author": "Sander Stad (@sqlstad), sqlstad.nl + Claude (Azure blob storage support)", "Syntax": "Invoke-DbaDbLogShipping [-SourceSqlInstance] \u003cDbaInstanceParameter\u003e [-DestinationSqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [[-SourceCredential] \u003cPSCredential\u003e] [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-DestinationCredential] \u003cPSCredential\u003e] [-Database] \u003cObject[]\u003e [[-SharedPath] \u003cString\u003e] [[-LocalPath] \u003cString\u003e] [[-AzureBaseUrl] \u003cString\u003e] [[-AzureCredential] \u003cString\u003e] [[-BackupJob] \u003cString\u003e] [[-BackupRetention] \u003cInt32\u003e] [[-BackupSchedule] \u003cString\u003e] [-BackupScheduleDisabled] [[-BackupScheduleFrequencyType] \u003cObject\u003e] [[-BackupScheduleFrequencyInterval] \r\n\u003cObject[]\u003e] [[-BackupScheduleFrequencySubdayType] \u003cObject\u003e] [[-BackupScheduleFrequencySubdayInterval] \u003cInt32\u003e] [[-BackupScheduleFrequencyRelativeInterval] \u003cObject\u003e] [[-BackupScheduleFrequencyRecurrenceFactor] \u003cInt32\u003e] [[-BackupScheduleStartDate] \u003cString\u003e] [[-BackupScheduleEndDate] \u003cString\u003e] [[-BackupScheduleStartTime] \u003cString\u003e] [[-BackupScheduleEndTime] \u003cString\u003e] [[-BackupThreshold] \u003cInt32\u003e] [-CompressBackup] [[-CopyDestinationFolder] \u003cString\u003e] [[-CopyJob] \u003cString\u003e] [[-CopyRetention] \u003cInt32\u003e] [[-CopySchedule] \u003cString\u003e] [-CopyScheduleDisabled] [[-CopyScheduleFrequencyType] \u003cObject\u003e] \r\n[[-CopyScheduleFrequencyInterval] \u003cObject[]\u003e] [[-CopyScheduleFrequencySubdayType] \u003cObject\u003e] [[-CopyScheduleFrequencySubdayInterval] \u003cInt32\u003e] [[-CopyScheduleFrequencyRelativeInterval] \u003cObject\u003e] [[-CopyScheduleFrequencyRecurrenceFactor] \u003cInt32\u003e] [[-CopyScheduleStartDate] \u003cString\u003e] [[-CopyScheduleEndDate] \u003cString\u003e] [[-CopyScheduleStartTime] \u003cString\u003e] [[-CopyScheduleEndTime] \u003cString\u003e] [-DisconnectUsers] [[-FullBackupPath] \u003cString\u003e] [-GenerateFullBackup] [[-HistoryRetention] \u003cInt32\u003e] [-NoRecovery] [-NoInitialization] [[-PrimaryMonitorServer] \u003cString\u003e] [[-PrimaryMonitorCredential] \u003cPSCredential\u003e] \r\n[[-PrimaryMonitorServerSecurityMode] \u003cObject\u003e] [-PrimaryThresholdAlertEnabled] [[-RestoreDataFolder] \u003cString\u003e] [[-RestoreLogFolder] \u003cString\u003e] [[-RestoreDelay] \u003cInt32\u003e] [[-RestoreAlertThreshold] \u003cInt32\u003e] [[-RestoreJob] \u003cString\u003e] [[-RestoreRetention] \u003cInt32\u003e] [[-RestoreSchedule] \u003cString\u003e] [-RestoreScheduleDisabled] [[-RestoreScheduleFrequencyType] \u003cObject\u003e] [[-RestoreScheduleFrequencyInterval] \u003cObject[]\u003e] [[-RestoreScheduleFrequencySubdayType] \u003cObject\u003e] [[-RestoreScheduleFrequencySubdayInterval] \u003cInt32\u003e] [[-RestoreScheduleFrequencyRelativeInterval] \u003cObject\u003e] \r\n[[-RestoreScheduleFrequencyRecurrenceFactor] \u003cInt32\u003e] [[-RestoreScheduleStartDate] \u003cString\u003e] [[-RestoreScheduleEndDate] \u003cString\u003e] [[-RestoreScheduleStartTime] \u003cString\u003e] [[-RestoreScheduleEndTime] \u003cString\u003e] [[-RestoreThreshold] \u003cInt32\u003e] [[-SecondaryDatabasePrefix] \u003cString\u003e] [[-SecondaryDatabaseSuffix] \u003cString\u003e] [[-SecondaryMonitorServer] \u003cString\u003e] [[-SecondaryMonitorCredential] \u003cPSCredential\u003e] [[-SecondaryMonitorServerSecurityMode] \u003cObject\u003e] [-SecondaryThresholdAlertEnabled] [-Standby] [[-StandbyDirectory] \u003cString\u003e] [-UseExistingFullBackup] [[-UseBackupFolder] \u003cString\u003e] [-Force] \r\n[-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database that was configured for log shipping, containing setup results and status information.\nProperties:\r\n- PrimaryInstance: The full SQL Server instance name (computer\\instance) of the primary/source server\r\n- SecondaryInstance: The full SQL Server instance name (computer\\instance) of the secondary/destination server\r\n- PrimaryDatabase: Name of the database on the primary instance that was configured for log shipping\r\n- SecondaryDatabase: Name of the database on the secondary instance (may have prefix/suffix applied)\r\n- Result: Setup status for this database configuration - \"Success\" if all log shipping components were created successfully, \"Failed\" if any step failed\r\n- Comment: Additional information about the setup result, typically populated with error details when Result is \"Failed\"", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$params = @{\n\u003e\u003e SourceSqlInstance = \u0027sql1\u0027\r\n\u003e\u003e DestinationSqlInstance = \u0027sql2\u0027\r\n\u003e\u003e Database = \u0027db1\u0027\r\n\u003e\u003e SharedPath= \u0027\\\\sql1\\logshipping\u0027\r\n\u003e\u003e LocalPath= \u0027D:\\Data\\logshipping\u0027\r\n\u003e\u003e BackupScheduleFrequencyType = \u0027daily\u0027\r\n\u003e\u003e BackupScheduleFrequencyInterval = 1\r\n\u003e\u003e CompressBackup = $true\r\n\u003e\u003e CopyScheduleFrequencyType = \u0027daily\u0027\r\n\u003e\u003e CopyScheduleFrequencyInterval = 1\r\n\u003e\u003e GenerateFullBackup = $true\r\n\u003e\u003e RestoreScheduleFrequencyType = \u0027daily\u0027\r\n\u003e\u003e RestoreScheduleFrequencyInterval = 1\r\n\u003e\u003e SecondaryDatabaseSuffix = \u0027LS\u0027\r\n\u003e\u003e CopyDestinationFolder = \u0027\\\\sql2\\logshippingdest\u0027\r\n\u003e\u003e Force = $true\r\n\u003e\u003e }\r\n\u003e\u003e\r\nPS C:\\\u003e Invoke-DbaDbLogShipping @params\nSets up log shipping for database \"db1\" with the backup path to a network share allowing local backups.\r\nIt creates daily schedules for the backup, copy and restore job with all the defaults to be executed every 15 minutes daily.\r\nThe secondary database will be called \"db1_LS\".\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$params = @{\n\u003e\u003e SourceSqlInstance = \u0027sql1\u0027\r\n\u003e\u003e DestinationSqlInstance = \u0027sql2\u0027\r\n\u003e\u003e Database = \u0027db1\u0027\r\n\u003e\u003e SharedPath= \u0027\\\\sql1\\logshipping\u0027\r\n\u003e\u003e GenerateFullBackup = $true\r\n\u003e\u003e Force = $true\r\n\u003e\u003e }\r\n\u003e\u003e\r\nPS C:\\\u003e Invoke-DbaDbLogShipping @params\nSets up log shipping with all defaults except that a backup file is generated.\r\nThe script will show a message that the copy destination has not been supplied and asks if you want to use the default which would be the backup directory of the secondary server with the folder \r\n\"logshipping\" i.e. \"D:\\SQLBackup\\Logshiping\".\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e# First, create the SAS credential on both instances\nPS C:\\\u003e $azureUrl = \"https://mystorageaccount.blob.core.windows.net/logshipping\"\r\nPS C:\\\u003e $cred = Get-Credential -Message \"Paste SAS token (without leading ?) in password field\" -UserName \"SHARED ACCESS SIGNATURE\"\r\nPS C:\\\u003e $splatCred = @{\r\n\u003e\u003e SqlInstance = \"sql1\", \"sql2\"\r\n\u003e\u003e Name = $azureUrl\r\n\u003e\u003e Identity = $cred.UserName\r\n\u003e\u003e SecurePassword = $cred.Password\r\n\u003e\u003e }\r\nPS C:\\\u003e New-DbaCredential @splatCred\r\nPS C:\\\u003e\r\nPS C:\\\u003e # Then set up log shipping\r\nPS C:\\\u003e $splatLogShipping = @{\r\n\u003e\u003e SourceSqlInstance = \"sql1\"\r\n\u003e\u003e DestinationSqlInstance = \"sql2\"\r\n\u003e\u003e Database = \"db1\"\r\n\u003e\u003e AzureBaseUrl = $azureUrl\r\n\u003e\u003e BackupScheduleFrequencyType = \"daily\"\r\n\u003e\u003e BackupScheduleFrequencyInterval = 1\r\n\u003e\u003e RestoreScheduleFrequencyType = \"daily\"\r\n\u003e\u003e RestoreScheduleFrequencyInterval = 1\r\n\u003e\u003e GenerateFullBackup = $true\r\n\u003e\u003e Force = $true\r\n\u003e\u003e }\r\nPS C:\\\u003e Invoke-DbaDbLogShipping @splatLogShipping\nSets up log shipping for database \"db1\" to Azure blob storage using SAS token authentication.", "Description": "Invoke-DbaDbLogShipping helps to easily set up log shipping for one or more databases.\n\nThis function will make a lot of decisions for you assuming you want default values like a daily interval for the schedules with a 15 minute interval on the day.\nThere are some settings that cannot be made by the function and they need to be prepared before the function is executed.\n\nThe following settings need to be made before log shipping can be initiated:\n- Backup destination (the folder and the privileges)\n- Copy destination (the folder and the privileges)\n\n* Privileges\nMake sure your agent service on both the primary and the secondary instance is an Active Directory account.\nAlso have the credentials ready to set the folder permissions\n\n** Network share\nThe backup destination needs to be shared and have the share privileges of FULL CONTROL to Everyone.\n\n** NTFS permissions\nThe backup destination must have at least read/write permissions for the primary instance agent account.\nThe backup destination must have at least read permissions for the secondary instance agent account.\nThe copy destination must have at least read/write permission for the secondary instance agent account.", "Links": "https://dbatools.io/Invoke-DbaDbLogShipping", "Synopsis": "Invoke-DbaDbLogShipping sets up log shipping for one or more databases", "Availability": "Windows, Linux, macOS", "Params": [ [ "SourceSqlInstance", "Source SQL Server instance which contains the databases to be log shipped.\r\nYou must have sysadmin access and server version must be SQL Server version 2000 or greater.", "SourceServerInstance,SourceSqlServerSqlServer,Source", true, "false", "", "" ], [ "DestinationSqlInstance", "Destination SQL Server instance which contains the databases to be log shipped.\r\nYou must have sysadmin access and server version must be SQL Server version 2000 or greater.", "DestinationServerInstance,DestinationSqlServer,Destination", 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", "", "" ], [ "SourceCredential", "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", "", "" ], [ "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", "", "" ], [ "DestinationCredential", "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 configure for log shipping. The database must be in FULL recovery model.\r\nUse this to target specific databases rather than setting up log shipping for all databases on the source instance.", "", true, "true (ByValue)", "", "" ], [ "SharedPath", "Specifies the network share path where transaction log backup files will be stored. Must be in UNC format (\\\\server\\\\share).\r\nThe function automatically creates a subdirectory for each database under this path. Both source and destination instances need access to this location.\r\nMutually exclusive with AzureBaseUrl parameter.", "BackupNetworkPath", false, "false", "", "" ], [ "LocalPath", "Sets the local backup path on the source server when different from the shared path.\r\nUse this when the source server accesses the backup location via a local path but other servers need to access it via the network share.\r\nNot applicable when using Azure blob storage (AzureBaseUrl).", "BackupLocalPath", false, "false", "", "" ], [ "AzureBaseUrl", "Specifies the Azure blob storage container URL where transaction log backups will be stored.\r\nFormat: https://storageaccount.blob.core.windows.net/container/\r\nWhen specified, traditional file-based copy jobs are skipped as backups go directly to Azure blob storage.\r\nMutually exclusive with SharedPath parameter. Requires SQL Server 2012 or later.", "", false, "false", "", "" ], [ "AzureCredential", "Specifies the SQL Server credential name for Azure storage access. When omitted, uses SAS token authentication with a credential named to match the AzureBaseUrl.\r\nThe credential must exist on both source and destination SQL Server instances before setting up log shipping.", "", false, "false", "", "" ], [ "BackupJob", "Specifies the prefix for the SQL Agent backup job name that performs transaction log backups.\r\nThe database name is automatically appended to create the full job name. Defaults to \u0027LSBackup_\u0027 if not specified.", "", false, "false", "", "" ], [ "BackupRetention", "Sets how long backup files are retained before deletion, specified in minutes.\r\nDefaults to 4320 minutes (72 hours). Consider storage capacity and recovery requirements when setting this value.", "", false, "false", "0", "" ], [ "BackupSchedule", "Name of the backup schedule created for the backup job.\r\nThe parameter works as a prefix where the name of the database will be added to the backup job schedule name.\r\nDefault is \"LSBackupSchedule_[databasename]\"", "", false, "false", "", "" ], [ "BackupScheduleDisabled", "Creates the backup job schedule in a disabled state, preventing automatic execution.\r\nUse this when you want to manually control when log shipping backup jobs start running.", "", false, "false", "False", "" ], [ "BackupScheduleFrequencyType", "Controls how often the backup job runs. Accepts \u0027Daily\u0027 (most common), \u0027AgentStart\u0027, or \u0027IdleComputer\u0027.\r\nDaily scheduling allows for regular transaction log backups to maintain the log shipping chain.", "", false, "false", "", "Daily,Weekly,AgentStart,IdleComputer" ], [ "BackupScheduleFrequencyInterval", "The number of type periods to occur between each execution of the backup job.", "", false, "false", "", "" ], [ "BackupScheduleFrequencySubdayType", "Specifies the units for the sub-day FrequencyInterval.\r\nAllowed values are \"Time\", \"Seconds\", \"Minutes\", \"Hours\"", "", false, "false", "", "Time,Seconds,Minutes,Hours" ], [ "BackupScheduleFrequencySubdayInterval", "Specifies the interval between backup job executions within a day when using Minutes, Seconds, or Hours frequency.\r\nFor example, setting 15 with FrequencySubdayType of \u0027Minutes\u0027 creates backups every 15 minutes.", "", false, "false", "0", "" ], [ "BackupScheduleFrequencyRelativeInterval", "A job\u0027s occurrence of FrequencyInterval in each month, if FrequencyInterval is 32 (monthlyrelative).", "", false, "false", "", "Unused,First,Second,Third,Fourth,Last" ], [ "BackupScheduleFrequencyRecurrenceFactor", "The number of weeks or months between the scheduled execution of a job. FrequencyRecurrenceFactor is used only if FrequencyType is 8, \"Weekly\", 16, \"Monthly\", 32 or \"MonthlyRelative\".", "", false, "false", "0", "" ], [ "BackupScheduleStartDate", "The date on which execution of a job can begin.", "", false, "false", "", "" ], [ "BackupScheduleEndDate", "The date on which execution of a job can stop.", "", false, "false", "", "" ], [ "BackupScheduleStartTime", "The time on any day to begin execution of a job. Format HHMMSS / 24 hour clock.\r\nExample: \u0027010000\u0027 for 01:00:00 AM.\r\nExample: \u0027140000\u0027 for 02:00:00 PM.", "", false, "false", "", "" ], [ "BackupScheduleEndTime", "The time on any day to end execution of a job. Format HHMMSS / 24 hour clock.\r\nExample: \u0027010000\u0027 for 01:00:00 AM.\r\nExample: \u0027140000\u0027 for 02:00:00 PM.", "", false, "false", "", "" ], [ "BackupThreshold", "Sets the alert threshold in minutes for detecting backup delays. An alert is raised if no backup occurs within this timeframe.\r\nDefaults to 60 minutes. Use shorter intervals for critical databases requiring frequent log backups.", "", false, "false", "0", "" ], [ "CompressBackup", "Enables backup compression for transaction log backups to reduce file size and network transfer time.\r\nOnly available on SQL Server 2008 and later. Uses server default compression setting if not specified.", "", false, "false", "False", "" ], [ "CopyDestinationFolder", "Specifies the destination folder path where backup files are copied on the secondary server.\r\nThe function creates a database-specific subdirectory under this path. Defaults to the secondary server\u0027s backup directory if not provided.", "", false, "false", "", "" ], [ "CopyJob", "Name of the copy job that will be created in the SQL Server agent.\r\nThe parameter works as a prefix where the name of the database will be added to the copy job name.\r\nThe default is \"LSBackup_[databasename]\"", "", false, "false", "", "" ], [ "CopyRetention", "The copy retention period in minutes. Default is 4320 / 72 hours", "", false, "false", "0", "" ], [ "CopySchedule", "Name of the backup schedule created for the copy job.\r\nThe parameter works as a prefix where the name of the database will be added to the copy job schedule name.\r\nDefault is \"LSCopy_[DestinationServerName]_[DatabaseName]\"", "", false, "false", "", "" ], [ "CopyScheduleDisabled", "Parameter to set the copy schedule to disabled upon creation.\r\nBy default the schedule is enabled.", "", false, "false", "False", "" ], [ "CopyScheduleFrequencyType", "A value indicating when a job is to be executed.\r\nAllowed values are \"Daily\", \"AgentStart\", \"IdleComputer\"", "", false, "false", "", "Daily,Weekly,AgentStart,IdleComputer" ], [ "CopyScheduleFrequencyInterval", "The number of type periods to occur between each execution of the copy job.", "", false, "false", "", "" ], [ "CopyScheduleFrequencySubdayType", "Specifies the units for the subday FrequencyInterval.\r\nAllowed values are \"Time\", \"Seconds\", \"Minutes\", \"Hours\"", "", false, "false", "", "Time,Seconds,Minutes,Hours" ], [ "CopyScheduleFrequencySubdayInterval", "The number of subday type periods to occur between each execution of the copy job.", "", false, "false", "0", "" ], [ "CopyScheduleFrequencyRelativeInterval", "A job\u0027s occurrence of FrequencyInterval in each month, if FrequencyInterval is 32 (monthlyrelative).", "", false, "false", "", "Unused,First,Second,Third,Fourth,Last" ], [ "CopyScheduleFrequencyRecurrenceFactor", "The number of weeks or months between the scheduled execution of a job. FrequencyRecurrenceFactor is used only if FrequencyType is 8, \"Weekly\", 16, \"Monthly\", 32 or \"MonthlyRelative\".", "", false, "false", "0", "" ], [ "CopyScheduleStartDate", "The date on which execution of a job can begin.", "", false, "false", "", "" ], [ "CopyScheduleEndDate", "The date on which execution of a job can stop.", "", false, "false", "", "" ], [ "CopyScheduleStartTime", "The time on any day to begin execution of a job. Format HHMMSS / 24 hour clock.\r\nExample: \u0027010000\u0027 for 01:00:00 AM.\r\nExample: \u0027140000\u0027 for 02:00:00 PM.", "", false, "false", "", "" ], [ "CopyScheduleEndTime", "The time on any day to end execution of a job. Format HHMMSS / 24 hour clock.\r\nExample: \u0027010000\u0027 for 01:00:00 AM.\r\nExample: \u0027140000\u0027 for 02:00:00 PM.", "", false, "false", "", "" ], [ "DisconnectUsers", "Forces disconnection of users from the secondary database during transaction log restore operations.\r\nUse this with standby mode when you need to ensure restores complete successfully despite active connections.", "", false, "false", "False", "" ], [ "FullBackupPath", "Specifies the path to an existing full database backup to initialize the secondary database.\r\nUse this when you have a recent backup available and want to avoid creating a new full backup for initialization.", "", false, "false", "", "" ], [ "GenerateFullBackup", "Creates a new full backup of the source database and restores it to initialize the secondary database.\r\nUse this when no existing backup is available or when you want to ensure the secondary starts with the most current data.", "", false, "false", "False", "" ], [ "HistoryRetention", "Sets how long log shipping history information is kept in the monitor server, specified in minutes.\r\nDefaults to 14420 minutes (approximately 10 days). Longer retention provides more historical data for troubleshooting.", "", false, "false", "0", "" ], [ "NoRecovery", "Keeps the secondary database in NORECOVERY mode, making it unavailable for read access but ready for continuous log restores.\r\nThis is the default mode and maintains the fastest restore performance for log shipping.", "", false, "false", "False", "" ], [ "NoInitialization", "Skips secondary database initialization, assuming the database already exists in NORECOVERY mode on the destination.\r\nUse this when you have manually restored the database or used a different method to initialize it.", "", false, "false", "False", "" ], [ "PrimaryMonitorServer", "Specifies the SQL Server instance that monitors the primary server\u0027s log shipping operations.\r\nDefaults to the source instance itself. Use a dedicated monitor server in production environments for centralized monitoring.", "", false, "false", "", "" ], [ "PrimaryMonitorCredential", "Allows you to login to enter a secure credential. Only needs to be used when the PrimaryMonitorServerSecurityMode is 0 or \"sqlserver\"\r\nTo use: $scred = Get-Credential, then pass $scred object to the -PrimaryMonitorCredential parameter.", "", false, "false", "", "" ], [ "PrimaryMonitorServerSecurityMode", "The security mode used to connect to the monitor server for the primary server. Allowed values are 0, \"sqlserver\", 1, \"windows\"\r\nThe default is 1 or Windows.", "", false, "false", "", "0,sqlserver,1,windows" ], [ "PrimaryThresholdAlertEnabled", "Enables the Threshold alert for the primary database", "", false, "false", "False", "" ], [ "RestoreDataFolder", "Sets the destination folder for database data files during secondary database initialization.\r\nOnly used with GenerateFullBackup or UseExistingFullBackup. Defaults to the secondary instance\u0027s default data directory if not specified.", "", false, "false", "", "" ], [ "RestoreLogFolder", "Sets the destination folder for database log files during secondary database initialization.\r\nOnly used with GenerateFullBackup or UseExistingFullBackup. Defaults to the secondary instance\u0027s default log directory if not specified.", "", false, "false", "", "" ], [ "RestoreDelay", "Introduces a delay in minutes before applying transaction log restores on the secondary database.\r\nDefaults to 0 (no delay). Use this to create a time buffer for recovering from accidental data changes on the primary.", "", false, "false", "0", "" ], [ "RestoreAlertThreshold", "Sets the alert threshold in minutes for detecting restore operation delays on the secondary database.\r\nAn alert is generated if no restore occurs within this timeframe. Defaults to 45 minutes.", "", false, "false", "0", "" ], [ "RestoreJob", "Name of the restore job that will be created in the SQL Server agent.\r\nThe parameter works as a prefix where the name of the database will be added to the restore job name.\r\nThe default is \"LSRestore_[databasename]\"", "", false, "false", "", "" ], [ "RestoreRetention", "The backup retention period in minutes. Default is 4320 / 72 hours", "", false, "false", "0", "" ], [ "RestoreSchedule", "Name of the backup schedule created for the restore job.\r\nThe parameter works as a prefix where the name of the database will be added to the restore job schedule name.\r\nDefault is \"LSRestore_[DestinationServerName]_[DatabaseName]\"", "", false, "false", "", "" ], [ "RestoreScheduleDisabled", "Parameter to set the restore schedule to disabled upon creation.\r\nBy default the schedule is enabled.", "", false, "false", "False", "" ], [ "RestoreScheduleFrequencyType", "A value indicating when a job is to be executed.\r\nAllowed values are \"Daily\", \"AgentStart\", \"IdleComputer\"", "", false, "false", "", "Daily,Weekly,AgentStart,IdleComputer" ], [ "RestoreScheduleFrequencyInterval", "The number of type periods to occur between each execution of the restore job.", "", false, "false", "", "" ], [ "RestoreScheduleFrequencySubdayType", "Specifies the units for the subday FrequencyInterval.\r\nAllowed values are \"Time\", \"Seconds\", \"Minutes\", \"Hours\"", "", false, "false", "", "Time,Seconds,Minutes,Hours" ], [ "RestoreScheduleFrequencySubdayInterval", "The number of subday type periods to occur between each execution of the restore job.", "", false, "false", "0", "" ], [ "RestoreScheduleFrequencyRelativeInterval", "A job\u0027s occurrence of FrequencyInterval in each month, if FrequencyInterval is 32 (monthlyrelative).", "", false, "false", "", "Unused,First,Second,Third,Fourth,Last" ], [ "RestoreScheduleFrequencyRecurrenceFactor", "The number of weeks or months between the scheduled execution of a job. FrequencyRecurrenceFactor is used only if FrequencyType is 8, \"Weekly\", 16, \"Monthly\", 32 or \"MonthlyRelative\".", "", false, "false", "0", "" ], [ "RestoreScheduleStartDate", "The date on which execution of a job can begin.", "", false, "false", "", "" ], [ "RestoreScheduleEndDate", "The date on which execution of a job can stop.", "", false, "false", "", "" ], [ "RestoreScheduleStartTime", "The time on any day to begin execution of a job. Format HHMMSS / 24 hour clock.\r\nExample: \u0027010000\u0027 for 01:00:00 AM.\r\nExample: \u0027140000\u0027 for 02:00:00 PM.", "", false, "false", "", "" ], [ "RestoreScheduleEndTime", "The time on any day to end execution of a job. Format HHMMSS / 24 hour clock.\r\nExample: \u0027010000\u0027 for 01:00:00 AM.\r\nExample: \u0027140000\u0027 for 02:00:00 PM.", "", false, "false", "", "" ], [ "RestoreThreshold", "Specifies the maximum time in minutes allowed between restore operations before triggering an alert.\r\nDefaults to 45 minutes. Set this based on your RTO requirements and backup frequency.", "", false, "false", "0", "" ], [ "SecondaryDatabasePrefix", "Adds a prefix to the secondary database name to distinguish it from the primary database.\r\nUseful when the secondary database resides on the same instance as the primary or for naming conventions.", "", false, "false", "", "" ], [ "SecondaryDatabaseSuffix", "Adds a suffix to the secondary database name to distinguish it from the primary database.\r\nCommon suffixes include \u0027_LS\u0027 for log shipping or \u0027_DR\u0027 for disaster recovery. Automatically applied when source and destination are the same instance.", "", false, "false", "", "" ], [ "SecondaryMonitorServer", "Is the name of the monitor server for the secondary server.\r\nDefaults to monitor on the instance provided via DestinationSqlInstance param.", "", false, "false", "", "" ], [ "SecondaryMonitorCredential", "Allows you to login to enter a secure credential. Only needs to be used when the SecondaryMonitorServerSecurityMode is 0 or \"sqlserver\"\r\nTo use: $scred = Get-Credential, then pass $scred object to the -SecondaryMonitorCredential parameter.", "", false, "false", "", "" ], [ "SecondaryMonitorServerSecurityMode", "The security mode used to connect to the monitor server for the secondary server. Allowed values are 0, \"sqlserver\", 1, \"windows\"\r\nThe default is 1 or Windows.", "", false, "false", "", "0,sqlserver,1,windows" ], [ "SecondaryThresholdAlertEnabled", "Enables the Threshold alert for the secondary database", "", false, "false", "False", "" ], [ "Standby", "Places the secondary database in STANDBY mode, allowing read-only access for reporting purposes.\r\nUsers are disconnected during log restores. Alternative to NORECOVERY mode when you need read access to secondary data.", "", false, "false", "False", "" ], [ "StandbyDirectory", "Specifies the directory where standby files (.tuf) are created when using STANDBY mode.\r\nRequired when using the Standby parameter. These files contain uncommitted transactions that are temporarily backed out during restore operations.", "", false, "false", "", "" ], [ "UseExistingFullBackup", "Uses the most recent full backup from backup history to initialize the secondary database.\r\nThe function automatically locates and uses the latest full backup of the source database for initialization.", "", false, "false", "False", "" ], [ "UseBackupFolder", "Specifies a folder containing backup files (full and/or differential) to initialize the secondary database.\r\nThe function processes all backup files in the folder to bring the secondary database up to the latest available point in time.", "", false, "false", "", "" ], [ "Force", "Bypasses confirmations and applies default values for missing parameters like copy destination folder.\r\nAlso removes existing schedules with the same name and sets automatic database suffix when source and destination instances are identical.", "", 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": "LogShipping", "CommandName": "Invoke-DbaDbLogShipRecovery", "Name": "Invoke-DbaDbLogShipRecovery", "Author": "Sander Stad (@sqlstad), sqlstad.nl", "Syntax": "Invoke-DbaDbLogShipRecovery [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-Database] \u003cString[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [-NoRecovery] [-EnableException] [-Force] [[-InputObject] \u003cDatabase[]\u003e] [[-Delay] \u003cInt32\u003e] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database recovered, containing the outcome and status of the log shipping recovery operation.\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- Database: Name of the log shipped secondary database that was recovered\r\n- RecoverResult: The final result of the recovery operation - either \"Success\" or \"Failed\"\r\n- Comment: Additional details about the recovery operation or error message if the recovery failed", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaDbLogShipRecovery -SqlInstance server1 -Force\nRecovers all the databases on the instance that are enabled for log shipping\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInvoke-DbaDbLogShipRecovery -SqlInstance server1 -SqlCredential $cred -Verbose -Force\nRecovers all the databases on the instance that are enabled for log shipping using a credential\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eInvoke-DbaDbLogShipRecovery -SqlInstance server1 -database db_logship -Verbose\nRecovers the database \"db_logship\" to a normal status\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003edb1, db2, db3, db4 | Invoke-DbaDbLogShipRecovery -SqlInstance server1 -Verbose\nRecovers the database db1, db2, db3, db4 to a normal status\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eInvoke-DbaDbLogShipRecovery -SqlInstance server1 -Force -WhatIf\nShows what would happen if the command were executed.", "Description": "Recovers log shipped secondary databases from standby or restoring state to normal operational state. This function is essential for disaster recovery scenarios when you need to bring secondary databases online after a primary server failure, or for planned migrations where you want to switch roles between primary and secondary servers.\n\nThe recovery process handles the complete workflow automatically. First, it checks if the backup source directory is still accessible. If so, it ensures all available transaction log backups are copied by running the log shipping copy job. If the source directory is unreachable (common in disaster scenarios), it proceeds with available backups.\n\nNext, it runs the log shipping restore job to apply any remaining transaction log backups that haven\u0027t been restored yet. Both the copy and restore jobs are monitored until completion, then disabled to prevent them from running again.\n\nFinally, unless you specify -NoRecovery, the database is brought online by executing RESTORE DATABASE WITH RECOVERY. This makes the database fully accessible for reads and writes.\n\nBy default, all log shipped databases on the target instance are recovered. You can specify individual databases using the -Database parameter. The function requires that SQL Server Agent is running and will validate the service status before proceeding.\n\nAll operations are tracked through the msdb database log shipping tables to ensure consistency and proper sequencing of the recovery steps.", "Links": "https://dbatools.io/Invoke-DbaDbLogShipRecovery", "Synopsis": "Brings log shipped secondary databases online for disaster recovery or planned migration scenarios", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", false, "false", "", "" ], [ "Database", "Specifies the log-shipped secondary databases to recover. Accepts multiple database names and wildcards for pattern matching.\r\nUse this when you need to recover specific databases instead of all log-shipped databases on the instance. Without specifying -Database, you must use -Force to recover all log-shipped databases.", "", 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", "", "" ], [ "NoRecovery", "Prevents the final RESTORE DATABASE WITH RECOVERY step that brings the database fully online. The database remains in restoring state after log shipping jobs complete.\r\nUse this when you need to apply additional transaction logs manually or perform other operations before bringing the database online. By default, databases are fully recovered and made available for \r\nread-write 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", "" ], [ "Force", "Bypasses the safety requirement to specify individual databases and processes all log-shipped databases on the instance. Also sets confirmation preference to none.\r\nUse this in disaster recovery scenarios when you need to quickly recover all log-shipped databases without interactive prompts. Without -Force, you must explicitly specify database names using \r\n-Database.", "", false, "false", "False", "" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase through the pipeline. This allows you to filter databases using Get-DbaDatabase and pipe them directly to the recovery function.\r\nParticularly useful when you need to recover databases based on specific criteria like database state or properties rather than just database names.", "", false, "true (ByValue)", "", "" ], [ "Delay", "Sets the polling interval in seconds to check if the log shipping copy and restore jobs have completed. The function waits this long between status checks.\r\nUse a shorter delay for faster recovery monitoring or a longer delay to reduce system load during job execution. Default is 5 seconds, which balances responsiveness with system performance.", "", false, "false", "5", "" ], [ "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": "Invoke-DbaDbMirrorFailover", "Name": "Invoke-DbaDbMirrorFailover", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Invoke-DbaDbMirrorFailover [[-SqlInstance] \u003cDbaInstanceParameter\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Database\nReturns one Database object for each database that was failed over successfully. When performing a failover operation, the database object is returned with its mirroring state updated to reflect the \r\nnew role (now the principal server).\nDefault properties visible:\r\n- Name: Database name\r\n- Status: Current database status\r\n- Owner: Database owner login\r\n- RecoveryModel: Database recovery model (typically Full for mirrored databases)\r\n- Size: Database size in megabytes\nWhen no failover is performed due to -WhatIf or user cancellation, no output is returned.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaDbMirrorFailover -SqlInstance sql2016 -Database pubs\nFails over the pubs database on sql2016. Prompts for confirmation.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2016 -Database pubs | Invoke-DbaDbMirrorFailover -Force -Confirm:$false\nForces the failover of the pubs database on sql2016 and allows data loss.\r\nDoes not prompt for confirmation.", "Description": "Performs a database mirroring failover by switching roles between the primary and mirror servers. For synchronous mirroring, sets safety level to Full and executes a clean failover without data loss. For asynchronous mirroring or emergency situations, use -Force to allow a forced failover that may result in data loss. This is essential for planned maintenance, disaster recovery scenarios, and testing your high availability setup.", "Links": "https://dbatools.io/Invoke-DbaDbMirrorFailover", "Synopsis": "Fails over database mirroring configurations to the mirror server", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "SQL Server name or SMO object representing the primary SQL Server.", "", 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 fail over to their mirror partners. Accepts multiple database names.\r\nUse this when you need to fail over specific databases rather than piping database objects from Get-DbaDatabase.", "", false, "false", "", "" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase through the pipeline for failover operations.\r\nThis enables you to filter databases using Get-DbaDatabase and pipe the results directly to perform failovers.", "", false, "true (ByValue)", "", "" ], [ "Force", "Forces an immediate failover that allows data loss, primarily for asynchronous mirroring or emergency situations.\r\nWithout this switch, the function performs a safe synchronous failover by setting safety to Full before failing over.", "", 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": [ "Mirroring", "Mirror", "HA" ], "CommandName": "Invoke-DbaDbMirroring", "Name": "Invoke-DbaDbMirroring", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Invoke-DbaDbMirroring [[-Primary] \u003cDbaInstanceParameter\u003e] [[-PrimarySqlCredential] \u003cPSCredential\u003e] [-Mirror] \u003cDbaInstanceParameter[]\u003e [[-MirrorSqlCredential] \u003cPSCredential\u003e] [[-Witness] \u003cDbaInstanceParameter\u003e] [[-WitnessSqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-EndpointEncryption] \u003cString\u003e] [[-EncryptionAlgorithm] \u003cString\u003e] [[-SharedPath] \u003cString\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-UseLastBackup] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database successfully configured for mirroring, containing configuration summary information for the mirroring partnership.\nDefault display properties (via Select-DefaultView):\nWithout witness server:\r\n- Primary: The SQL Server instance serving as the primary (principal) server\r\n- Mirror: The SQL Server instance serving as the mirror server\r\n- Database: The name of the database configured for mirroring\r\n- Status: Status of the mirroring setup (Success indicates successful configuration)\nWith witness server:\r\n- Primary: The SQL Server instance serving as the primary (principal) server\r\n- Mirror: The SQL Server instance serving as the mirror server\r\n- Witness: The SQL Server instance configured as the witness server for automatic failover\r\n- Database: The name of the database configured for mirroring\r\n- Status: Status of the mirroring setup (Success indicates successful configuration)\nAdditional properties available (from PSCustomObject):\r\n- ServiceAccount: String array of SQL Server service accounts that were granted CONNECT permissions on the mirroring endpoints\nOutput occurs only when the ShouldProcess block executes successfully. Multiple objects are returned when mirroring is configured for multiple databases or to multiple mirror instances.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$params = @{\n\u003e\u003e Primary = \u0027sql2017a\u0027\r\n\u003e\u003e Mirror = \u0027sql2017b\u0027\r\n\u003e\u003e MirrorSqlCredential = \u0027sqladmin\u0027\r\n\u003e\u003e Witness = \u0027sql2019\u0027\r\n\u003e\u003e Database = \u0027pubs\u0027\r\n\u003e\u003e SharedPath = \u0027\\\\nas\\sql\\share\u0027\r\n\u003e\u003e }\r\n\u003e\u003e\r\nPS C:\\\u003e Invoke-DbaDbMirroring @params\nPerforms a bunch of checks to ensure the pubs database on sql2017a\r\ncan be mirrored from sql2017a to sql2017b. Logs in to sql2019 and sql2017a\r\nusing Windows credentials and sql2017b using a SQL credential.\nPrompts for confirmation for most changes. To avoid confirmation, use -Confirm:$false or\r\nuse the syntax in the second example.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$params = @{\n\u003e\u003e Primary = \u0027sql2017a\u0027\r\n\u003e\u003e Mirror = \u0027sql2017b\u0027\r\n\u003e\u003e MirrorSqlCredential = \u0027sqladmin\u0027\r\n\u003e\u003e Witness = \u0027sql2019\u0027\r\n\u003e\u003e Database = \u0027pubs\u0027\r\n\u003e\u003e SharedPath = \u0027\\\\nas\\sql\\share\u0027\r\n\u003e\u003e Force = $true\r\n\u003e\u003e Confirm = $false\r\n\u003e\u003e }\r\n\u003e\u003e\r\nPS C:\\\u003e Invoke-DbaDbMirroring @params\nPerforms a bunch of checks to ensure the pubs database on sql2017a\r\ncan be mirrored from sql2017a to sql2017b. Logs in to sql2019 and sql2017a\r\nusing Windows credentials and sql2017b using a SQL credential.\nDrops existing pubs database on Mirror and restores it with\r\na fresh backup.\nDoes all the things in the description, does not prompt for confirmation.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$map = @{ \u0027database_data\u0027 = \u0027M:\\Data\\database_data.mdf\u0027 \u0027database_log\u0027 = \u0027L:\\Log\\database_log.ldf\u0027 }\nPS C:\\\u003e Get-ChildItem \\\\nas\\seed | Restore-DbaDatabase -SqlInstance sql2017b -FileMapping $map -NoRecovery\r\nPS C:\\\u003e Get-DbaDatabase -SqlInstance sql2017a -Database pubs | Invoke-DbaDbMirroring -Mirror sql2017b -Confirm:$false\nRestores backups from sql2017a to a specific file structure on sql2017b then creates mirror with no prompts for confirmation.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2017a -Database pubs |\n\u003e\u003e Invoke-DbaDbMirroring -Mirror sql2017b -UseLastBackup -Confirm:$false\nMirrors pubs on sql2017a to sql2017b and uses the last full and logs from sql2017a to seed. Doesn\u0027t prompt for confirmation.", "Description": "Creates database mirroring configurations between SQL Server instances, handling the complete end-to-end setup process that would normally require dozens of manual T-SQL commands and careful validation steps. This function eliminates the complexity and potential errors involved in manually configuring database mirroring partnerships.\n\nThe function performs comprehensive validation before setup and handles all the technical requirements:\n* Verifies that mirroring is possible between the specified instances and databases\n* Sets the recovery model to Full if needed (required for mirroring)\n* Creates and restores full and log backups to initialize the mirror database if it doesn\u0027t exist\n* Sets up database mirroring endpoints on all participating instances\n* Creates logins and grants CONNECT permissions to service accounts on all endpoints\n* Starts endpoints if they\u0027re not already running\n* Establishes the mirroring partnership between primary and mirror\n* Configures witness server if specified for automatic failover scenarios\n\nThis saves DBAs significant time when setting up high availability solutions and reduces the risk of configuration errors that can cause mirroring setup failures. The function can work with existing backups or create fresh ones as needed.\n\nNOTE: If backup/restore is performed, the backup files will remain on the network share for your records.", "Links": "https://dbatools.io/Invoke-DbaDbMirroring", "Synopsis": "Creates and configures database mirroring between SQL Server instances with full validation and setup", "Availability": "Windows, Linux, macOS", "Params": [ [ "Primary", "Specifies the SQL Server instance that will serve as the primary (principal) server in the mirroring partnership.\r\nUse this when setting up mirroring from scratch rather than piping database objects from Get-DbaDatabase.\r\nMust be paired with the Database parameter to identify which databases to mirror.", "", false, "false", "", "" ], [ "PrimarySqlCredential", "Alternative credentials for connecting to the primary SQL Server instance.\r\nRequired when the current user context doesn\u0027t have sufficient permissions on the primary server.\r\nAccepts PowerShell credential objects created with Get-Credential for SQL Authentication or domain accounts.", "", false, "false", "", "" ], [ "Mirror", "Specifies the SQL Server instance(s) that will serve as the mirror server(s) in the mirroring partnership.\r\nThis is where the mirrored database copies will be created and maintained.\r\nSupports multiple mirror instances for creating mirror partnerships with different servers.", "", true, "false", "", "" ], [ "MirrorSqlCredential", "Alternative credentials for connecting to the mirror SQL Server instance(s).\r\nRequired when the current user context doesn\u0027t have sufficient permissions on the mirror server.\r\nAccepts PowerShell credential objects created with Get-Credential for SQL Authentication or domain accounts.", "", false, "false", "", "" ], [ "Witness", "Specifies the SQL Server instance that will serve as the witness server for automatic failover scenarios.\r\nOptional parameter that enables high safety mode with automatic failover when all three servers can communicate.\r\nLeave empty if you only need high safety mode without automatic failover or high performance mode.", "", false, "false", "", "" ], [ "WitnessSqlCredential", "Alternative credentials for connecting to the witness SQL Server instance.\r\nRequired when the current user context doesn\u0027t have sufficient permissions on the witness server.\r\nAccepts PowerShell credential objects created with Get-Credential for SQL Authentication or domain accounts.", "", false, "false", "", "" ], [ "Database", "Specifies which database(s) on the primary server to set up for mirroring.\r\nRequired when using the Primary parameter instead of piping from Get-DbaDatabase.\r\nSupports multiple database names to set up mirroring for several databases in a single operation.", "", false, "false", "", "" ], [ "EndpointEncryption", "Controls the encryption requirement for database mirroring endpoints created during setup.\r\nDefault is \u0027Required\u0027 which enforces encrypted communication between all mirroring partners.\r\nUse \u0027Supported\u0027 to allow both encrypted and unencrypted connections, or \u0027Disabled\u0027 to prevent encryption.", "", false, "false", "Required", "Disabled,Required,Supported" ], [ "EncryptionAlgorithm", "Specifies the encryption algorithm used by database mirroring endpoints for secure communication.\r\nDefault is \u0027Aes\u0027 which provides strong encryption with good performance.\r\nConsider \u0027AesRC4\u0027 or \u0027RC4Aes\u0027 for compatibility with older SQL Server versions in mixed environments.", "", false, "false", "Aes", "Aes,AesRC4,None,RC4,RC4Aes" ], [ "SharedPath", "Network share path accessible by all SQL Server service accounts for backup and restore operations.\r\nRequired when the mirror database doesn\u0027t exist and needs to be initialized from backups.\r\nMust have read/write permissions for the service accounts running SQL Server on primary and mirror instances.", "", false, "false", "", "" ], [ "InputObject", "Accepts database objects piped from Get-DbaDatabase to set up mirroring for specific databases.\r\nUse this approach when you want to filter databases first or work with existing database objects.\r\nAlternative to using the Primary and Database parameters.", "", false, "true (ByValue)", "", "" ], [ "UseLastBackup", "Uses the most recent full and log backups from the primary server to initialize the mirror database.\r\nAvoids creating new backups when recent ones already exist and are sufficient for mirroring setup.\r\nRequires the primary database to be in Full recovery model with existing backup history.", "", false, "false", "False", "" ], [ "Force", "Drops and recreates the mirror database even if it already exists, using fresh backups from the primary.\r\nUse this when you need to completely reinitialize mirroring or when the existing mirror database is corrupted.\r\nRequires either SharedPath for new backups or UseLastBackup to use existing ones.", "", 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": [ "DataMasking", "GDPR", "PII" ], "CommandName": "Invoke-DbaDbPiiScan", "Name": "Invoke-DbaDbPiiScan", "Author": "Sander Stad (@sqlstad, sqlstad.nl)", "Syntax": "Invoke-DbaDbPiiScan [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-Table] \u003cString[]\u003e] [[-Column] \u003cString[]\u003e] [[-Country] \u003cString[]\u003e] [[-CountryCode] \u003cString[]\u003e] [[-ExcludeTable] \u003cString[]\u003e] [[-ExcludeColumn] \u003cString[]\u003e] [[-SampleCount] \u003cInt32\u003e] [[-KnownNameFilePath] \u003cString\u003e] [[-PatternFilePath] \u003cString\u003e] [-ExcludeDefaultKnownName] [-ExcludeDefaultPattern] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per detected PII finding across all scanned databases, tables, and columns. The result set includes classification information, masking recommendations, and detection method \r\ndetails.\nDefault properties returned (all findings):\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 scanned\r\n- Schema: The schema name containing the table\r\n- Table: The table name containing the potential PII column\r\n- Column: The column name that was flagged as containing potential PII\r\n- PII-Category: Classification category for the PII data (e.g., Identity, Location, Contact)\r\n- PII-Name: Specific name of the PII type detected (e.g., SSN, Geography, Phone)\r\n- FoundWith: Detection method used - DataType, KnownName, or Pattern\r\n- MaskingType: Recommended type of data masking for this PII (e.g., Random, Shuffle, Partial)\r\n- MaskingSubType: Sub-type of the masking method (e.g., Decimal, String, Date)\nAdditional properties based on detection method:\nWhen FoundWith = \"Pattern\" (pattern-matched data):\r\n- Country: Country filter applied to the pattern matching rule\r\n- CountryCode: ISO country code for the matched pattern\r\n- Pattern: The regex pattern that matched the data\r\n- Description: Human-readable description of the pattern\nWhen FoundWith = \"KnownName\" (column name match):\r\n- Pattern: The column name pattern that matched\nWhen FoundWith = \"DataType\" (geography type):\r\n- No additional properties beyond the default set", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaDbPiiScan -SqlInstance sql1 -Database db1\nScan the database db1 on instance sql1\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInvoke-DbaDbPiiScan -SqlInstance sql1, sql2 -Database db1, db2\nScan multiple databases on multiple instances\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eInvoke-DbaDbPiiScan -SqlInstance sql1 -Database db2 -ExcludeColumn firstname\nScan database db2 but exclude the column firstname\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eInvoke-DbaDbPiiScan -SqlInstance sql1 -Database db2 -CountryCode US\nScan database db2 but only apply data patterns used for the United States\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eInvoke-DbaDbPiiScan -SqlInstance sql1 -Database db1 -PatternFilePath c:\\pii\\patterns.json\nScans db1 on instance sql1 with additional custom patterns\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eInvoke-DbaDbPiiScan -SqlInstance sql1 -Database db1 -PatternFilePath c:\\pii\\patterns.json -ExcludeDefaultPattern\nScans db1 on instance sql1 with additional custom patterns, excluding the default patterns", "Description": "This command will go through the tables in your database and assess each column.\nIt will first check the columns names if it was named in such a way that it would indicate PII.\nThe next thing that it will do is pattern recognition by looking into the data from the table.\nCustom scan definitions can be specified using the formats seen in \u003cdbatools module root\u003e\\bin\\datamasking\\pii-knownnames.json and \u003cdbatools module root\u003e\\bin\\datamasking\\pii-patterns.json.", "Links": "https://dbatools.io/Invoke-DbaDbPiiScan", "Synopsis": "Command to return any columns that could potentially contain PII (Personal Identifiable Information)", "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 databases to scan for potential PII data. Required parameter - at least one database must be specified.\r\nUse this to target specific databases rather than scanning entire SQL Server instances.", "", false, "false", "", "" ], [ "Table", "Limits the scan to specific tables within the target databases. Accepts multiple table names.\r\nUse this when you need to focus PII scanning on known tables containing sensitive data rather than scanning all tables.", "", false, "false", "", "" ], [ "Column", "Restricts the scan to specific columns within the target tables. Accepts multiple column names.\r\nUse this when you want to validate specific columns suspected of containing PII or to recheck previously identified columns.", "", false, "false", "", "" ], [ "Country", "Filters PII pattern matching to specific countries using full country names (e.g., \"United States\", \"Canada\").\r\nUse this when your data contains region-specific formats like phone numbers or postal codes that should only match certain countries.", "", false, "false", "", "" ], [ "CountryCode", "Filters PII pattern matching to specific countries using ISO country codes (e.g., \"US\", \"CA\", \"GB\").\r\nUse this for more precise regional filtering when you know the specific country codes for your data regions.", "", false, "false", "", "" ], [ "ExcludeTable", "Prevents scanning of specified tables even if they would otherwise be included in the scan scope.\r\nUse this to skip known system tables, staging tables, or tables confirmed to not contain PII data.", "", false, "false", "", "" ], [ "ExcludeColumn", "Prevents scanning of specified columns even if they would otherwise be included in the scan scope.\r\nUse this to skip columns like timestamps, IDs, or other fields confirmed to not contain PII data.", "", false, "false", "", "" ], [ "SampleCount", "Sets the number of data rows to examine per column for pattern matching. Default is 100 rows.\r\nIncrease this value for more thorough scanning of large tables, or decrease it to speed up scans of tables with consistent data patterns.", "", false, "false", "100", "" ], [ "KnownNameFilePath", "Specifies a JSON file path containing custom column name patterns that indicate PII data.\r\nUse this to add organization-specific column naming conventions that should be flagged as potential PII beyond the default patterns.", "", false, "false", "", "" ], [ "PatternFilePath", "Specifies a JSON file path containing custom regex patterns for identifying PII data within column values.\r\nUse this to add custom data patterns specific to your organization or industry that aren\u0027t covered by the default patterns.", "", false, "false", "", "" ], [ "ExcludeDefaultKnownName", "Disables the built-in column name patterns for PII detection, using only custom patterns if provided.\r\nUse this when the default column name patterns generate too many false positives for your specific database schema conventions.", "", false, "false", "False", "" ], [ "ExcludeDefaultPattern", "Disables the built-in data value patterns for PII detection, using only custom patterns if provided.\r\nUse this when the default data patterns don\u0027t match your data formats or generate excessive false positives.", "", 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": [ "Shrink", "Database" ], "CommandName": "Invoke-DbaDbShrink", "Name": "Invoke-DbaDbShrink", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Invoke-DbaDbShrink [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-AllUserDatabases] [-PercentFreeSpace \u003cInt32\u003e] [-ShrinkMethod \u003cString\u003e] [-FileType \u003cString\u003e] [-StepSize \u003cInt64\u003e] [-StatementTimeout \u003cInt32\u003e] [-ExcludeIndexStats] [-ExcludeUpdateUsage] [-EnableException] [-InputObject \u003cDatabase[]\u003e] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database file that was successfully shrunk, providing detailed metrics about the shrink operation including space reclaimed, fragmentation changes, and execution time.\nDefault properties:\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: Name of the database containing the file\r\n- File: The logical name of the database file that was shrunk\r\n- Start: DateTime when the shrink operation began\r\n- End: DateTime when the shrink operation completed\r\n- Elapsed: Total execution time in HH:mm:ss format\r\n- Success: Boolean indicating if the shrink operation completed successfully\r\n- InitialSize: Original size of the file before shrinking (dbasize object)\r\n- InitialUsed: Amount of space used in the file before shrinking (dbasize object)\r\n- InitialAvailable: Amount of free space in the file before shrinking (dbasize object)\r\n- TargetAvailable: Target amount of free space requested via -PercentFreeSpace parameter (dbasize object)\r\n- FinalAvailable: Amount of free space remaining in the file after shrinking (dbasize object)\r\n- FinalSize: Final size of the file after shrinking (dbasize object)\r\n- InitialAverageFragmentation: Average index fragmentation percentage before shrinking (numeric, 0-100); null if -ExcludeIndexStats was used or SQL Server 2000\r\n- FinalAverageFragmentation: Average index fragmentation percentage after shrinking (numeric, 0-100); null if -ExcludeIndexStats was used or SQL Server 2000\r\n- InitialTopFragmentation: Maximum index fragmentation percentage before shrinking (numeric, 0-100); null if -ExcludeIndexStats was used or SQL Server 2000\r\n- FinalTopFragmentation: Maximum index fragmentation percentage after shrinking (numeric, 0-100); null if -ExcludeIndexStats was used or SQL Server 2000\r\n- Notes: Warning message about potential index fragmentation and recommended post-shrink maintenance\nWhen -ExcludeIndexStats is specified:\r\n- The four fragmentation properties (InitialAverageFragmentation, FinalAverageFragmentation, InitialTopFragmentation, FinalTopFragmentation) are excluded from the output\r\n- All other properties remain available\nAll size properties (InitialSize, InitialUsed, etc.) are dbasize objects that automatically format as human-readable units (Bytes, KB, MB, GB, TB) when displayed. Access the .Bytes, .Kilobytes, \r\n.Megabytes, .Gigabytes, or .Terabytes properties for specific unit conversions.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaDbShrink -SqlInstance sql2016 -Database Northwind,pubs,Adventureworks2014\nShrinks Northwind, pubs and Adventureworks2014 to have as little free space as possible.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInvoke-DbaDbShrink -SqlInstance sql2014 -Database AdventureWorks2014 -PercentFreeSpace 50\nShrinks AdventureWorks2014 to have 50% free space. So let\u0027s say AdventureWorks2014 was 1GB and it\u0027s using 100MB space. The database free space would be reduced to 50MB.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eInvoke-DbaDbShrink -SqlInstance sql2014 -Database AdventureWorks2014 -PercentFreeSpace 50 -FileType Data -StepSize 25MB\nShrinks AdventureWorks2014 to have 50% free space, runs shrinks in 25MB chunks for improved performance.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eInvoke-DbaDbShrink -SqlInstance sql2012 -AllUserDatabases\nShrinks all user databases on SQL2012 (not ideal for production)\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2012 -Database Northwind,pubs | Invoke-DbaDbShrink\nShrinks all databases coming from a pre-filtered list via Get-DbaDatabase", "Description": "Reduces database file sizes by removing unused space from data files, log files, or both. This function targets specific files within databases and can reclaim substantial disk space when databases have grown significantly beyond their current data requirements.\n\nUse this function sparingly and only when disk space recovery is critical, such as after large data deletions, index rebuilds, or when preparing databases for migration. The function supports chunked shrinking operations to minimize performance impact and provides detailed fragmentation statistics to help assess the operation\u0027s effects.\n\nMany awesome SQL people have written about why you should not shrink your data files. Paul Randal and Kalen Delaney wrote great posts about this topic:\n\nhttp://www.sqlskills.com/blogs/paul/why-you-should-not-shrink-your-data-files\nhttps://www.itprotoday.com/sql-server/shrinking-data-files\n\nHowever, there are some cases where a database will need to be shrunk. In the event that you must shrink your database:\n\n1. Ensure you have plenty of space for your T-Log to grow\n2. Understand that shrinks require a lot of CPU and disk resources\n3. Consider running DBCC INDEXDEFRAG or ALTER INDEX ... REORGANIZE after the shrink is complete.", "Links": "https://dbatools.io/Invoke-DbaDbShrink", "Synopsis": "Reduces the physical size of database files by removing unused space from data and log files.\n\n- Shrinks can cause severe index fragmentation (to the tune of 99%)\n- Shrinks can cause massive growth in the database\u0027s transaction log\n- Shrinks can require a lot of time and system resources to perform data movement", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. Defaults to the default instance on 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 shrink on the target instance. Accepts wildcard patterns and multiple database names.\r\nUse this when you need to shrink specific databases rather than all databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific databases from the shrink operation when processing multiple databases. Accepts wildcard patterns.\r\nUseful when shrinking all user databases but want to skip critical production databases or those with specific maintenance windows.", "", false, "false", "", "" ], [ "AllUserDatabases", "Targets all user databases on the instance, excluding system databases (master, model, msdb, tempdb).\r\nUse this for maintenance operations across an entire instance while preserving system database integrity.", "", false, "false", "False", "" ], [ "PercentFreeSpace", "Sets the percentage of free space to maintain in the database files after shrinking, ranging from 0-99. Defaults to 0.\r\nLeave some free space (10-20%) to accommodate normal database growth and reduce the need for frequent auto-growth events.", "", false, "false", "0", "" ], [ "ShrinkMethod", "Controls how SQL Server performs the shrink operation. Default moves data pages and truncates files.\r\nEmptyFile migrates all data to other files in the filegroup. NoTruncate moves pages but doesn\u0027t truncate. TruncateOnly reclaims space without moving data.\r\nUse TruncateOnly when possible as it\u0027s the least resource-intensive and doesn\u0027t cause data movement or fragmentation.", "", false, "false", "Default", "Default,EmptyFile,NoTruncate,TruncateOnly" ], [ "FileType", "Determines which database files to target for shrinking: All (data and log files), Data (only data files), or Log (only log files). Defaults to All.\r\nUse Data when you only need to reclaim space from data files after large deletions. Use Log to specifically target transaction log files after maintenance operations.", "", false, "false", "All", "All,Data,Log" ], [ "StepSize", "Breaks large shrink operations into smaller chunks of the specified size. Use PowerShell size notation like 100MB or 1GB.\r\nChunked shrinks reduce resource contention and allow for better progress monitoring during large shrink operations. Recommended for databases being shrunk by several gigabytes.", "", false, "false", "0", "" ], [ "StatementTimeout", "Sets the command timeout in minutes for the shrink operation. Defaults to 0 (infinite timeout).\r\nLarge database shrinks can take hours to complete, so the default allows operations to run without timing out.", "", false, "false", "0", "" ], [ "ExcludeIndexStats", "Skips collecting index fragmentation statistics before and after the shrink operation.\r\nUse this to speed up the shrink process when you don\u0027t need fragmentation analysis or are planning to rebuild indexes immediately afterward.", "", false, "false", "False", "" ], [ "ExcludeUpdateUsage", "Skips running DBCC UPDATEUSAGE before the shrink operation to ensure accurate space usage statistics.\r\nUse this to reduce operation time when space usage statistics are already current or when immediate shrinking is more important than precision.", "", 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", "" ], [ "InputObject", "Accepts database objects from the pipeline, typically from Get-DbaDatabase output.\r\nUse this for advanced filtering scenarios or when combining multiple database operations in a pipeline.", "", false, "true (ByValue)", "", "" ], [ "WhatIf", "Shows what would happen if the command were to run.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts for confirmation of every step. For example:\nAre you sure you want to perform this action?\r\nPerforming the operation \"Shrink database\" on target \"pubs on SQL2016\\VNEXT\".\r\n[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is \"Y\"):", "cf", false, "false", "", "" ] ] }, { "Tags": [ "General", "Object" ], "CommandName": "Invoke-DbaDbTransfer", "Name": "Invoke-DbaDbTransfer", "Author": "Kirill Kravtsov (@nvarscar)", "Syntax": "Invoke-DbaDbTransfer [[-SqlInstance] \u003cDbaInstanceParameter\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-DestinationSqlInstance] \u003cDbaInstanceParameter\u003e] [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString\u003e] [[-DestinationDatabase] \u003cString\u003e] [[-BatchSize] \u003cInt32\u003e] [[-BulkCopyTimeOut] \u003cInt32\u003e] [[-ScriptingOption] \u003cScriptingOptions\u003e] [[-InputObject] \u003cTransfer\u003e] [-CopyAllObjects] [[-CopyAll] \u003cString[]\u003e] [-SchemaOnly] [-DataOnly] [-ScriptOnly] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject (default behavior)\nReturns one object with transfer summary information when the transfer completes successfully.\nProperties:\r\n- SourceInstance: Name of the source SQL Server instance\r\n- SourceDatabase: Name of the source database\r\n- DestinationInstance: Name of the destination SQL Server instance\r\n- DestinationDatabase: Name of the destination database\r\n- Status: Transfer status (returns \"Success\" when transfer completes)\r\n- Elapsed: Time elapsed during the transfer operation displayed as a human-readable timespan (e.g., \"00:05:30\")\r\n- Log: Array of event messages captured during transfer from DataTransferEvent events\nSystem.String array (when -ScriptOnly is specified)\nWhen -ScriptOnly is specified, returns an array of T-SQL script statements that would be executed to create the transferred objects, without actually performing the transfer.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaDbTransfer -SqlInstance sql1 -DestinationSqlInstance sql2 -Database mydb -CopyAll Tables -DestinationDatabase newdb\nCopies all tables from database mydb on sql1 to database newdb on sql2.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInvoke-DbaDbTransfer -SqlInstance sql1 -DestinationSqlInstance sql2 -Database mydb -CopyAllObjects\nCopies all objects from database mydb on sql1 to database mydb on sql2.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$transfer = New-DbaDbTransfer -SqlInstance sql1 -DestinationSqlInstance sql2 -Database mydb -CopyAllObjects\nPS C:\\\u003e $transfer.Options.ScriptDrops = $true\r\nPS C:\\\u003e $transfer.SchemaOnly = $true\r\nPS C:\\\u003e $transfer | Invoke-DbaDbTransfer\nCopies object schema from database mydb on sql1 to database mydb on sql2 using customized transfer parameters.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$options = New-DbaScriptingOption\nPS C:\\\u003e $options.ScriptDrops = $true\r\nPS C:\\\u003e $transfer = New-DbaDbTransfer -SqlInstance sql1 -DestinationSqlInstance sql2 -Database mydb -CopyAll StoredProcedures -ScriptingOption $options\r\nPS C:\\\u003e $transfer | Invoke-DbaDbTransfer\nCopies procedures from database mydb on sql1 to database mydb on sql2 using custom scripting parameters.", "Description": "Transfers database objects and data between SQL Server instances or databases by executing an SMO Transfer object. This function handles database migrations, environment synchronization, and selective object deployment scenarios where you need to copy specific objects or data without doing a full database restore. You can transfer everything at once, copy only schema without data, copy only data without schema, or generate scripts for manual review. The function works with transfer objects created by New-DbaDbTransfer or generates them automatically based on the parameters you provide.", "Links": "https://dbatools.io/Invoke-DbaDbTransfer", "Synopsis": "Transfers database objects and data between SQL Server instances or databases using SMO Transfer objects.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "Source SQL Server instance name.", "", 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", "", "" ], [ "DestinationSqlInstance", "Target SQL Server instance where database objects will be transferred to. You must have appropriate permissions to create and modify objects on the destination server.\r\nUse this to specify a different server for migrations, environment promotions, or cross-server object synchronization.", "", false, "false", "", "" ], [ "DestinationSqlCredential", "Credentials for connecting to the destination SQL Server instance. Accepts PowerShell credentials created with Get-Credential.\r\nOnly SQL Server Authentication is supported for destination connections. When not specified, the function uses Windows Integrated Authentication.", "", false, "false", "", "" ], [ "Database", "Source database name containing the objects to transfer. This database must exist on the source SQL Server instance.\r\nSpecify the exact database name - wildcards are not supported for this parameter.", "", false, "false", "", "" ], [ "DestinationDatabase", "Target database name where objects will be transferred to. If not specified, uses the same name as the source database.\r\nUse this when transferring objects to a database with a different name, such as during environment refreshes where databases have different naming conventions.", "", false, "false", "$Database", "" ], [ "BatchSize", "Number of rows to transfer in each batch operation during data copy. Defaults to 50,000 rows per batch.\r\nIncrease this value for faster transfers of large tables, or decrease it to reduce memory usage and lock duration on busy systems.", "", false, "false", "50000", "" ], [ "BulkCopyTimeOut", "Timeout in seconds for bulk copy operations when transferring table data. Defaults to 5000 seconds.\r\nIncrease this value when transferring very large tables that take longer than the default timeout to complete.", "", false, "false", "5000", "" ], [ "ScriptingOption", "Custom scripting configuration created by New-DbaScriptingOption that controls how objects are scripted during transfer.\r\nUse this to customize object scripting behavior such as including permissions, indexes, triggers, or generating DROP statements.", "", false, "false", "", "" ], [ "InputObject", "Pre-configured SMO Transfer object created by New-DbaDbTransfer that defines what to transfer and how.\r\nUse this when you need to customize transfer settings beyond what the direct parameters provide, or when reusing the same transfer configuration multiple times.", "", false, "true (ByValue)", "", "" ], [ "CopyAllObjects", "Transfers all database objects including tables, views, stored procedures, functions, users, roles, and other database-level objects.\r\nUse this for complete database migrations where you need to copy everything from the source database to the destination.", "", false, "false", "False", "" ], [ "CopyAll", "Specific types of database objects to transfer. Accepts an array of object type names for selective copying.\r\nUse this when you only need certain object types instead of everything, such as copying only tables and views for a data warehouse refresh.\r\nCommon values include Tables, Views, StoredProcedures, UserDefinedFunctions, Users, Roles, and Schemas.", "", false, "false", "", "FullTextCatalogs,FullTextStopLists,SearchPropertyLists,Tables,Views,StoredProcedures,UserDefinedFunctions,UserDefinedDataTypes,UserDefinedTableTypes,PlanGuides,Rules,Defaults,Users,Roles,PartitionSchemes,PartitionFunctions,XmlSchemaCollections,SqlAssemblies,UserDefinedAggregates,UserDefinedTypes,Schemas,Synonyms,Sequences,DatabaseTriggers,DatabaseScopedCredentials,ExternalFileFormats,ExternalDataSources,Logins,ExternalLibraries" ], [ "SchemaOnly", "Transfers only the structure and definitions of database objects without copying any table data.\r\nUse this for setting up new environments where you need the database structure but will populate data separately, or for schema synchronization between environments.", "", false, "false", "False", "" ], [ "DataOnly", "Transfers only table data without creating or modifying object schemas. Target objects must already exist in the destination database.\r\nUse this for data refreshes where the destination database structure is already in place and you only need to update the data.", "", false, "false", "False", "" ], [ "ScriptOnly", "Generates T-SQL scripts for creating the selected objects without actually executing the transfer.\r\nUse this to review what would be created, save scripts for later execution, or integrate with deployment pipelines that require script artifacts.", "", 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": [ "Shrink", "Database" ], "CommandName": "Invoke-DbaDbUpgrade", "Name": "Invoke-DbaDbUpgrade", "Author": "Stephen Bennett, sqlnotesfromtheunderground.wordpress.com", "Syntax": "Invoke-DbaDbUpgrade [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-NoCheckDb] [-NoUpdateUsage] [-NoUpdateStats] [-NoRefreshView] [-AllUserDatabases] [-Force] [-InputObject \u003cDatabase[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database processed with detailed information about each upgrade operation performed.\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- Database: Name of the database that was upgraded\r\n- OriginalCompatibility: Original database compatibility level before upgrade (e.g., \"100\", \"110\", \"140\")\r\n- CurrentCompatibility: New database compatibility level after upgrade (e.g., \"100\", \"110\", \"140\")\r\n- Compatibility: Result status of compatibility level update; values: version number if updated, \"No change\" if already correct, \"Fail\" if update failed\r\n- TargetRecoveryTime: Result of target recovery time update; values: 60 if set to 60 seconds, \"No change\" if already 60 or SQL Server version \u003c 2016, \"Fail\" if update failed\r\n- DataPurity: Result of DBCC CHECKDB DATA_PURITY; values: \"Success\" if completed, \"Fail\" if failed, omitted if -NoCheckDb is specified\r\n- UpdateUsage: Result of DBCC UPDATEUSAGE; values: \"Success\" if completed, \"Fail\" if failed, \"Skipped\" if -NoUpdateUsage is specified\r\n- UpdateStats: Result of sp_updatestats; values: \"Success\" if completed, \"Fail\" if failed, \"Skipped\" if -NoUpdateStats is specified\r\n- RefreshViews: Result of sp_refreshview on all user views; values: \"Success\" if all refreshed, \"Fail\" if any failed, \"Skipped\" if -NoRefreshView is specified", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaDbUpgrade -SqlInstance PRD-SQL-MSD01 -Database Test\nRuns the below processes against the databases\r\n-- Puts compatibility of database to level of SQL Instance\r\n-- Changes the target recovery time to the new default of 60 seconds (for SQL Server 2016 and newer)\r\n-- Runs CHECKDB DATA_PURITY\r\n-- Runs DBCC UPDATESUSAGE\r\n-- Updates all users statistics\r\n-- Runs sp_refreshview against every view in the database\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInvoke-DbaDbUpgrade -SqlInstance PRD-SQL-INT01 -Database Test -NoRefreshView\nRuns the upgrade command skipping the sp_refreshview update on all views\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eInvoke-DbaDbUpgrade -SqlInstance PRD-SQL-INT01 -Database Test -Force\nIf database Test is already at the correct compatibility, runs every necessary step\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2016 | Out-GridView -Passthru | Invoke-DbaDbUpgrade\nGet only specific databases using GridView and pass those to Invoke-DbaDbUpgrade", "Description": "Performs the essential steps needed after upgrading SQL Server or moving databases to a newer instance. Updates database compatibility level to match the hosting SQL Server version and sets target recovery time to 60 seconds for SQL Server 2016 and newer.\n\nExecutes critical post-upgrade maintenance including DBCC CHECKDB with DATA_PURITY to detect data corruption, DBCC UPDATEUSAGE to correct page counts, sp_updatestats to refresh statistics, and sp_refreshview to update all user views with new metadata. This automates the manual checklist DBAs typically follow after SQL Server upgrades to ensure databases function optimally on the new version.\n\nBased on https://thomaslarock.com/2014/06/upgrading-to-sql-server-2014-a-dozen-things-to-check/", "Links": "https://dbatools.io/Invoke-DbaDbUpgrade", "Synopsis": "Upgrades database compatibility level and performs post-upgrade maintenance tasks", "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 upgrade and run post-upgrade maintenance tasks on. Accepts wildcards for pattern matching.\r\nUse this when you need to target specific databases rather than processing all user databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific databases from the upgrade process when using -AllUserDatabases. Accepts wildcards for pattern matching.\r\nUseful for skipping system-critical databases or those with special maintenance windows during bulk upgrade operations.", "", false, "false", "", "" ], [ "NoCheckDb", "Skips the DBCC CHECKDB with DATA_PURITY validation step during the upgrade process.\r\nUse this when you\u0027ve recently run integrity checks or need to reduce upgrade time, though this removes corruption detection from the process.", "", false, "false", "False", "" ], [ "NoUpdateUsage", "Skips the DBCC UPDATEUSAGE step that corrects inaccuracies in page and row count information.\r\nUse this when you\u0027re confident space usage statistics are accurate or need to minimize upgrade time for very large databases.", "", false, "false", "False", "" ], [ "NoUpdateStats", "Skips running sp_updatestats to refresh all user table statistics with current data distribution.\r\nUse this when statistics were recently updated or when you have a separate statistics maintenance plan in place.", "", false, "false", "False", "" ], [ "NoRefreshView", "Skips executing sp_refreshview on all user views to update their metadata for the new SQL Server version.\r\nUse this when you have no views or prefer to refresh view metadata manually to avoid potential view compilation issues.", "", false, "false", "False", "" ], [ "AllUserDatabases", "Processes all user databases on the instance, excluding system databases. Cannot be used with -Database parameter.\r\nUse this for instance-wide upgrades after SQL Server version changes or when standardizing all databases to current compatibility levels.", "", false, "false", "False", "" ], [ "Force", "Runs all maintenance tasks even on databases already at the correct compatibility level and target recovery time.\r\nUse this when you need to ensure CHECKDB, UPDATEUSAGE, statistics updates, and view refreshes run regardless of compatibility status.", "", false, "false", "False", "" ], [ "InputObject", "Accepts database objects from the pipeline, typically from Get-DbaDatabase output. Cannot be used with -Database or -AllUserDatabases.\r\nUse this for targeted upgrades based on complex filtering criteria or when integrating with other dbatools commands in a 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", "" ], [ "WhatIf", "Shows what would happen if the command were to run", "wi", false, "false", "", "" ], [ "Confirm", "Prompts for confirmation of every step. For example:\nAre you sure you want to perform this action?\r\nPerforming the operation \"Update database\" on target \"pubs on SQL2016\\VNEXT\".\r\n[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is \"Y\"):", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Community", "GlennBerry" ], "CommandName": "Invoke-DbaDiagnosticQuery", "Name": "Invoke-DbaDiagnosticQuery", "Author": "Andre Kamman (@AndreKamman), andrekamman.com", "Syntax": "Invoke-DbaDiagnosticQuery [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-ExcludeQuery \u003cObject[]\u003e] [-SqlCredential \u003cPSCredential\u003e] [-Path \u003cFileInfo\u003e] [-QueryName \u003cString[]\u003e] [-UseSelectionHelper] [-InstanceOnly] [-DatabaseSpecific] [-ExcludeQueryTextColumn] [-ExcludePlanColumn] [-NoColumnParsing] [-OutputPath \u003cString\u003e] [-ExportQueries] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per diagnostic query executed from Glenn Berry\u0027s query collection. Each object contains the query execution results along with metadata about the query and target database.\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- Number: The query number from Glenn Berry\u0027s diagnostic query collection\r\n- Name: The name or title of the diagnostic query\r\n- Description: Description of what the diagnostic query analyzes and why it\u0027s useful\r\n- DatabaseSpecific: Boolean indicating if the query is database-specific (true) or instance-level (false)\r\n- Database: Database name if DatabaseSpecific is true; null for instance-level queries\r\n- Notes: Status notes; \"Empty Result for this Query\" if no rows returned, \"WhatIf - Bypassed Execution\" when -WhatIf is used, null for successful executions\r\n- Result: The query result set as an array of DataRow objects containing the diagnostic data; null if no results or on WhatIf execution\nSpecial behaviors:\r\n- When -ExportQueries is used, no output objects are returned; only SQL files are written to disk\r\n- The Result property contains all columns from the diagnostic query output, formatted as DataRow objects\r\n- Database-specific queries return one object per database queried, with Database property populated\r\n- Instance-level queries return one object with Database set to null", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaDiagnosticQuery -SqlInstance sql2016\nRun the selection made by the user on the Sql Server instance specified.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInvoke-DbaDiagnosticQuery -SqlInstance sql2016 -UseSelectionHelper | Export-DbaDiagnosticQuery -Path C:\\temp\\gboutput\nProvides a grid view with all the queries to choose from and will run the selection made by the user on the SQL Server instance specified.\r\nThen it will export the results to Export-DbaDiagnosticQuery.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eInvoke-DbaDiagnosticQuery -SqlInstance localhost -ExportQueries -OutputPath \"C:\\temp\\DiagnosticQueries\"\nExport All Queries to Disk\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eInvoke-DbaDiagnosticQuery -SqlInstance localhost -DatabaseSpecific -ExportQueries -OutputPath \"C:\\temp\\DiagnosticQueries\"\nExport Database Specific Queries for all User Dbs\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eInvoke-DbaDiagnosticQuery -SqlInstance localhost -DatabaseSpecific -DatabaseName \u0027tempdb\u0027 -ExportQueries -OutputPath \"C:\\temp\\DiagnosticQueries\"\nExport Database Specific Queries For One Target Database\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eInvoke-DbaDiagnosticQuery -SqlInstance localhost -DatabaseSpecific -DatabaseName \u0027tempdb\u0027 -ExportQueries -OutputPath \"C:\\temp\\DiagnosticQueries\" -QueryName \u0027Database-scoped Configurations\u0027\nExport Database Specific Queries For One Target Database and One Specific Query\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eInvoke-DbaDiagnosticQuery -SqlInstance localhost -UseSelectionHelper\nChoose Queries To Export\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003e[PSObject[]]$results = Invoke-DbaDiagnosticQuery -SqlInstance localhost -WhatIf\nParse the appropriate diagnostic queries by connecting to server, and instead of running them, return as [PSCustomObject[]] to work with further\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003e$results = Invoke-DbaDiagnosticQuery -SqlInstance Sql2017 -DatabaseSpecific -QueryName \u0027Database-scoped Configurations\u0027 -DatabaseName TestStuff\nRun diagnostic queries targeted at specific database, and only run database level queries against this database.", "Description": "Runs Glenn Berry\u0027s comprehensive collection of DMV-based diagnostic queries to analyze SQL Server performance, configuration, and health issues. These queries help identify common problems like blocking, high CPU usage, memory pressure, index fragmentation, and configuration issues that affect SQL Server performance.\n\nThe diagnostic queries are developed and maintained by Glenn Berry and can be found at https://glennsqlperformance.com/resources/ along with extensive documentation. The most recent version of these diagnostic queries are included in the dbatools module, but you can also specify a custom path to run newer versions or specific query collections.\n\nThis function automatically detects your SQL Server version (2005-2025, including Azure SQL Database) and runs the appropriate queries for that platform. You can run all queries, select specific ones interactively, or target only instance-level or database-specific diagnostics. Results are returned as structured PowerShell objects for easy analysis, filtering, and reporting. You can also export the queries as SQL files for manual execution or documentation purposes.", "Links": "https://dbatools.io/Invoke-DbaDiagnosticQuery", "Synopsis": "Executes Glenn Berry\u0027s DMV diagnostic queries to assess SQL Server performance and health", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. Can be either a string or SMO server", "", true, "true (ByValue)", "", "" ], [ "Database", "Specifies which databases to run database-specific diagnostic queries against. Accepts wildcard patterns and multiple database names.\r\nWhen omitted, all user databases are processed. System databases are automatically excluded unless explicitly specified.", "DatabaseName", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific databases from database-level diagnostic query execution. Accepts wildcard patterns and multiple database names.\r\nUseful when you want to run diagnostics on most databases but skip problematic or maintenance databases.", "", false, "false", "", "" ], [ "ExcludeQuery", "Excludes specific diagnostic queries from execution by their query names. Accepts multiple query names as an array.\r\nUse this to skip time-consuming queries like index fragmentation analysis or queries that might cause blocking during peak hours.", "", 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.", "Credential", false, "false", "", "" ], [ "Path", "Specifies a custom directory containing Glenn Berry diagnostic query script files. By default, uses the scripts included with dbatools.\r\nUse this when you want to run newer diagnostic query versions downloaded from Glenn Berry\u0027s website or custom query collections.", "", false, "false", "", "" ], [ "QueryName", "Runs only the specified diagnostic queries by their exact query names. Accepts multiple query names as an array.\r\nUse this when you know exactly which diagnostics you need, such as \u0027Wait Stats\u0027 or \u0027Top CPU Queries\u0027 for targeted performance analysis.", "", false, "false", "", "" ], [ "UseSelectionHelper", "Opens an interactive grid view showing all available diagnostic queries with descriptions for manual selection.\r\nPerfect for ad-hoc troubleshooting when you want to run only specific queries relevant to your current performance issue.", "", false, "false", "False", "" ], [ "InstanceOnly", "Limits execution to server-level diagnostic queries only, skipping all database-specific queries.\r\nIdeal for quick instance health checks focusing on server configuration, wait statistics, and instance-wide performance metrics.", "", false, "false", "False", "" ], [ "DatabaseSpecific", "Limits execution to database-level diagnostic queries only, skipping all instance-level queries.\r\nUse this when investigating database-specific issues like index fragmentation, table statistics, or database configuration problems.", "", false, "false", "False", "" ], [ "ExcludeQueryTextColumn", "Removes the [Complete Query Text] column from diagnostic query results to reduce output size and improve performance.\r\nUseful when you only need query execution statistics without the actual SQL text, especially for queries with large stored procedures.", "", false, "false", "False", "" ], [ "ExcludePlanColumn", "Removes the [Query Plan] column from diagnostic query results to significantly reduce memory usage and improve performance.\r\nEssential when processing large result sets or when execution plan XML data is not needed for your analysis.", "", false, "false", "False", "" ], [ "NoColumnParsing", "Disables all column parsing and formatting for [Complete Query Text] and [Query Plan] columns, returning raw data.\r\nUse this for maximum performance when you need the fastest possible execution and don\u0027t require formatted output columns.", "", false, "false", "False", "" ], [ "OutputPath", "Specifies the directory path where exported diagnostic query SQL files will be saved when using -ExportQueries.\r\nFiles are automatically organized by server name, database name, and query name for easy identification and manual execution.", "", false, "false", "", "" ], [ "ExportQueries", "Exports diagnostic queries as individual SQL files instead of executing them, organized by query type and target database.\r\nUseful for creating a library of diagnostic scripts for offline analysis, sharing with team members, or manual execution during maintenance windows.", "", 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 would execute, but does not actually perform the command", "wi", false, "false", "", "" ], [ "Confirm", "Prompts to confirm certain actions", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Performance", "DataCollector", "PerfCounter", "Relog" ], "CommandName": "Invoke-DbaPfRelog", "Name": "Invoke-DbaPfRelog", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Invoke-DbaPfRelog [[-Path] \u003cString[]\u003e] [[-Destination] \u003cString\u003e] [[-Type] \u003cString\u003e] [-Append] [-AllowClobber] [[-PerformanceCounter] \u003cString[]\u003e] [[-PerformanceCounterPath] \u003cString\u003e] [[-Interval] \u003cInt32\u003e] [[-BeginTime] \u003cDateTime\u003e] [[-EndTime] \u003cDateTime\u003e] [[-ConfigPath] \u003cString\u003e] [-Summary] [[-InputObject] \u003cObject[]\u003e] [-Multithread] [-AllTime] [-Raw] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.IO.FileInfo (default)\nReturns file objects for each successfully converted performance log file. Each file object includes all standard System.IO.FileInfo properties plus an added RelogFile property.\nProperties:\r\n- FullName: The complete path to the converted output file\r\n- Name: The file name with extension (.tsv, .csv, .bin, etc.)\r\n- Directory: The directory containing the file\r\n- DirectoryName: The full path of the directory\r\n- Extension: The file extension (.tsv, .csv, .bin, .sql)\r\n- Length: The size of the file in bytes\r\n- Attributes: File attributes (Archive, ReadOnly, etc.)\r\n- CreationTime: The date and time the file was created\r\n- LastAccessTime: The date and time the file was last accessed\r\n- LastWriteTime: The date and time the file was last modified\r\n- RelogFile: Boolean NoteProperty set to true, indicating this file was created by relog conversion\nString (when -Raw is specified)\nReturns the raw output from the relog command including:\r\n- Input file information (file path, format, begin/end times, sample count)\r\n- Output file information (file path, format, begin/end times, sample count)\r\n- Completion status message\r\n- Processing progress percentage\nNo output (when -Summary or -ExportQueries is specified)\nWhen -Summary is used, summary information is displayed as text output but no objects are returned.\r\nWhen relog output is written directly to SQL via ODBC, no file objects are available for return.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaPfRelog -Path C:\\temp\\perfmon.blg\nCreates C:\\temp\\perfmon.tsv from C:\\temp\\perfmon.blg.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInvoke-DbaPfRelog -Path C:\\temp\\perfmon.blg -Destination C:\\temp\\a\\b\\c\nCreates the temp, a, and b directories if needed, then generates c.tsv (tab separated) from C:\\temp\\perfmon.blg.\nReturns the newly created file as a file object.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorSet -ComputerName sql2016 | Get-DbaPfDataCollector | Invoke-DbaPfRelog -Destination C:\\temp\\perf\nCreates C:\\temp\\perf if needed, then generates computername-datacollectorname.tsv (tab separated) from the latest logs of all data collector sets on sql2016. This destination format was chosen to \r\navoid naming conflicts with piped input.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eInvoke-DbaPfRelog -Path C:\\temp\\perfmon.blg -Destination C:\\temp\\a\\b\\c -Raw\n\u003e\u003e [Invoke-DbaPfRelog][21:21:35] relog \"C:\\temp\\perfmon.blg\" -f csv -o C:\\temp\\a\\b\\c\r\n\u003e\u003e Input\r\n\u003e\u003e ----------------\r\n\u003e\u003e File(s):\r\n\u003e\u003e C:\\temp\\perfmon.blg (Binary)\r\n\u003e\u003e Begin: 1/13/2018 5:13:23\r\n\u003e\u003e End: 1/13/2018 14:29:55\r\n\u003e\u003e Samples: 2227\r\n\u003e\u003e 100.00%\r\n\u003e\u003e Output\r\n\u003e\u003e ----------------\r\n\u003e\u003e File: C:\\temp\\a\\b\\c.csv\r\n\u003e\u003e Begin: 1/13/2018 5:13:23\r\n\u003e\u003e End: 1/13/2018 14:29:55\r\n\u003e\u003e Samples: 2227\r\n\u003e\u003e The command completed successfully.\nCreates the temp, a, and b directories if needed, then generates c.tsv (tab separated) from C:\\temp\\perfmon.blg then outputs the raw results of the relog command.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eInvoke-DbaPfRelog -Path \u0027C:\\temp\\perflog with spaces.blg\u0027 -Destination C:\\temp\\a\\b\\c -Type csv -BeginTime ((Get-Date).AddDays(-30)) -EndTime ((Get-Date).AddDays(-1))\nCreates the temp, a, and b directories if needed, then generates c.csv (comma separated) from C:\\temp\\perflog with spaces.blg\u0027, starts 30 days ago and ends one day ago.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e$servers | Get-DbaPfDataCollectorSet | Get-DbaPfDataCollector | Invoke-DbaPfRelog -Multithread -AllowClobber\nRelogs latest data files from all collectors within the servers listed in $servers.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollector -Collector DataCollector01 | Invoke-DbaPfRelog -AllowClobber -AllTime\nRelogs all the log files from the DataCollector01 on the local computer and allows overwrite.", "Description": "Pipeline-compatible wrapper for the relog command. Relog is useful for converting Windows Perfmon.\n\nExtracts performance counters from performance counter logs into other formats,\nsuch as text-TSV (for tab-delimited text), text-CSV (for comma-delimited text), binary-BIN, or SQL.\n\n`relog \"C:\\PerfLogs\\Admin\\System Correlation\\WORKSTATIONX_20180112-000001\\DataCollector01.blg\" -o C:\\temp\\foo.csv -f tsv`\n\nIf you find any input hangs, please send us the output so we can accommodate for it then use -Raw for an immediate solution.", "Links": "https://dbatools.io/Invoke-DbaPfRelog", "Synopsis": "Pipeline-compatible wrapper for the relog command which is available on modern Windows platforms.", "Availability": "Windows, Linux, macOS", "Params": [ [ "Path", "Specifies the file path to Windows performance counter log files (.blg format) that need to be converted. Accepts multiple file paths and supports pipeline input.\r\nUse this when you have perfmon binary logs that need to be converted to readable formats like CSV or TSV for analysis.", "FullName", false, "true (ByPropertyName)", "", "" ], [ "Destination", "Specifies the output file path or directory where converted performance data will be saved. Creates necessary directories automatically if they don\u0027t exist.\r\nWhen omitted, files are saved in the same directory as the source with the appropriate extension (.tsv, .csv, etc.).", "", false, "false", "", "" ], [ "Type", "Specifies the output format for the converted performance data. Defaults to \u0027tsv\u0027 (tab-separated values).\r\nUse \u0027csv\u0027 for Excel compatibility, \u0027tsv\u0027 for easy parsing in PowerShell, \u0027bin\u0027 for binary format, or \u0027sql\u0027 to write directly to a SQL database via ODBC.\r\nFor SQL output, specify the destination as \u0027DSN!counter_log\u0027 where DSN is configured in ODBC Manager.", "", false, "false", "tsv", "tsv,csv,bin,sql" ], [ "Append", "Appends performance data to an existing output file instead of overwriting it. Only works with binary (-Type bin) format.\r\nUse this when consolidating multiple perfmon logs into a single file for comprehensive analysis over time periods.", "", false, "false", "False", "" ], [ "AllowClobber", "Overwrites existing output files without prompting. Required when the destination file already exists and you want to replace it.\r\nUse this in automated scripts or when you need to refresh converted performance data files.", "", false, "false", "False", "" ], [ "PerformanceCounter", "Specifies specific performance counters to extract from the log files. Accepts counter paths like \u0027\\Processor(_Total)\\% Processor Time\u0027.\r\nUse this to filter large perfmon logs and extract only the counters you need for analysis, reducing output file size.", "", false, "false", "", "" ], [ "PerformanceCounterPath", "Specifies a text file containing performance counter paths to extract, one counter per line. Alternative to specifying counters directly.\r\nUse this when you have a standard set of counters for monitoring SQL Server performance and want to consistently extract the same metrics across multiple log files.", "", false, "false", "", "" ], [ "Interval", "Specifies the sampling interval by including every nth data point from the original log. Reduces output size by skipping intermediate samples.\r\nUse this when working with high-frequency perfmon logs where you need less granular data for trend analysis rather than detailed monitoring.", "", false, "false", "0", "" ], [ "BeginTime", "Specifies the start time for data extraction using a DateTime object. Only performance data from this time forward will be included in the output.\r\nUse this to extract specific time periods from large perfmon logs, such as during a known performance incident or maintenance window.", "", false, "false", "", "" ], [ "EndTime", "Specifies the end time for data extraction using a DateTime object. Performance data after this time will be excluded from the output.\r\nCombine with BeginTime to extract data from specific time ranges, useful for analyzing performance during particular events or time periods.", "", false, "false", "", "" ], [ "ConfigPath", "Specifies a configuration file containing relog command-line parameters for complex or frequently-used conversion settings.\r\nUse this when you have standardized performance log processing requirements that need consistent parameters across multiple operations.", "", false, "false", "", "" ], [ "Summary", "Displays summary information about the performance log files including available counters and time ranges without performing the conversion.\r\nUse this to examine perfmon logs before processing them, helping you determine what counters are available and the time span covered.", "", false, "false", "False", "" ], [ "InputObject", "Accepts data collector objects from Get-DbaPfDataCollector and Get-DbaPfDataCollectorSet via pipeline input for automatic log file discovery.\r\nUse this to convert performance logs directly from active or configured data collectors without manually specifying file paths.", "", false, "true (ByValue)", "", "" ], [ "Multithread", "Processes multiple performance log files in parallel to improve performance when converting large batches of files.\r\nUse this when converting many perfmon logs simultaneously, especially beneficial on multi-core systems with large performance monitoring datasets.", "", false, "false", "False", "" ], [ "AllTime", "Processes all available log files from data collectors instead of just the most recent ones when used with pipeline input from Get-DbaPfDataCollector.\r\nUse this when you need to convert historical performance data from all collection periods, not just the latest monitoring session.", "", false, "false", "False", "" ], [ "Raw", "Displays the raw output from the relog command instead of returning file objects. Useful for debugging conversion issues or seeing detailed progress.\r\nUse this when troubleshooting relog operations or when you need to see the exact command-line output and statistics from the conversion process.", "", 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": [ "Database", "Query", "Utility" ], "CommandName": "Invoke-DbaQuery", "Name": "Invoke-DbaQuery", "Author": "Friedrich Weinmann (@FredWeinmann)", "Syntax": "Invoke-DbaQuery [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cString\u003e] -Query \u003cString\u003e [-QueryTimeout \u003cInt32\u003e] [-As \u003cString\u003e] [-SqlParameter \u003cPSObject[]\u003e] [-CommandType {Text | StoredProcedure | TableDirect}] [-AppendServerInstance] [-MessagesToOutput] [-InputObject \u003cDatabase[]\u003e] [-ReadOnly] [-NoExec] [-QuotedIdentifier] [-AppendConnectionString \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]\nInvoke-DbaQuery [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cString\u003e] [-QueryTimeout \u003cInt32\u003e] -SqlObject \u003cSqlSmoObject[]\u003e [-As \u003cString\u003e] [-SqlParameter \u003cPSObject[]\u003e] [-CommandType {Text | StoredProcedure | TableDirect}] [-AppendServerInstance] [-MessagesToOutput] [-InputObject \u003cDatabase[]\u003e] [-ReadOnly] [-NoExec] [-QuotedIdentifier] [-AppendConnectionString \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]\nInvoke-DbaQuery [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cString\u003e] [-QueryTimeout \u003cInt32\u003e] -File \u003cObject[]\u003e [-As \u003cString\u003e] [-SqlParameter \u003cPSObject[]\u003e] [-CommandType {Text | StoredProcedure | TableDirect}] [-AppendServerInstance] [-MessagesToOutput] [-InputObject \u003cDatabase[]\u003e] [-ReadOnly] [-NoExec] [-QuotedIdentifier] [-AppendConnectionString \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "ivq", "Outputs": "System.Data.DataSet (when -As DataSet is specified)\nReturns a DataSet object containing all result tables from the query. This format preserves table relationships and metadata.\nSystem.Data.DataTable[] (when -As DataTable is specified)\nReturns an array of DataTable objects, one for each result set returned by the query. Use this when you need access to individual result sets with full DataTable methods and properties.\nSystem.Data.DataRow[] (when -As DataRow is specified - default)\nReturns an array of DataRow objects representing the rows from the first result set. This is the most common format for typical SELECT queries. When -MessagesToOutput is specified, T-SQL PRINT and \r\nRAISERROR messages are also included in the output stream alongside the data rows.\nPSObject (when -As PSObject is specified)\nReturns individual PSObject objects, one per row from each result set in the query results. DBNull values are converted to $null for easier comparison and PowerShell integration. Use this when you \r\nneed to pipe results to other PowerShell commands that expect objects.\nPSObject[] (when -As PSObjectArray is specified)\nReturns an array of PSObject objects per result set. When multiple result sets are returned, each result set is returned as a separate array. DBNull values are converted to $null.\nSystem.Object (when -As SingleValue is specified)\nReturns a single scalar value (the first column of the first row). Use this for queries returning a count, sum, or other single value like SELECT COUNT(*) or SELECT @@SERVERNAME.\nWhen -AppendServerInstance is specified, an additional ServerInstance column is added to DataRow and PSObject output, containing the source SQL Server instance name.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaQuery -SqlInstance server\\instance -Query \u0027SELECT foo FROM bar\u0027\nRuns the sql query \u0027SELECT foo FROM bar\u0027 against the instance \u0027server\\instance\u0027\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaRegServer -SqlInstance [SERVERNAME] -Group [GROUPNAME] | Invoke-DbaQuery -Query \u0027SELECT foo FROM bar\u0027\nRuns the sql query \u0027SELECT foo FROM bar\u0027 against all instances in the group [GROUPNAME] on the CMS [SERVERNAME]\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e\"server1\", \"server1\\nordwind\", \"server2\" | Invoke-DbaQuery -File \"C:\\scripts\\sql\\rebuild.sql\"\nRuns the sql commands stored in rebuild.sql against the instances \"server1\", \"server1\\nordwind\" and \"server2\"\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance \"server1\", \"server1\\nordwind\", \"server2\" | Invoke-DbaQuery -File \"C:\\scripts\\sql\\rebuild.sql\"\nRuns the sql commands stored in rebuild.sql against all accessible databases of the instances \"server1\", \"server1\\nordwind\" and \"server2\"\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eInvoke-DbaQuery -SqlInstance . -Query \u0027SELECT * FROM users WHERE Givenname = @name\u0027 -SqlParameter @{ Name = \"Maria\" }\nExecutes a simple query against the users table using SQL Parameters.\r\nThis avoids accidental SQL Injection and is the safest way to execute queries with dynamic content.\r\nKeep in mind the limitations inherent in parameters - it is quite impossible to use them for content references.\r\nWhile it is possible to parameterize a where condition, it is impossible to use this to select which columns to select.\r\nThe inserted text will always be treated as string content, and not as a reference to any SQL entity (such as columns, tables or databases).\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eInvoke-DbaQuery -SqlInstance aglistener1 -ReadOnly -Query \"select something from readonlydb.dbo.atable\"\nExecutes a query with ReadOnly application intent on aglistener1.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eInvoke-DbaQuery -SqlInstance server1 -Database tempdb -Query Example_SP -SqlParameter @{ Name = \"Maria\" } -CommandType StoredProcedure\nExecutes a stored procedure Example_SP using SQL Parameters\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003e$queryParameters = @{\n\u003e\u003e StartDate = $startdate\r\n\u003e\u003e EndDate = $enddate\r\n\u003e\u003e }\r\nPS C:\\\u003e Invoke-DbaQuery -SqlInstance server1 -Database tempdb -Query Example_SP -SqlParameter $queryParameters -CommandType StoredProcedure\nExecutes a stored procedure Example_SP using multiple SQL Parameters\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003e$inparam = @()\nPS C:\\\u003e $inparam += [PSCustomObject]@{\r\n\u003e\u003e somestring = \u0027string1\u0027\r\n\u003e\u003e somedate = \u00272021-07-15T01:02:00\u0027\r\n\u003e\u003e }\r\nPS C:\\\u003e $inparam += [PSCustomObject]@{\r\n\u003e\u003e somestring = \u0027string2\u0027\r\n\u003e\u003e somedate = \u00272021-07-15T02:03:00\u0027\r\n\u003e\u003e }\r\n\u003e\u003e $inparamAsDataTable = ConvertTo-DbaDataTable -InputObject $inparam\r\nPS C:\\\u003e $inparamAsSQLParameter = New-DbaSqlParameter -SqlDbType structured -Value $inparamAsDataTable -TypeName \u0027dbatools_tabletype\u0027\r\nPS C:\\\u003e Invoke-DbaQuery -SqlInstance localhost -Database master -CommandType StoredProcedure -Query my_proc -SqlParameter $inparamAsSQLParameter\nCreates an TVP input parameter and uses it to invoke a stored procedure.\n-------------------------- EXAMPLE 10 --------------------------\nPS C:\\\u003e$output = New-DbaSqlParameter -ParameterName json_result -SqlDbType NVarChar -Size -1 -Direction Output\nPS C:\\\u003e Invoke-DbaQuery -SqlInstance localhost -Database master -CommandType StoredProcedure -Query my_proc -SqlParameter $output\r\nPS C:\\\u003e $output.Value\nCreates an output parameter and uses it to invoke a stored procedure.\n-------------------------- EXAMPLE 11 --------------------------\nPS C:\\\u003e$server = Connect-DbaInstance -SqlInstance localhost -Database master -AlwaysEncrypted\nPS C:\\\u003e $inputparamSSN = New-DbaSqlParameter -Direction Input -ParameterName \"@SSN\" -DbType AnsiStringFixedLength -Size 11 -SqlValue \"444-44-4444\" -ForceColumnEncryption\r\nPS C:\\\u003e Invoke-DbaQuery -SqlInstance $server -Query \u0027SELECT * FROM bar WHERE SSN_col = @SSN\u0027 -SqlParameter @inputparamSSN\nCreates an input parameter using Always Encrypted\n-------------------------- EXAMPLE 12 --------------------------\nPS C:\\\u003e$server = Connect-DbaInstance -SqlInstance AG1 -Database dbatools -MultiSubnetFailover -ConnectTimeout 60\nPS C:\\\u003e Invoke-DbaQuery -SqlInstance $server -Query \u0027SELECT foo FROM bar\u0027\nReuses Connect-DbaInstance, leveraging advanced paramenters, to adhere to official guidelines to target FCI or AG listeners.\r\nSee https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql/sqlclient-support-for-high-availability-disaster-recovery#connecting-with-multisubnetfailover\n-------------------------- EXAMPLE 13 --------------------------\nPS C:\\\u003eInvoke-DbaQuery -SqlInstance AG1 -Query \u0027SELECT foo FROM bar\u0027 -AppendConnectionString \u0027MultiSubnetFailover=true;Connect Timeout=60\u0027\nLeverages your own parameters, giving you full power, mimicking Connect-DbaInstance\u0027s `-MultiSubnetFailover -ConnectTimeout 60`, to adhere to official guidelines to target FCI or AG listeners.\r\nSee https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql/sqlclient-support-for-high-availability-disaster-recovery#connecting-with-multisubnetfailover\n-------------------------- EXAMPLE 14 --------------------------\nPS C:\\\u003eInvoke-DbaQuery -SqlInstance server1 -Database tempdb -Query \"INSERT INTO dbo.TableWithFilteredIndex (Id, Name) VALUES (1, \u0027Test\u0027)\" -QuotedIdentifier\nExecutes an INSERT statement with QUOTED_IDENTIFIER set to ON. This is required when modifying tables that have filtered indexes, as SQL Server requires this setting for such operations.", "Description": "Executes T-SQL commands against one or more SQL Server instances, supporting queries from strings, files, URLs, or SQL Server Management Objects. This is the primary dbatools command for running custom SQL against your environment, whether you\u0027re extracting data for reports, deploying scripts across multiple servers, or running maintenance commands.\n\nThe function provides secure parameterized query execution to prevent SQL injection attacks, making it safe to use with dynamic values. You can target specific databases, execute against Availability Group listeners with ReadOnly intent, and choose from multiple output formats to match your workflow needs.\n\nBuilt for pipeline operations, it accepts multiple instances from Get-DbaRegServer or database collections from Get-DbaDatabase, allowing you to efficiently execute the same query across your entire SQL Server estate. The function handles both simple ad-hoc queries and complex stored procedure calls with input/output parameters, table-valued parameters, and Always Encrypted column support.", "Links": "https://dbatools.io/Invoke-DbaQuery", "Synopsis": "Executes T-SQL queries, scripts, and stored procedures against SQL Server instances with parameterized query support", "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", "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 target database context for query execution. The query will run against this database regardless of any USE statements in the SQL code.\r\nUse this when you need to ensure queries execute in a specific database, particularly when running the same query against multiple instances with different default databases.", "", false, "false", "", "" ], [ "Query", "Contains the T-SQL commands to execute against the target instances. Supports T-SQL statements, XQuery, and SQLCMD commands with GO batch separators.\r\nUse this for ad-hoc queries, maintenance scripts, or data extraction commands. For complex scripts or version-controlled SQL, consider using the File parameter instead.\nEscape any double quotation marks included in the string.\nConsider using bracketed identifiers such as [MyTable] instead of quoted identifiers such as \"MyTable\".", "", true, "false", "", "" ], [ "QueryTimeout", "Sets the command timeout in seconds before the query is cancelled. Defaults to the connection\u0027s default timeout if not specified.\r\nIncrease this value for long-running maintenance operations, large data exports, or complex analytical queries that need more processing time.", "", false, "false", "0", "" ], [ "File", "Specifies file paths, URLs, or directories containing SQL scripts to execute. Supports individual .sql files, entire directories, or HTTP/HTTPS URLs for remote scripts.\r\nUse this for deploying version-controlled SQL scripts, running standardized maintenance routines, or executing scripts downloaded from repositories.", "InputFile", true, "false", "", "" ], [ "SqlObject", "Accepts SQL Server Management Objects (SMO) that will be scripted out and executed on target instances. Works with tables, views, stored procedures, functions, and other database objects.\r\nUse this to deploy database schema changes by passing SMO objects from a source environment to recreate them elsewhere.", "", true, "false", "", "" ], [ "As", "Controls the format of returned query results. Choose \u0027DataRow\u0027 (default) for typical result sets, \u0027PSObject\u0027 for PowerShell-friendly objects, or \u0027SingleValue\u0027 for scalar results.\r\nUse \u0027PSObject\u0027 when you need to pipe results to other PowerShell commands that expect objects. Use \u0027SingleValue\u0027 for queries returning a single value like COUNT(*) or configuration checks.\nPSObject and PSObjectArray output introduces overhead but adds flexibility for working with results: https://forums.powershell.org/t/dealing-with-dbnull/2328/2", "", false, "false", "DataRow", "DataSet,DataTable,DataRow,PSObject,PSObjectArray,SingleValue" ], [ "SqlParameter", "Provides parameters for safe execution of queries with dynamic values, preventing SQL injection attacks. Accepts hashtables or SqlParameter objects from New-DbaSqlParameter.\r\nUse this whenever your queries include user input, dynamic values, or when calling stored procedures with input/output parameters. Essential for secure production scripts. \r\nhttp://blog.codinghorror.com/give-me-parameterized-sql-or-give-me-death/", "SqlParameters", false, "false", "", "" ], [ "CommandType", "Defines how the Query parameter should be interpreted. Use \u0027Text\u0027 (default) for T-SQL statements, \u0027StoredProcedure\u0027 for procedure calls, or \u0027TableDirect\u0027 for direct table access.\r\nSet this to \u0027StoredProcedure\u0027 when calling stored procedures, which enables proper parameter handling and allows the use of output parameters.\r\nFurther information: https://docs.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.commandtype", "", false, "false", "Text", "" ], [ "AppendServerInstance", "Adds the source SQL Server instance name as a column to query results. Particularly useful when running the same query against multiple instances.\r\nUse this when you need to identify which instance produced each row of results, essential for multi-instance reporting and troubleshooting scenarios.", "", false, "false", "False", "" ], [ "MessagesToOutput", "Captures and returns T-SQL PRINT statements, RAISERROR messages, and other informational messages along with query results.\r\nUse this when debugging stored procedures, monitoring script progress, or when you need to see messages that SQL scripts output during execution.", "", false, "false", "False", "" ], [ "InputObject", "Accepts database objects from the pipeline, typically from Get-DbaDatabase. The query will execute against each database in the collection.\r\nUse this to run the same query across multiple databases efficiently, such as checking configuration settings or gathering statistics from all user databases.", "", false, "true (ByValue)", "", "" ], [ "ReadOnly", "Sets the connection to use ReadOnly application intent, directing queries to readable secondary replicas in Availability Groups.\r\nUse this when querying Availability Group listeners to reduce load on primary replicas and take advantage of readable secondaries for reporting workloads.", "", false, "false", "False", "" ], [ "NoExec", "Enables syntax and semantic validation without executing the actual statements. The SQL engine parses and compiles queries but doesn\u0027t run them.\r\nUse this to validate T-SQL syntax, check object references, and verify permissions before running potentially destructive scripts in production environments.", "", false, "false", "False", "" ], [ "QuotedIdentifier", "Prepends SET QUOTED_IDENTIFIER ON to each batch before execution. This is required for INSERT, UPDATE, and DELETE operations on tables with filtered indexes, indexed views, computed columns, or XML \r\nindexes.\r\nUse this when modifying tables with filtered indexes and experiencing silent failures, as SMO connections may have QUOTED_IDENTIFIER set to OFF depending on server/database configuration.", "", false, "false", "False", "" ], [ "AppendConnectionString", "Adds custom connection string parameters for specialized connection requirements like MultiSubnetFailover, encryption settings, or timeout values.\r\nUse this for Availability Group connections, Always Encrypted scenarios, or when you need connection properties not available through standard parameters. Authentication must still be handled via \r\nSqlInstance and SqlCredential.", "", 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", "Support" ], "CommandName": "Invoke-DbatoolsFormatter", "Name": "Invoke-DbatoolsFormatter", "Author": "Simone Bizzotto", "Syntax": "Invoke-DbatoolsFormatter [-Path] \u003cObject[]\u003e [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "None\nThis function performs file formatting operations and writes the formatted content back to the source files. It does not return any objects to the pipeline. Status and error messages are written \r\nusing the dbatools Write-Message function.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbatoolsFormatter -Path C:\\dbatools\\public\\Get-DbaDatabase.ps1\nReformats C:\\dbatools\\public\\Get-DbaDatabase.ps1 to dbatools\u0027 standards", "Description": "Applies consistent code formatting to PowerShell files using PSScriptAnalyzer\u0027s Invoke-Formatter with OTBS (One True Brace Style) settings. This function standardizes indentation, brace placement, and whitespace handling across all dbatools module files, ensuring code consistency for contributors and maintainers. Files are saved without BOM encoding and with proper line ending handling for cross-platform compatibility.", "Links": "https://dbatools.io/Invoke-DbatoolsFormatter", "Synopsis": "Formats PowerShell function files to dbatools coding standards", "Availability": "Windows, Linux, macOS", "Params": [ [ "Path", "Specifies the path to one or more PowerShell (.ps1) files that need to be formatted to dbatools coding standards.\r\nAccepts pipeline input from Get-ChildItem or other file listing commands for batch processing multiple files.\r\nUse this when you want to apply consistent OTBS formatting, proper indentation, and standardized brace placement to your dbatools contributions.", "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": "Module", "CommandName": "Invoke-DbatoolsRenameHelper", "Name": "Invoke-DbatoolsRenameHelper", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Invoke-DbatoolsRenameHelper [-InputObject] \u003cFileInfo[]\u003e [[-Encoding] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per matched pattern found and replaced in each file. If no deprecated command or parameter names are found, nothing is returned.\nProperties:\r\n- Path: The full file path that was updated\r\n- Pattern: The deprecated command or parameter name that was found (e.g., \u0027Get-SqlMaxMemory\u0027, \u0027ExcludeSystem\u0027)\r\n- ReplacedWith: The current equivalent name that replaced the deprecated name (e.g., \u0027Get-DbaMaxMemory\u0027, \u0027ExcludeSystem\u0027)\nObjects are returned for both deprecated command name replacements and parameter name replacements. This allows you to see exactly which deprecated names were found and what they were changed to in \r\neach file.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-ChildItem C:\\temp\\ps\\*.ps1 -Recurse | Invoke-DbatoolsRenameHelper\nChecks to see if any ps1 file in C:\\temp\\ps matches an old command name.\r\nIf so, then the command name within the text is updated and the resulting changes are written to disk in UTF-8.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-ChildItem C:\\temp\\ps\\*.ps1 -Recurse | Invoke-DbatoolsRenameHelper -Encoding Ascii -WhatIf\nShows what would happen if the command would run. If the command would run and there were matches,\r\nthe resulting changes would be written to disk as Ascii encoded.", "Description": "Automatically scans and updates PowerShell script files to replace old dbatools command names and parameter names that have been renamed over time. This function searches through your scripts for over 200 deprecated command names and dozens of parameter renames, then updates the file content with the current naming conventions. Instead of manually hunting through scripts to update commands like Get-SqlMaxMemory to Get-DbaMaxMemory or Copy-SqlLogin to Copy-DbaLogin, this function handles the bulk replacement work for you.", "Links": "https://dbatools.io/Invoke-DbatoolsRenameHelper", "Synopsis": "Updates PowerShell scripts to replace deprecated dbatools command and parameter names with current equivalents.", "Availability": "Windows, Linux, macOS", "Params": [ [ "InputObject", "Specifies the PowerShell script files to scan and update for deprecated dbatools command and parameter names.\r\nAccept file objects from Get-ChildItem when you need to process multiple scripts containing outdated dbatools commands.\r\nUse this when modernizing existing automation scripts or migrating legacy PowerShell code to current dbatools naming conventions.", "", true, "true (ByValue)", "", "" ], [ "Encoding", "Sets the character encoding used when writing the updated script files back to disk. Defaults to UTF8.\r\nUse this when your PowerShell scripts require specific encoding formats for compatibility with source control systems or deployment processes.\r\nMost modern environments work well with the default UTF8 encoding, but legacy systems may require ASCII or other specific encodings.", "", 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", "" ], [ "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", "WhoIsActive" ], "CommandName": "Invoke-DbaWhoIsActive", "Name": "Invoke-DbaWhoIsActive", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Invoke-DbaWhoIsActive [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString\u003e] [[-Filter] \u003cString\u003e] [[-FilterType] \u003cString\u003e] [[-NotFilter] \u003cString\u003e] [[-NotFilterType] \u003cString\u003e] [-ShowOwnSpid] [-ShowSystemSpids] [[-ShowSleepingSpids] \u003cInt32\u003e] [-GetFullInnerText] [[-GetPlans] \u003cInt32\u003e] [-GetOuterCommand] [-GetTransactionInfo] [[-GetTaskInfo] \u003cInt32\u003e] [-GetLocks] [-GetAverageTime] [-GetAdditonalInfo] [-FindBlockLeaders] [[-DeltaInterval] \u003cInt32\u003e] [[-OutputColumnList] \u003cString\u003e] [[-SortOrder] \u003cString\u003e] [[-FormatOutput] \u003cInt32\u003e] [[-DestinationTable] \u003cString\u003e] \r\n[-ReturnSchema] [[-Schema] \u003cString\u003e] [-Help] [[-As] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Output type depends on the -As parameter:\nDataRow (default)\r\n System.Data.DataRow for each row of sp_WhoIsActive results\nDataTable\r\n System.Data.DataTable containing all sp_WhoIsActive result rows with columns for session activity\nDataSet\r\n System.Data.DataSet containing one DataTable from sp_WhoIsActive results\nPSObject\r\n PSCustomObject with properties for each column returned by sp_WhoIsActive\nThe actual properties and columns returned depend on which feature parameters are enabled:\r\n- Base columns include: session_id, sql_text, login_name, start_time, status, host_name, etc.\r\n- GetPlans adds: query_plan (XML execution plan)\r\n- GetLocks adds: locks (XML lock information)\r\n- GetTransactionInfo adds: tran_log_used_percent, tran_start_time, tran_duration_sec\r\n- GetTaskInfo adds: wait_info, tasks, CPU usage information\r\n- GetAverageTime adds: avg_elapsed_time_ms\r\n- DeltaInterval adds: CPU delta, IO delta, and other rate-of-change metrics\r\n- OutputColumnList parameter controls which columns are included in results\nWhen -ReturnSchema or -Schema is specified, a CREATE TABLE statement is returned instead of data.\r\nWhen -DestinationTable is specified, data is inserted to the specified table and no results are returned to PowerShell.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eInvoke-DbaWhoIsActive -SqlInstance sqlserver2014a\nExecute sp_whoisactive on sqlserver2014a. This command expects sp_WhoIsActive to be in the master database. Logs into the SQL Server with Windows credentials.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eInvoke-DbaWhoIsActive -SqlInstance sqlserver2014a -SqlCredential $credential -Database dbatools\nExecute sp_whoisactive on sqlserver2014a. This command expects sp_WhoIsActive to be in the dbatools database. Logs into the SQL Server with SQL Authentication.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eInvoke-DbaWhoIsActive -SqlInstance sqlserver2014a -GetAverageTime\nSimilar to running sp_WhoIsActive @get_avg_time\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eInvoke-DbaWhoIsActive -SqlInstance sqlserver2014a -GetOuterCommand -FindBlockLeaders\nSimilar to running sp_WhoIsActive @get_outer_command = 1, @find_block_leaders = 1", "Description": "Executes Adam Machanic\u0027s sp_WhoIsActive stored procedure to display detailed information about currently running sessions, active queries, and their resource consumption. This is the go-to command for troubleshooting performance issues, identifying blocking chains, and monitoring SQL Server activity in real-time. Provides comprehensive session details including wait statistics, query plans, lock information, and transaction details that would otherwise require querying multiple DMVs manually.\n\nThis command was built with Adam\u0027s permission. To read more about sp_WhoIsActive, please visit:\n\nUpdates: http://sqlblog.com/blogs/adam_machanic/archive/tags/who+is+active/default.aspx\n\nAlso, consider donating to Adam if you find this stored procedure helpful: http://tinyurl.com/WhoIsActiveDonate", "Links": "https://dbatools.io/Invoke-DbaWhoIsActive", "Synopsis": "Retrieves real-time information about active SQL Server sessions and currently running queries", "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", "", "" ], [ "Database", "Specifies the database where sp_WhoIsActive is installed. Defaults to master if not specified.\r\nUse this when you\u0027ve installed sp_WhoIsActive in a different database like a DBA utilities database.", "", false, "false", "", "" ], [ "Filter", "Filters results to include only sessions matching the specified criteria. Supports wildcards (% and _) for pattern matching.\r\nUse this to focus on specific sessions, applications, databases, logins, or hosts when troubleshooting performance issues.\r\nFor session ID filtering, use 0 or an empty string to include all sessions.", "", false, "false", "", "" ], [ "FilterType", "Specifies what type of filtering to apply with the Filter parameter. Valid options: Session, Program, Database, Login, Host.\r\nUse \u0027Program\u0027 to filter by application name, \u0027Login\u0027 to filter by SQL login, or \u0027Host\u0027 to filter by client machine name.", "", false, "false", "Session", "Session,Program,Database,Login,Host" ], [ "NotFilter", "Excludes sessions matching the specified criteria from results. Supports wildcards (% and _) for pattern matching.\r\nUse this to exclude specific applications, databases, or users when you want to focus on everything else.\r\nFor session ID filtering, use 0 or an empty string to exclude no sessions.", "", false, "false", "", "" ], [ "NotFilterType", "Specifies what type of exclusion filtering to apply with the NotFilter parameter. Valid options: Session, Program, Database, Login, Host.\r\nUse this in combination with NotFilter to exclude sessions by application name, database, login, or host.", "", false, "false", "Session", "Session,Program,Database,Login,Host" ], [ "ShowOwnSpid", "Includes the current session (the one running sp_WhoIsActive) in the results.\r\nBy default, your own session is excluded to reduce clutter in the output.", "", false, "false", "False", "" ], [ "ShowSystemSpids", "Includes internal SQL Server system sessions in the results.\r\nUse this when troubleshooting system-level performance issues or investigating background processes.", "", false, "false", "False", "" ], [ "ShowSleepingSpids", "Controls which idle sessions to include based on their transaction status. 0 = no sleeping sessions, 1 = only sleeping sessions with open transactions, 2 = all sleeping sessions.\r\nUse 1 when investigating blocking issues or long-running transactions, or 2 for comprehensive session auditing.", "", false, "false", "0", "" ], [ "GetFullInnerText", "Retrieves the complete SQL batch or stored procedure text instead of just the current statement.\r\nUse this when you need to see the full context of what\u0027s executing, not just the individual statement within a larger batch.", "", false, "false", "False", "" ], [ "GetPlans", "Retrieves execution plans for active queries. 1 = plan for current statement only, 2 = entire plan for the batch or procedure.\r\nEssential for performance troubleshooting to identify inefficient queries, missing indexes, and optimization opportunities.", "", false, "false", "0", "" ], [ "GetOuterCommand", "Captures the original command that initiated the current batch, including stored procedure calls with parameters.\r\nUseful for understanding the full call stack when procedures call other procedures or dynamic SQL.", "", false, "false", "False", "" ], [ "GetTransactionInfo", "Includes transaction log usage and duration information for active sessions.\r\nCritical for identifying sessions with long-running transactions that may cause blocking or log space issues.", "", false, "false", "False", "" ], [ "GetTaskInfo", "Controls task and wait information collection. 0 = no task info, 1 = lightweight mode with primary waits and blockers, 2 = comprehensive task metrics including I/O and context switches.\r\nUse level 1 for general troubleshooting or level 2 for detailed performance analysis when you need full wait statistics.", "", false, "false", "0", "" ], [ "GetLocks", "Retrieves detailed lock information for each session in XML format.\r\nEssential for troubleshooting blocking issues and understanding what resources sessions are waiting for or holding.", "", false, "false", "False", "" ], [ "GetAverageTime", "Calculates the average execution time for the currently running query based on historical execution data.\r\nHelps identify queries that are running longer than usual, indicating potential performance degradation.", "", false, "false", "False", "" ], [ "GetAdditonalInfo", "Includes session configuration details like ANSI settings, isolation level, language, and command type information.\r\nUseful for troubleshooting application-specific issues where session settings affect query behavior or when investigating SQL Agent job activity.", "", false, "false", "False", "" ], [ "FindBlockLeaders", "Identifies the root cause sessions in blocking chains and counts how many sessions each one is blocking.\r\nCritical for resolving blocking issues by showing you which sessions to focus on first when multiple blocking chains exist.", "", false, "false", "False", "" ], [ "DeltaInterval", "Captures performance metrics at two points in time separated by the specified interval (in seconds) to show rate-of-change data.\r\nExcellent for identifying which sessions are actively consuming CPU, I/O, or memory resources during the measurement period.", "", false, "false", "0", "" ], [ "OutputColumnList", "Specifies which columns to include in the results and their display order using bracket-delimited column names.\r\nCustomize this to focus on specific metrics or reduce output complexity for your monitoring scenarios.\r\nOnly columns related to enabled features will actually appear in the output.", "", false, "false", "[dd%][session_id][sql_text][sql_command][login_name][wait_info][tasks][tran_log%][cpu%][temp%][block%][reads%][writes%][context%][physical%][query_plan][locks][%]", "" ], [ "SortOrder", "Controls how results are sorted using bracket-delimited column names with optional ASC/DESC direction.\r\nSort by CPU, physical_io, or start_time to quickly identify the most resource-intensive or longest-running sessions.\r\nDefaults to sorting by start_time in ascending order.", "", false, "false", "[start_time] ASC", "" ], [ "FormatOutput", "Controls output formatting for better readability. 0 = no formatting, 1 = variable-width fonts (default), 2 = fixed-width fonts.\r\nUse 2 when displaying results in console windows or fixed-width displays for better column alignment.", "", false, "false", "1", "" ], [ "DestinationTable", "Inserts results directly into a specified table instead of returning them to PowerShell.\r\nUseful for automated monitoring scripts or building historical performance data repositories.\r\nTable must already exist with the correct schema structure.", "", false, "false", "", "" ], [ "ReturnSchema", "Returns a CREATE TABLE statement showing the schema structure needed for the DestinationTable instead of collecting data.\r\nUse this to generate the correct table structure before setting up automated data collection with DestinationTable.", "", false, "false", "False", "" ], [ "Schema", "Alternative parameter name for ReturnSchema functionality.\r\nReturns a CREATE TABLE statement for the result set structure instead of collecting actual data.", "", false, "false", "", "" ], [ "Help", "Returns detailed help information about sp_WhoIsActive parameters and their usage instead of executing the procedure.\r\nUse this to understand all available options when you\u0027re unsure which parameters to use for your specific troubleshooting scenario.", "", false, "false", "False", "" ], [ "As", "Specifies the PowerShell output format. Options: DataSet, DataTable, DataRow (default), PSObject.\r\nUse PSObject for advanced scripting scenarios where you need better handling of null values and type conversion.", "", false, "false", "DataRow", "DataSet,DataTable,DataRow,PSObject" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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": "Invoke-DbaXEReplay", "Name": "Invoke-DbaXEReplay", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Invoke-DbaXEReplay [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-Event] \u003cString[]\u003e] [-InputObject] \u003cObject\u003e [-Raw] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.String\nReturns the output from sqlcmd execution. The exact content depends on the SQL queries being replayed.\nWhen -Raw is specified, all sqlcmd output is returned unmodified, including headers and formatting lines.\nWhen -Raw is not specified, output is filtered to remove sqlcmd formatting lines and column headers (lines containing only dashes), but query results and messages remain intact.\nIf an error occurs during replay, the error message from sqlcmd is returned as a string. If no output is produced by the queries, nothing is returned.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRead-DbaXEFile -Path C:\\temp\\sample.xel | Invoke-DbaXEReplay -SqlInstance sql2017\nRuns all batch_text for sql_batch_completed against tempdb on sql2017.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRead-DbaXEFile -Path C:\\temp\\sample.xel | Invoke-DbaXEReplay -SqlInstance sql2017 -Database planning -Event sql_batch_completed\nSets the *initial* database to planning then runs only sql_batch_completed against sql2017.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRead-DbaXEFile -Path C:\\temp\\sample.xel | Invoke-DbaXEReplay -SqlInstance sql2017, sql2016\nRuns all batch_text for sql_batch_completed against tempdb on sql2017 and sql2016.", "Description": "This command replays SQL workloads captured in Extended Event files against one or more target SQL Server instances for performance testing and load simulation. It extracts SQL statements from Extended Event data piped from Read-DbaXEFile and executes them sequentially against your specified targets.\n\nThe function works by collecting SQL queries from the Extended Event stream, writing them to a temporary SQL file with proper batch separators, then executing the file using sqlcmd to ensure batches run correctly. This approach allows you to replay production workloads in test environments to validate performance changes, test capacity, or troubleshoot query behavior under realistic conditions.\n\nBy default, it processes sql_batch_completed and rcp_completed events, but you can filter to specific event types. The replay maintains the original SQL structure while allowing you to redirect the workload to different databases or instances as needed.", "Links": "https://dbatools.io/Invoke-DbaXEReplay", "Synopsis": "Replays SQL queries captured in Extended Event files against target SQL Server instances", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "Target SQL Server(s)", "", 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", "Sets the initial database context for the replayed SQL statements. This determines which database sqlcmd connects to before executing the captured queries.\r\nUse this when you need to replay workloads in a specific database context, especially when the captured queries don\u0027t include explicit database references.", "", false, "false", "", "" ], [ "Event", "Filters which Extended Event types to replay from the input stream. Defaults to sql_batch_completed and rcp_completed events.\r\nUse this to replay only specific event types when you want to test particular workload patterns or exclude certain query types from the replay.", "", false, "false", "@(\u0027sql_batch_completed\u0027, \u0027rcp_completed\u0027)", "" ], [ "InputObject", "Accepts Extended Event objects from Read-DbaXEFile or Read-DbaXESession containing captured SQL statements for replay.\r\nThis is typically piped from Read-DbaXEFile when processing Extended Event files or from Read-DbaXESession for live session data.", "", true, "true (ByValue)", "", "" ], [ "Raw", "Shows all sqlcmd output immediately without cleanup or formatting. By default, results are collected, cleaned, and filtered for readability.\r\nUse this when you need to see complete sqlcmd output including headers and formatting, or when troubleshooting query execution issues during replay.", "", 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": [ "AG", "HA" ], "CommandName": "Join-DbaAvailabilityGroup", "Name": "Join-DbaAvailabilityGroup", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Join-DbaAvailabilityGroup [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-AvailabilityGroup] \u003cString[]\u003e] [[-ClusterType] \u003cString\u003e] [[-InputObject] \u003cAvailabilityGroup[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "None\nThis command does not return any objects. It modifies the SQL Server instance configuration by joining an existing availability group on the secondary replica.\nThe command succeeds silently when the availability group is successfully joined. If any errors occur during the join operation, they are caught and reported via Stop-Function.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sql01 -AvailabilityGroup SharePoint | Join-DbaAvailabilityGroup -SqlInstance sql02\nJoins sql02 to the SharePoint availability group on sql01\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$ag = Get-DbaAvailabilityGroup -SqlInstance sql01 -AvailabilityGroup SharePoint\nPS C:\\\u003e Join-DbaAvailabilityGroup -SqlInstance sql02 -InputObject $ag\nJoins sql02 to the SharePoint availability group on sql01\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sql01 -AvailabilityGroup SharePoint | Join-DbaAvailabilityGroup -SqlInstance sql02 -WhatIf\nShows what would happen if the command were to run. No actions are actually performed.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sql01 -AvailabilityGroup SharePoint | Join-DbaAvailabilityGroup -SqlInstance sql02 -Confirm\nPrompts for confirmation then joins sql02 to the SharePoint availability group on sql01.", "Description": "Adds a SQL Server instance as a secondary replica to an existing availability group that has already been created on the primary replica. This command is typically used after creating the availability group on the primary server and before adding databases to the group. The target instance must have the availability group feature enabled and be properly configured for high availability. For SQL Server 2017 and later, you can specify the cluster type (External, Wsfc, or None) to match your environment\u0027s configuration.", "Links": "https://dbatools.io/Join-DbaAvailabilityGroup", "Synopsis": "Adds a SQL Server instance as a secondary replica to an existing availability group.", "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 the name of the availability group that the target instance will join as a secondary replica.\r\nUse this when you need to add a secondary replica to an existing availability group that was created on the primary server.", "", false, "false", "", "" ], [ "ClusterType", "Specifies the cluster type for the availability group when joining SQL Server 2017 or later instances.\r\nUse \u0027Wsfc\u0027 for Windows Server Failover Clustering, \u0027External\u0027 for Linux cluster managers like Pacemaker, or \u0027None\u0027 for read-scale availability groups without clustering.\r\nIf not specified, the cluster type is automatically detected from the existing availability group.", "", false, "false", "", "External,Wsfc,None" ], [ "InputObject", "Accepts availability group objects from Get-DbaAvailabilityGroup for pipeline operations.\r\nUse this when you want to retrieve availability group details from the primary replica and pipe them directly to join secondary replicas.\r\nThe availability group name and cluster type are automatically extracted from the input object.", "", 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": [ "Path", "Utility" ], "CommandName": "Join-DbaPath", "Name": "Join-DbaPath", "Author": "Friedrich Weinmann (@FredWeinmann)", "Syntax": "Join-DbaPath [-Path] \u003cString\u003e [-SqlInstance \u003cDbaInstanceParameter\u003e] [-Child \u003cString[]\u003e] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.String\nReturns a single string containing the constructed file path with the appropriate path separators for the target system.\nWhen no -SqlInstance is specified, the path uses the local computer\u0027s separator convention.\r\nWhen -SqlInstance targets a Linux SQL Server, forward slashes (/) are used as separators.\r\nWhen -SqlInstance targets a Windows SQL Server, backslashes (\\) are used as separators.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eJoin-DbaPath -Path \u0027C:\\temp\u0027 \u0027Foo\u0027 \u0027Bar\u0027\nReturns \u0027C:\\temp\\Foo\\Bar\u0027 on windows.\r\nReturns \u0027C:/temp/Foo/Bar\u0027 on non-windows.", "Description": "Constructs file paths by joining multiple segments while automatically using the correct path separators (backslash for Windows, forward slash for Linux) based on the target SQL Server instance\u0027s operating system. This function eliminates the guesswork when building file paths for backup files, exports, scripts, or other SQL Server operations that need to reference files on the remote server. Without specifying a SqlInstance, it defaults to the local machine\u0027s path separator conventions.", "Links": "https://dbatools.io/Join-DbaPath", "Synopsis": "Constructs file paths with correct separators for Windows and Linux SQL Server instances.", "Availability": "Windows, Linux, macOS", "Params": [ [ "Path", "Specifies the base directory path where backup files, scripts, or other SQL Server resources will be stored. This forms the root location for building complete file paths.\r\nUse this when you need to define the starting directory for backup operations, export locations, or script file destinations on either local or remote SQL Server instances.", "", true, "false", "", "" ], [ "SqlInstance", "Optional -- tests to see if destination SQL Server is Linux or Windows", "", false, "false", "", "" ], [ "Child", "Specifies additional path segments to append to the base path, such as subdirectories, filename prefixes, or date folders. Accepts multiple values to build nested directory structures.\r\nUse this to organize files into logical groupings like database names, backup types, or date-based folders (e.g., \u0027MyDatabase\u0027, \u0027Full\u0027, \u00272024-01-15\u0027).", "ChildPath", false, "false", "", "" ] ] }, { "Tags": [ "Backup", "Database" ], "CommandName": "Measure-DbaBackupThroughput", "Name": "Measure-DbaBackupThroughput", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Measure-DbaBackupThroughput [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-Since] \u003cDateTime\u003e] [-Last] [[-Type] \u003cString\u003e] [[-DeviceType] \u003cString[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database analyzed, containing aggregated backup throughput statistics across the backup history.\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 being analyzed\r\n- AvgThroughput: Average backup throughput in megabytes per second; DbaSize object with unit conversion properties (.Megabyte, .Gigabyte, etc.)\r\n- AvgSize: Average backup size; DbaSize object with unit conversion properties\r\n- AvgDuration: Average time required for backups; DbaTimeSpan object representing time span\r\n- MinThroughput: Minimum backup throughput observed; DbaSize object\r\n- MaxThroughput: Maximum backup throughput observed; DbaSize object\r\n- MinBackupDate: DateTime of the earliest backup in the analyzed time period; DbaDateTime object\r\n- MaxBackupDate: DateTime of the most recent backup in the analyzed time period; DbaDateTime object\r\n- BackupCount: Total number of backups analyzed for this database (int)\nAll size and throughput values use dbasize objects that automatically format to appropriate units (Bytes, KB, MB, GB, TB) when displayed.\r\nThe DbaTimeSpan and DbaDateTime objects provide specialized handling for time values with automatic formatting.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eMeasure-DbaBackupThroughput -SqlInstance sql2016\nParses every backup in msdb\u0027s backuphistory for stats on all databases.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eMeasure-DbaBackupThroughput -SqlInstance sql2016 -Database AdventureWorks2014\nParses every backup in msdb\u0027s backuphistory for stats on AdventureWorks2014.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eMeasure-DbaBackupThroughput -SqlInstance sql2005 -Last\nProcesses the last full, diff and log backups every backup for all databases on sql2005.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eMeasure-DbaBackupThroughput -SqlInstance sql2005 -Last -Type Log\nProcesses the last log backups every backup for all databases on sql2005.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eMeasure-DbaBackupThroughput -SqlInstance sql2016 -Since (Get-Date).AddDays(-7) | Where-Object { $_.MinThroughput.Gigabyte -gt 1 }\nGets backup calculations for the last week and filters results that have a minimum of 1GB throughput\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eMeasure-DbaBackupThroughput -SqlInstance sql2016 -Since (Get-Date).AddDays(-365) -Database bigoldb\nGets backup calculations, limited to the last year and only the bigoldb database", "Description": "Analyzes backup history records from the msdb database to calculate detailed throughput statistics including average, minimum, and maximum backup speeds measured in megabytes per second. This function helps DBAs identify performance patterns, troubleshoot slow backups, and optimize backup strategies by examining historical backup performance data.\n\nThe function processes backup records for specified databases and time periods, calculating throughput by dividing backup size by duration. Results include comprehensive statistics like average backup size, duration ranges, throughput metrics, and backup frequency counts. This data is essential for capacity planning, identifying storage bottlenecks, and ensuring backup windows meet your RTO requirements.\n\nOutput includes detailed metrics per database showing average throughput, size patterns, duration statistics, and backup count summaries. You can filter by backup type (full, differential, log), time ranges, or specific databases to focus your performance analysis on particular scenarios or problem areas.\n\nOutput looks like this:\nSqlInstance : sql2016\nDatabase : SharePoint_Config\nAvgThroughput : 1.07 MB\nAvgSize : 24.17\nAvgDuration : 00:00:01.1000000\nMinThroughput : 0.02 MB\nMaxThroughput : 2.26 MB\nMinBackupDate : 8/6/2015 10:22:01 PM\nMaxBackupDate : 6/19/2016 12:57:45 PM\nBackupCount : 10", "Links": "https://dbatools.io/Measure-DbaBackupThroughput", "Synopsis": "Calculates backup throughput statistics from msdb backup history to analyze backup 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 backup throughput statistics. Accepts wildcards for pattern matching.\r\nUse this when you need to focus performance analysis on specific databases rather than analyzing all databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies databases to exclude from throughput analysis. Accepts wildcards for pattern matching.\r\nUse this to remove system databases or problematic databases from your performance analysis without affecting other databases.", "", false, "false", "", "" ], [ "Since", "Filters backup history to analyze only backups taken on or after the specified date and time.\r\nUse this to focus your throughput analysis on recent backups or compare performance before and after infrastructure changes. Accepts standard PowerShell datetime formats.", "", false, "false", "", "" ], [ "Last", "Analyzes only the most recent backup for each database instead of processing the entire backup history.\r\nUse this for quick performance checks or when you only need current backup throughput statistics rather than historical trends.", "", false, "false", "False", "" ], [ "Type", "Specifies which backup type to analyze for throughput calculations. Valid options include \"Full\", \"Log\", \"Differential\", \"File\", \"Differential File\", \"Partial Full\", and \"Partial Differential\".\r\nUse this to analyze specific backup types when troubleshooting performance issues or comparing different backup strategies. Defaults to \"Full\" backups.", "", false, "false", "Full", "Full,Log,Differential,File,Differential File,Partial Full,Partial Differential" ], [ "DeviceType", "Filters analysis to specific backup device types such as \"Disk\", \"Tape\", \"Virtual Device\", or their permanent counterparts.\r\nUse this to compare throughput performance between different backup destinations or troubleshoot specific backup infrastructure components. Accepts custom integer values for specialized backup \r\ndevices.", "", 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", "VLF", "LogFile" ], "CommandName": "Measure-DbaDbVirtualLogFile", "Name": "Measure-DbaDbVirtualLogFile", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Measure-DbaDbVirtualLogFile [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-IncludeSystemDBs] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database containing virtual log file (VLF) statistics and transaction log growth configuration.\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- Total: Total count of VLFs in the transaction log\nAdditional properties available:\r\n- TotalCount: Duplicate of Total (total count of VLFs)\r\n- Inactive: Count of inactive VLFs (status = 0)\r\n- Active: Count of active VLFs (status = 2)\r\n- LogFileName: Comma-separated list of logical names of the transaction log files\r\n- LogFileGrowth: Comma-separated list of growth increment values for each log file\r\n- LogFileGrowthType: Comma-separated list of growth types (Percent or kb) for each log file\nUse Select-Object * to access all properties.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eMeasure-DbaDbVirtualLogFile -SqlInstance sqlcluster\nReturns all user database virtual log file counts for the sqlcluster instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eMeasure-DbaDbVirtualLogFile -SqlInstance sqlserver | Where-Object {$_.Total -ge 50}\nReturns user databases that have 50 or more VLFs.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e@(\u0027sqlserver\u0027,\u0027sqlcluster\u0027) | Measure-DbaDbVirtualLogFile\nReturns all VLF information for the sqlserver and sqlcluster SQL Server instances. Processes data via the pipeline.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eMeasure-DbaDbVirtualLogFile -SqlInstance sqlcluster -Database db1, db2\nReturns VLF counts for the db1 and db2 databases on sqlcluster.", "Description": "Analyzes Virtual Log File (VLF) fragmentation across databases by counting total, active, and inactive VLFs in transaction logs. This function helps identify databases with excessive VLF counts that can severely impact performance.\n\nHigh VLF counts (typically over 50-100) cause transaction log backups to slow down, extend database recovery times, and in extreme cases can affect insert/update/delete operations. This commonly happens when transaction logs auto-grow frequently in small increments rather than being pre-sized appropriately.\n\nThe function returns VLF counts along with log file growth settings, making it easy to spot databases that need log file maintenance. Use this for regular health checks, performance troubleshooting, or before major maintenance windows.\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-SqlTLogResponsibly to reduce the number.", "Links": "https://dbatools.io/Measure-DbaDbVirtualLogFile", "Synopsis": "Measures Virtual Log File (VLF) counts in transaction logs to identify performance bottlenecks", "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 counts. Accepts database names, wildcards, or arrays of database names.\r\nUse this to focus VLF analysis on specific databases when troubleshooting performance issues or during targeted maintenance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies databases to skip during VLF analysis. Accepts database names, wildcards, or arrays of database names.\r\nUse this to exclude problematic databases or those you know are healthy when running instance-wide VLF checks.", "", false, "false", "", "" ], [ "IncludeSystemDBs", "Includes system databases (master, model, msdb, tempdb) in the VLF analysis.\r\nBy default only user databases are analyzed 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": [ "Diagnostic", "Storage", "Space", "Database" ], "CommandName": "Measure-DbaDiskSpaceRequirement", "Name": "Measure-DbaDiskSpaceRequirement", "Author": "Pollus Brodeur (@pollusb)", "Syntax": "Measure-DbaDiskSpaceRequirement [-Source] \u003cDbaInstanceParameter\u003e [-Database] \u003cString\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter\u003e [[-DestinationDatabase] \u003cString\u003e] [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database file analyzed during migration planning. Multiple objects are returned for databases with multiple files (one per file). Objects are returned for three scenarios: \r\nfiles on both source and destination, files only on source, or files only on destination.\nDefault display properties (via Select-DefaultView):\r\n- SourceSqlInstance: The full SQL Server instance name of the source (computer\\instance)\r\n- SourceDatabase: Name of the source database\r\n- SourceLogicalName: Logical name of the database file on the source\r\n- SourceFileName: Operating system file path of the source file\r\n- SourceFileSize: DbaSize object of the source file size (bytes, converts to KB/MB/GB/TB)\r\n- DestinationComputerName: The computer name of the destination SQL Server instance\r\n- DestinationSqlInstance: The full SQL Server instance name of the destination (computer\\instance)\r\n- DestinationDatabase: Name of the destination database (may differ from source if renamed)\r\n- DestinationFileName: Operating system file path of the destination file (null if file only on source)\r\n- DestinationFileSize: DbaSize object of destination file size; null or 0 if file only on source (displayed as negative value when present)\r\n- DifferenceSize: DbaSize object showing the difference in file size between source and destination\r\n- MountPoint: The volume mount point where the destination file is or will be located\r\n- FileLocation: Scenario description - \"Source and Destination\", \"Only on Source\", or \"Only on Destination\"\nHidden properties (available via Select-Object *):\r\n- SourceComputerName: The computer name of the source SQL Server instance\r\n- SourceInstance: The SQL Server instance name of the source\r\n- DestinationInstance: The SQL Server instance name of the destination\r\n- DestinationLogicalName: Logical name of the destination file (null if file only on source)\r\n- SourceDatabaseName: Source database name (used in \"Only on Destination\" scenario)\r\n- DestinationDatabaseName: Destination database name (used in \"Only on Destination\" scenario)\nUse Select-Object * to access all properties including hidden ones.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eMeasure-DbaDiskSpaceRequirement -Source INSTANCE1 -Database DB1 -Destination INSTANCE2\nCalculate space needed for a simple migration with one database with the same name at destination.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e@(\n\u003e\u003e [PSCustomObject]@{Source=\u0027SQL1\u0027;Destination=\u0027SQL2\u0027;Database=\u0027DB1\u0027},\r\n\u003e\u003e [PSCustomObject]@{Source=\u0027SQL1\u0027;Destination=\u0027SQL2\u0027;Database=\u0027DB2\u0027}\r\n\u003e\u003e ) | Measure-DbaDiskSpaceRequirement\nUsing a PSCustomObject with 2 databases to migrate on SQL2.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eImport-Csv -Path .\\migration.csv -Delimiter \"`t\" | Measure-DbaDiskSpaceRequirement | Format-Table -AutoSize\nUsing a CSV file. You will need to use this header line \"Source\u003ctab\u003eDestination\u003ctab\u003eDatabase\u003ctab\u003eDestinationDatabase\".\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$qry = \"SELECT Source, Destination, Database FROM dbo.Migrations\"\nPS C:\\\u003e Invoke-DbaCmd -SqlInstance DBA -Database Migrations -Query $qry | Measure-DbaDiskSpaceRequirement\nUsing a SQL table. We are DBA after all!", "Description": "Analyzes database files on source and destination instances to calculate space requirements before migration. Shows file size differences, mount points, and identifies potential overwrites when copying databases between SQL Server instances.\n\nThe function compares data and log files from the source database against existing files on the destination, accounting for scenarios where files exist only on source, only on destination, or on both sides. This prevents migration failures due to insufficient disk space and helps plan storage allocation.\n\nAccepts pipeline input with Source, Database, and Destination properties, making it ideal for bulk migration planning from CSV files, SQL queries, or PowerShell objects.", "Links": "https://dbatools.io/Measure-DbaDiskSpaceRequirement", "Synopsis": "Calculates disk space requirements for database migration between SQL Server instances", "Availability": "Windows, Linux, macOS", "Params": [ [ "Source", "Specifies the source SQL Server instance containing the database to analyze for migration.\r\nThis is where the database currently exists and from which file sizes will be measured.", "", true, "true (ByPropertyName)", "", "" ], [ "Database", "Specifies the name of the database to analyze on the source instance.\r\nThe database must exist on the source server as the function reads actual file sizes from this database.", "", true, "true (ByPropertyName)", "", "" ], [ "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, "true (ByPropertyName)", "", "" ], [ "Destination", "Specifies the destination SQL Server instance where the database will be migrated.\r\nUsed to determine target file paths, check for existing databases with the same name, and calculate mount point requirements.", "", true, "true (ByPropertyName)", "", "" ], [ "DestinationDatabase", "Specifies the database name to use on the destination instance if different from the source database name.\r\nWhen omitted, the destination database will use the same name as the source database.\r\nUseful when migrating databases that need to be renamed or when avoiding naming conflicts on the destination server.", "", false, "true (ByPropertyName)", "", "" ], [ "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, "true (ByPropertyName)", "", "" ], [ "Credential", "The credentials to use to connect via CIM/WMI/PowerShell remoting.", "", false, "true (ByPropertyName)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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", "Support" ], "CommandName": "Measure-DbatoolsImport", "Name": "Measure-DbatoolsImport", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Measure-DbatoolsImport [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per dbatools module initialization step that took measurable time to complete. The timing data includes steps for loading the dbatools library, type aliases, internal commands, \r\nexternal commands, and other initialization operations.\nProperties:\r\n- Name: Name of the initialization step (e.g., \"Importing Type Aliases\", \"Loading Internal Commands\")\r\n- Duration: TimeSpan representing how long the step took to complete; only steps with Duration greater than 00:00:00 are returned", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eMeasure-DbatoolsImport\nDisplays the import load times of the dbatools PowerShell module\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eImport-Module dbatools\nPS C:\\\u003e Measure-DbatoolsImport\nDisplays the import load times of the dbatools PowerShell module", "Description": "Returns performance data collected during the dbatools module import process, showing the duration of each import step. This function helps troubleshoot slow module loading times by identifying which components take the longest to initialize. The timing data includes loading the dbatools library, type aliases, internal commands, external commands, and other initialization steps. Only displays steps that took measurable time (greater than 00:00:00) to complete.", "Links": "https://dbatools.io/Measure-DbatoolsImport", "Synopsis": "Measures and displays detailed timing metrics for dbatools module import operations", "Availability": "Windows, Linux, macOS", "Params": [ ] }, { "Tags": [ "Attach", "Database" ], "CommandName": "Mount-DbaDatabase", "Name": "Mount-DbaDatabase", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Mount-DbaDatabase [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Database] \u003cString[]\u003e [[-FileStructure] \u003cStringCollection\u003e] [[-DatabaseOwner] \u003cString\u003e] [[-AttachOption] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "Attach-DbaDatabase", "Outputs": "PSCustomObject\nReturns one object per database successfully attached to 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 format)\r\n- Database: The name of the database that was attached\r\n- AttachResult: Status of the attach operation (always \"Success\" when returned)\r\n- AttachOption: The attach option that was used (None, RebuildLog, EnableBroker, NewBroker, or ErrorBrokerConversations)\r\n- FileStructure: System.Collections.Specialized.StringCollection containing the file paths that were attached", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$fileStructure = New-Object System.Collections.Specialized.StringCollection\nPS C:\\\u003e $fileStructure.Add(\"E:\\archive\\example.mdf\")\r\nPS C:\\\u003e $filestructure.Add(\"E:\\archive\\example.ldf\")\r\nPS C:\\\u003e $filestructure.Add(\"E:\\archive\\example.ndf\")\r\nPS C:\\\u003e Mount-DbaDatabase -SqlInstance sql2016 -Database example -FileStructure $fileStructure\nAttaches a database named \"example\" to sql2016 with the files \"E:\\archive\\example.mdf\", \"E:\\archive\\example.ldf\" and \"E:\\archive\\example.ndf\". The database owner will be set to sa and the attach \r\noption is None.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eMount-DbaDatabase -SqlInstance sql2016 -Database example\nSince the FileStructure was not provided, this command will attempt to determine it based on backup history. If found, a database named example will be attached to sql2016.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eMount-DbaDatabase -SqlInstance sql2016 -Database example -WhatIf\nShows what would happen if the command were executed (without actually performing the command)", "Description": "Attaches detached database files (.mdf, .ldf, .ndf) back to a SQL Server instance, making the database available for use again. When database files exist on disk but the database is not registered in the SQL Server instance, this command reconnects them using the SQL Server Management Objects (SMO) AttachDatabase method.\n\nIf you don\u0027t specify the file structure, the command attempts to determine the correct database files by examining backup history for the most recent full backup. This is particularly useful when restoring databases from file copies or moving databases between instances where the files already exist but need to be reattached.", "Links": "https://dbatools.io/Mount-DbaDatabase", "Synopsis": "Attaches detached database files to a SQL Server instance", "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 the names of the detached databases to attach to the SQL Server instance.\r\nUse this when you have database files (.mdf, .ldf, .ndf) on disk but the database is no longer registered in SQL Server.", "", true, "false", "", "" ], [ "FileStructure", "Specifies the complete collection of database file paths (.mdf, .ldf, .ndf) required to attach the database.\r\nWhen omitted, the command attempts to determine file locations automatically using backup history from the most recent full backup.\r\nUse this parameter when files are in non-standard locations or when automatic detection fails.", "", false, "false", "", "" ], [ "DatabaseOwner", "Sets the login account that will own the attached database.\r\nWhen not specified, defaults to the sa account or the SQL Server sysadmin with ID 1 if sa is not available.\r\nUse this to assign ownership to a specific login for security or administrative requirements.", "", false, "false", "", "" ], [ "AttachOption", "Controls how SQL Server handles the database attachment process and Service Broker configuration.\r\nUse \u0027RebuildLog\u0027 when transaction log files are missing or corrupt, \u0027EnableBroker\u0027 to activate Service Broker, or \u0027NewBroker\u0027 to create a new Service Broker identifier.\r\nDefaults to \u0027None\u0027 for standard attachment without special handling.", "", false, "false", "None", "None,RebuildLog,EnableBroker,NewBroker,ErrorBrokerConversations" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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": [ "Database", "Move", "File" ], "CommandName": "Move-DbaDbFile", "Name": "Move-DbaDbFile", "Author": "Claudio Silva (@claudioessilva), claudioeesilva.eu", "Syntax": "Move-DbaDbFile -SqlInstance \u003cDbaInstanceParameter\u003e [-SqlCredential \u003cPSCredential\u003e] -Database \u003cString\u003e [-FileType \u003cString\u003e] [-FileDestination \u003cString\u003e] [-DeleteAfterMove] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nMove-DbaDbFile -SqlInstance \u003cDbaInstanceParameter\u003e [-SqlCredential \u003cPSCredential\u003e] -Database \u003cString\u003e [-FileToMove \u003cHashtable\u003e] [-DeleteAfterMove] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nMove-DbaDbFile -SqlInstance \u003cDbaInstanceParameter\u003e [-SqlCredential \u003cPSCredential\u003e] -Database \u003cString\u003e [-FileStructureOnly] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.String (when -FileStructureOnly is specified)\nReturns the current file structure as a formatted PowerShell hashtable template showing logical file names and their current directory paths. This can be used as input for the FileToMove parameter.\r\nExample: $fileToMove=@{\u0027MyDB_Data\u0027=\u0027D:\\Data\u0027; \u0027MyDB_Log\u0027=\u0027D:\\Logs\u0027}\nPSCustomObject (default)\nReturns one object per database file processed during the move operation. Each object represents the result of moving a single logical database file.\nProperties:\r\n- Instance: The target SQL Server instance name\r\n- Database: The name of the database containing the file\r\n- LogicalName: The logical name of the database file within SQL Server\r\n- Source: The original physical file path before the move\r\n- Destination: The new physical file path after the move\r\n- Result: Status of the operation (Success, Failed, or Already exists. Skipping)\r\n- DatabaseFileMetadata: Status of SQL Server metadata update (Updated, N/A if file copy failed, or N/A if file already exists)\r\n- SourceFileDeleted: Boolean indicating if source file was deleted (True, False) or N/A if not deleted or copy failed", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eMove-DbaDbFile -SqlInstance sql2017 -Database dbatools -FileType Data -FileDestination D:\\DATA2\nCopy all data files of dbatools database on sql2017 instance to the \"D:\\DATA2\" path.\r\nBefore it puts database offline and after copy each file will update database metadata and it ends by set the database back online\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$fileToMove=@{\n\u003e\u003e \u0027dbatools\u0027=\u0027D:\\DATA3\u0027\r\n\u003e\u003e \u0027dbatools_log\u0027=\u0027D:\\LOG2\u0027\r\n\u003e\u003e }\r\nPS C:\\\u003e Move-DbaDbFile -SqlInstance sql2019 -Database dbatools -FileToMove $fileToMove\nDeclares a hashtable that says for each logical file the new path.\r\nCopy each dbatools database file referenced on the hashtable on the sql2019 instance from the current location to the new mentioned location (D:\\DATA3 and D:\\LOG2 paths).\r\nBefore it puts database offline and after copy each file will update database metadata and it ends by set the database back online\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eMove-DbaDbFile -SqlInstance sql2017 -Database dbatools -FileStructureOnly\nShows the current database file structure (without filenames). Example: \u0027dbatools\u0027=\u0027D:\\Data\u0027", "Description": "Relocates database data and log files to new locations on the same SQL Server instance. The function takes the database offline, copies files to the new location, updates the database metadata with ALTER DATABASE commands, and brings the database back online.\n\nThis is typically used when you need to move databases to faster storage, free up disk space, or reorganize your file layout without restoring from backup. The function handles both local and remote SQL Server instances, preserves file permissions, and optionally removes the original files after successful moves.", "Links": "https://dbatools.io/Move-DbaDbFile", "Synopsis": "Relocates database files to different drives or folders while maintaining database integrity.", "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 the user database whose files will be relocated to new paths.\r\nSystem databases (master, model, msdb, tempdb) are not supported for safety reasons.", "", true, "false", "", "" ], [ "FileType", "Specifies which file types to relocate: Data, Log, or Both (default).\r\nUse this with FileDestination when you want to move all files of a specific type to the same directory.\r\nCannot be combined with FileToMove parameter as they serve different movement strategies.", "", false, "false", "", "Data,Log,Both" ], [ "FileDestination", "Sets the target directory where all selected database files will be moved.\r\nUsed with FileType parameter to move all data files, log files, or both to a single location.\r\nMust be accessible to the SQL Server service account and have sufficient space for the files.", "", false, "false", "", "" ], [ "FileToMove", "Defines specific file movements using a hashtable where keys are logical file names and values are destination directory paths.\r\nUse this when you need granular control over where each file goes, like separating data and log files to different drives.\r\nExample: @{\u0027MyDB_Data\u0027=\u0027E:\\Data\u0027; \u0027MyDB_Log\u0027=\u0027F:\\Logs\u0027}", "", false, "false", "", "" ], [ "DeleteAfterMove", "Removes the original database files from their source location after successful relocation.\r\nUse this to free up disk space on the source drive once files are confirmed copied and database metadata updated.\r\nFiles are only deleted after successful copy and database metadata update to prevent data loss.", "", false, "false", "False", "" ], [ "FileStructureOnly", "Returns the current file structure as a hashtable template without performing any file operations.\r\nUse this to discover logical file names and current paths, then modify the output for use with FileToMove.\r\nHelpful for planning complex moves or scripting multiple database relocations.", "", false, "false", "False", "" ], [ "Force", "Forces the database offline using WITH ROLLBACK IMMEDIATE, terminating active transactions and connections.\r\nUse this when the database has active connections that would prevent it from going offline gracefully.\r\nWithout this switch, the operation may fail if users are connected to the database.", "", 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": [ "RegisteredServer", "CMS" ], "CommandName": "Move-DbaRegServer", "Name": "Move-DbaRegServer", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Move-DbaRegServer [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Name] \u003cString[]\u003e] [[-ServerName] \u003cString[]\u003e] [[-Group] \u003cString\u003e] [[-InputObject] \u003cRegisteredServer[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.RegisteredServers.RegisteredServer\nReturns one RegisteredServer object per registered server that was successfully moved to the new group. Each object represents the updated server registration after the move operation completes.\nDefault display properties include:\r\n- ComputerName: The computer name of the Central Management Server instance\r\n- InstanceName: The SQL Server instance name hosting the CMS\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Name: The display name of the registered server in CMS\r\n- ServerName: The actual SQL Server instance name (connection string)\r\n- Group: The group path where the registered server is now located", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eMove-DbaRegServer -SqlInstance sql2012 -Name \u0027Web SQL Cluster\u0027 -Group HR\\Prod\nMoves the registered server on sql2012 titled \u0027Web SQL Cluster\u0027 to the Prod group within the HR group\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaRegServer -SqlInstance sql2017 -Name \u0027Web SQL Cluster\u0027 | Move-DbaRegServer -Group Web\nMoves the registered server \u0027Web SQL Cluster\u0027 on sql2017 to the Web group, also on sql2017", "Description": "Moves registered server entries from one group to another within Central Management Server hierarchy. This helps reorganize CMS structure when server roles change or you need to restructure your server groupings for better management. The function updates the CMS database to reflect the new group membership while preserving all server connection details and properties.", "Links": "https://dbatools.io/Move-DbaRegServer", "Synopsis": "Moves registered servers between groups within SQL Server Central Management Server (CMS)", "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 one or more registered servers to move by their display name as shown in SSMS CMS interface. This is the friendly name you see in the registered servers tree, which may differ from the \r\nactual server instance name.\r\nUse this when you know the descriptive name assigned to servers in CMS but not necessarily their technical instance names.", "", false, "false", "", "" ], [ "ServerName", "Specifies one or more registered servers to move by their actual SQL Server instance name. This is the technical server\\instance connection string used to connect to SQL Server.\r\nUse this when you need to target servers by their network instance names rather than their CMS display names.", "", false, "false", "", "" ], [ "Group", "Specifies the destination group where the registered servers will be moved. Use backslash notation for nested groups like \u0027Production\\WebServers\u0027.\r\nIf not specified, servers are moved to the root level of the CMS hierarchy. The target group must already exist in CMS.", "NewGroup", false, "false", "", "" ], [ "InputObject", "Accepts registered server objects from the pipeline, typically from Get-DbaRegServer output. This allows you to filter servers first and then move the results.\r\nUse this approach when you need complex filtering or when working with servers from multiple CMS 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": [ "RegisteredServer", "CMS" ], "CommandName": "Move-DbaRegServerGroup", "Name": "Move-DbaRegServerGroup", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Move-DbaRegServerGroup [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Group] \u003cString[]\u003e] [-NewGroup] \u003cString\u003e [[-InputObject] \u003cServerGroup[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.RegisteredServers.ServerGroup\nReturns one ServerGroup object for the group that was successfully moved to its new location. The object represents the moved group at its new position within the Central Management Server hierarchy.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the CMS host\r\n- InstanceName: The SQL Server instance name of the CMS\r\n- SqlInstance: The full SQL Server instance name in computer\\instance format\r\n- Name: The name of the moved server group\r\n- DisplayName: Display name of the server group for UI presentation\r\n- Description: Text description of the group\u0027s purpose or contents\r\n- ServerGroups: Collection of child server groups nested under this group\r\n- RegisteredServers: Collection of registered servers that belong to this group\nAll properties from the base SMO ServerGroup object are accessible using Select-Object *, including Urn, Parent, ParentServer, and other internal properties.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eMove-DbaRegServerGroup -SqlInstance sql2012 -Group HR\\Development -NewGroup AD\\Prod\nMoves the Development group within HR to the Prod group within AD\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaRegServerGroup -SqlInstance sql2017 -Group HR\\Development| Move-DbaRegServerGroup -NewGroup Web\nMoves the Development group within HR to the Web group", "Description": "Moves registered server groups to new locations within your Central Management Server hierarchy. This lets you reorganize your CMS group structure without using SQL Server Management Studio manually. You can move groups between different parent groups or relocate them to the root level, helping you maintain organized server collections as your environment grows or changes.", "Links": "https://dbatools.io/Move-DbaRegServerGroup", "Synopsis": "Moves registered server groups to different parent groups within SQL Server Central Management Server (CMS)", "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", "", "" ], [ "Group", "Specifies the registered server group(s) to move within your Central Management Server hierarchy. Accepts group paths like \u0027HR\\Development\u0027 or \u0027Production\\WebServers\u0027.\r\nUse this when you need to select specific groups to relocate rather than piping group objects from Get-DbaRegServerGroup.", "", false, "false", "", "" ], [ "NewGroup", "Specifies the destination group where the selected groups will be moved. Accepts group paths like \u0027AD\\Prod\u0027 or \u0027Web\u0027, or use \u0027Default\u0027 to move to the root level.\r\nThe destination group must already exist in the Central Management Server hierarchy.", "", true, "false", "", "" ], [ "InputObject", "Accepts registered server group objects from Get-DbaRegServerGroup for pipeline operations. Use this when you want to filter or manipulate groups before moving them.\r\nThis parameter enables advanced scenarios like moving multiple groups based on complex criteria or properties.", "", 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": [ "Agent", "Alert" ], "CommandName": "New-DbaAgentAlert", "Name": "New-DbaAgentAlert", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "New-DbaAgentAlert [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Alert] \u003cString\u003e [[-Category] \u003cString\u003e] [[-Database] \u003cString\u003e] [[-Operator] \u003cString[]\u003e] [[-DelayBetweenResponses] \u003cInt32\u003e] [-Disabled] [[-EventDescriptionKeyword] \u003cString\u003e] [[-EventSource] \u003cString\u003e] [[-JobId] \u003cString\u003e] [[-Severity] \u003cInt32\u003e] [[-MessageId] \u003cInt32\u003e] [[-NotificationMessage] \u003cString\u003e] [[-PerformanceCondition] \u003cString\u003e] [[-WmiEventNamespace] \u003cString\u003e] [[-WmiEventQuery] \u003cString\u003e] [[-NotifyMethod] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Agent.Alert\nReturns one Alert object for each newly created SQL Server Agent alert. The object represents the alert as configured on the target 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- Name: Name of the newly created 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, PerformanceConditionAlert, or WmiEventAlert)\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 or disabled\r\n- DelayBetweenResponses: Delay in seconds between repeated alert responses\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- EventDescriptionKeyword: Keyword filter for event descriptions\r\n- LastOccurrenceDate: DateTime when this alert was last triggered\r\n- Notifications: DataTable containing operators notified by this alert and their notification methods\r\n- OccurrenceCount: Number of times this alert has been raised\r\n- PerformanceCondition: Performance condition that triggers the alert (if performance-based)\r\n- WmiEventNamespace: WMI namespace for WMI-based alerts\r\n- WmiEventQuery: WMI query for WMI-based alerts\r\n- Urn: Uniform Resource Name for the SMO object\r\n- State: SMO object state (Existing, Creating, Pending, etc.)\nAll properties from the base SMO Alert object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$parms = @{\nSqlInstance = \"sql01\"\r\n Severity = 18\r\n Alert = \"Severity 018 - Nonfatal Internal Error\"\r\n DelayBetweenResponses = 60\r\n NotifyMethod = \"NotifyEmail\"\r\n }\nPS C:\\\u003e $alert = New-DbaAgentAlert @parms\nCreates a new alert for severity 18 with the name Severity 018 - Nonfatal Internal Error.\nIt will send an email to the default operator and wait 60 seconds before sending another email.", "Description": "Creates new SQL Server Agent alerts that monitor for specific error severities, message IDs, performance conditions, or WMI events. Alerts can automatically notify operators via email, pager, or net send when triggered, and optionally execute jobs in response to the monitored condition. Supports configurable notification delays to prevent alert spam and can target specific databases or system-wide monitoring scenarios.", "Links": "https://dbatools.io/New-DbaAgentAlert", "Synopsis": "Creates SQL Server Agent alerts for automated monitoring and notification of errors, performance conditions, or system events", "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", "", "" ], [ "Alert", "Specifies the name for the new SQL Server Agent alert. Must be unique within the SQL Server instance.\r\nUse descriptive names that clearly identify the alert\u0027s purpose, such as \u0027High Severity Errors\u0027 or \u0027Database Full\u0027.", "", true, "false", "", "" ], [ "Category", "Assigns the alert to a specific category for organization and management purposes.\r\nCategories help group related alerts together in SQL Server Management Studio and can be used for filtering in reports.", "", false, "false", "", "" ], [ "Database", "Restricts the alert to monitor events occurring only in the specified database.\r\nLeave blank to monitor all databases on the instance, or specify a database name to limit scope and reduce false positives.", "", false, "false", "", "" ], [ "Operator", "Specifies which SQL Server Agent operators will receive notifications when this alert fires.\r\nThe operators must already exist and be configured with valid email addresses, pager numbers, or net send addresses.", "", false, "false", "", "" ], [ "DelayBetweenResponses", "Sets the minimum time in seconds between alert notifications to prevent notification spam.\r\nUse higher values like 300-900 seconds for recurring issues to avoid overwhelming operators with repeated alerts.", "", false, "false", "60", "" ], [ "Disabled", "Creates the alert in a disabled state, preventing it from triggering until manually enabled.\r\nUseful when setting up alerts during maintenance windows or when you need to configure notifications before activating monitoring.", "", false, "false", "False", "" ], [ "EventDescriptionKeyword", "Filters alert triggers to only events containing this keyword in the error message text.\r\nUse this to create targeted alerts for specific error conditions like \u0027deadlock\u0027, \u0027timeout\u0027, or \u0027corruption\u0027 within broader error categories.", "", false, "false", "", "" ], [ "EventSource", "Identifies the source application or component for WMI event monitoring.\r\nRequired when creating WMI-based alerts to specify which system component\u0027s events should trigger the alert.", "", false, "false", "", "" ], [ "JobId", "Specifies the GUID of a SQL Server Agent job to automatically execute when the alert fires.\r\nUse this for automated responses like running diagnostics, performing cleanup, or triggering failover procedures.", "", false, "false", "00000000-0000-0000-0000-000000000000", "" ], [ "Severity", "Sets the SQL Server error severity level that triggers this alert, ranging from 0-25.\r\nCommon values include 16-18 for user errors, 19-21 for resource issues, and 22-25 for system errors requiring immediate attention.", "", false, "false", "0", "" ], [ "MessageId", "Creates an alert that triggers on a specific SQL Server error message number.\r\nUse this for precise monitoring of known error conditions like message 9002 (transaction log full) or 825 (read-retry errors).", "", false, "false", "0", "" ], [ "NotificationMessage", "Defines custom text to include in alert notifications sent to operators.\r\nUse this to provide context, troubleshooting steps, or escalation procedures specific to this alert condition.", "", false, "false", "", "" ], [ "PerformanceCondition", "Defines a performance counter condition that triggers the alert when threshold values are exceeded.\r\nSpecify conditions like \u0027SQLServer:General Statistics|Logins/sec|\u003e|100\u0027 to monitor performance metrics and respond to resource issues.", "", false, "false", "", "" ], [ "WmiEventNamespace", "Specifies the WMI namespace to monitor for events, typically \u0027root\\cimv2\u0027 for system events.\r\nRequired when creating WMI-based alerts to monitor Windows system events, hardware failures, or application-specific WMI providers.", "", false, "false", "", "" ], [ "WmiEventQuery", "Defines the WQL (WMI Query Language) query that determines which WMI events trigger the alert.\r\nUse queries like \u0027SELECT * FROM Win32_VolumeChangeEvent\u0027 to monitor specific system events outside of SQL Server\u0027s direct control.", "", false, "false", "", "" ], [ "NotifyMethod", "The method to use to notify the user of the alert. Valid values are \u0027None\u0027, \u0027NotifyEmail\u0027, \u0027Pager\u0027, \u0027NetSend\u0027, \u0027NotifyAll\u0027. It is NotifyAll by default.\nThe Pager and net send options will be removed from SQL Server Agent in a future version of Microsoft SQL Server.\nAvoid using these features in new development work, and plan to modify applications that currently use these features.", "", false, "false", "NotifyAll", "None,NotifyEmail,Pager,NetSend,NotifyAll" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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": [ "Agent", "Alert", "AlertCategory" ], "CommandName": "New-DbaAgentAlertCategory", "Name": "New-DbaAgentAlertCategory", "Author": "Patrick Flynn (@sqllensman)", "Syntax": "New-DbaAgentAlertCategory [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Category] \u003cString[]\u003e [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Agent.AlertCategory\nReturns one AlertCategory object for each category created. The returned objects represent the newly created alert categories and are fully functional for immediate assignment to SQL Agent alerts.\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 alert category within the instance\r\n- Name: The name of the alert category\r\n- CategoryType: Type of category (Alert or JobStep)\nAll properties from the base SMO AlertCategory object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaAgentAlertCategory -SqlInstance sql1 -Category \u0027Category 1\u0027\nCreates a new alert category with the name \u0027Category 1\u0027.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027sql1\u0027 | New-DbaAgentAlertCategory -Category \u0027Category 2\u0027\nCreates a new alert category with the name \u0027Category 2\u0027.", "Description": "Creates custom alert categories in SQL Server Agent to help organize and group related alerts for better management and monitoring.\nAlert categories allow DBAs to logically group alerts by function, severity, or responsibility, making it easier to assign different categories to different teams or escalation procedures.\nThis is particularly useful in environments with many alerts where categorization helps with organization, reporting, and maintenance workflows.\nReturns the newly created alert category objects that can be immediately used when configuring SQL Agent alerts.", "Links": "https://dbatools.io/New-DbaAgentAlertCategory", "Synopsis": "Creates new SQL Agent alert categories for organizing and managing database alerts.", "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", "", "" ], [ "Category", "Specifies the name or names of the alert categories to create in SQL Server Agent.\r\nUse descriptive names that reflect how you organize alerts, such as \u0027Database Errors\u0027, \u0027Performance Issues\u0027, or \u0027Security Events\u0027.\r\nMultiple categories can be created in a single operation by providing an array of category names.", "", true, "false", "", "" ], [ "Force", "Bypasses confirmation prompts and creates the alert categories without user interaction.\r\nUse this parameter in automated scripts or when you\u0027re confident about the category names being 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": [ "Agent", "Job", "JobStep" ], "CommandName": "New-DbaAgentJob", "Name": "New-DbaAgentJob", "Author": "Sander Stad (@sqlstad), sqlstad.nl", "Syntax": "New-DbaAgentJob [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Job] \u003cString\u003e [[-Schedule] \u003cObject[]\u003e] [[-ScheduleId] \u003cInt32[]\u003e] [-Disabled] [[-Description] \u003cString\u003e] [[-StartStepId] \u003cInt32\u003e] [[-Category] \u003cString\u003e] [[-OwnerLogin] \u003cString\u003e] [[-EventLogLevel] \u003cObject\u003e] [[-EmailLevel] \u003cObject\u003e] [[-PageLevel] \u003cObject\u003e] [[-EmailOperator] \u003cString\u003e] [[-NetsendOperator] \u003cString\u003e] [[-PageOperator] \u003cString\u003e] [[-DeleteLevel] \u003cObject\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Agent.Job\nReturns one Job object for each job created on the target instance(s). The returned objects represent the newly created SQL Server Agent jobs with all configuration options applied, including \r\nnotification settings, schedules, and job category assignments.\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 SQL Server Agent job\r\n- Enabled: Boolean indicating if the job is enabled\r\n- Description: The description of the job\r\n- Owner: The owner login name of the job\r\n- CreateDate: DateTime when the job was created\r\n- LastModifiedDate: DateTime when the job was last modified\r\n- Category: The category assigned to the job\r\n- EventLogLevel: Notification level for Windows Application event log (Never, OnSuccess, OnFailure, Always)\r\n- EmailLevel: Notification level for e-mail notifications (Never, OnSuccess, OnFailure, Always)\r\n- NetSendLevel: Notification level for network message notifications (Never, OnSuccess, OnFailure, Always)\r\n- PageLevel: Notification level for pager notifications (Never, OnSuccess, OnFailure, Always)\r\n- DeleteLevel: Automatic deletion level (Never, OnSuccess, OnFailure, Always)\r\n- IsScheduled: Boolean indicating if the job has schedules attached\nAll properties from the base SMO Job object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaAgentJob -SqlInstance sql1 -Job \u0027Job One\u0027 -Description \u0027Just another job\u0027\nCreates a job with the name \"Job1\" and a small description\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaAgentJob -SqlInstance sql1 -Job \u0027Job One\u0027 -Disabled\nCreates the job but sets it to disabled\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eNew-DbaAgentJob -SqlInstance sql1 -Job \u0027Job One\u0027 -EventLogLevel OnSuccess\nCreates the job and sets the notification to write to the Windows Application event log on success\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eNew-DbaAgentJob -SqlInstance SSTAD-PC -Job \u0027Job One\u0027 -EmailLevel OnFailure -EmailOperator dba\nCreates the job and sets the notification to send an e-mail to the e-mail operator\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eNew-DbaAgentJob -SqlInstance sql1 -Job \u0027Job One\u0027 -Description \u0027Just another job\u0027 -Whatif\nDoesn\u0027t create the job but shows what would happen.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eNew-DbaAgentJob -SqlInstance sql1, sql2, sql3 -Job \u0027Job One\u0027\nCreates a job with the name \"Job One\" on multiple servers\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003e\"sql1\", \"sql2\", \"sql3\" | New-DbaAgentJob -Job \u0027Job One\u0027\nCreates a job with the name \"Job One\" on multiple servers using the pipe line", "Description": "Creates SQL Server Agent jobs with full configuration options including owner assignment, job categories, and comprehensive notification settings.\nYou can configure email, event log, pager, and netsend notifications with specific operators and trigger conditions (success, failure, completion).\nThe function also supports attaching existing schedules during job creation and can automatically create missing job categories when using -Force.\nThis replaces the manual process of using SQL Server Management Studio or T-SQL scripts to create and configure Agent jobs across multiple instances.", "Links": "https://dbatools.io/New-DbaAgentJob", "Synopsis": "Creates SQL Server Agent jobs with notification settings and schedule assignments", "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", "", "" ], [ "Job", "The name of the job. The name must be unique and cannot contain the percent (%) character.", "", true, "false", "", "" ], [ "Schedule", "Schedule to attach to job. This can be more than one schedule.", "", false, "false", "", "" ], [ "ScheduleId", "Schedule ID to attach to job. This can be more than one schedule ID.", "", false, "false", "", "" ], [ "Disabled", "Sets the status of the job to disabled. By default a job is enabled.", "", false, "false", "False", "" ], [ "Description", "The description of the job.", "", false, "false", "", "" ], [ "StartStepId", "The identification number of the first step to execute for the job.", "", false, "false", "0", "" ], [ "Category", "The category of the job.", "", false, "false", "", "" ], [ "OwnerLogin", "The name of the login that owns the job.", "", false, "false", "", "" ], [ "EventLogLevel", "Specifies when to place an entry in the Microsoft Windows application log for this job.\r\nAllowed values 0, \"Never\", 1, \"OnSuccess\", 2, \"OnFailure\", 3, \"Always\"\r\nThe text value can either be lowercase, uppercase or something in between as long as the text is correct.", "", false, "false", "", "0,Never,1,OnSuccess,2,OnFailure,3,Always" ], [ "EmailLevel", "Specifies when to send an e-mail upon the completion of this job.\r\nAllowed values 0, \"Never\", 1, \"OnSuccess\", 2, \"OnFailure\", 3, \"Always\"\r\nThe text value can either be lowercase, uppercase or something in between as long as the text is correct.", "", false, "false", "", "0,Never,1,OnSuccess,2,OnFailure,3,Always" ], [ "PageLevel", "Specifies when to send a page upon the completion of this job.\r\nAllowed values 0, \"Never\", 1, \"OnSuccess\", 2, \"OnFailure\", 3, \"Always\"\r\nThe text value can either be lowercase, uppercase or something in between as long as the text is correct.", "", false, "false", "", "0,Never,1,OnSuccess,2,OnFailure,3,Always,0,Never,1,OnSuccess,2,OnFailure,3,Always" ], [ "EmailOperator", "The e-mail name of the operator to whom the e-mail is sent when EmailLevel is reached.", "", false, "false", "", "" ], [ "NetsendOperator", "The name of the operator to whom the network message is sent.", "", false, "false", "", "" ], [ "PageOperator", "The name of the operator to whom a page is sent.", "", false, "false", "", "" ], [ "DeleteLevel", "Specifies when to delete the job.\r\nAllowed values 0, \"Never\", 1, \"OnSuccess\", 2, \"OnFailure\", 3, \"Always\"\r\nThe text value can either be lowercase, uppercase or something in between as long as the text is correct.", "", false, "false", "", "0,Never,1,OnSuccess,2,OnFailure,3,Always" ], [ "Force", "The force parameter will ignore some errors in the parameters and assume defaults.", "", 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": [ "Agent", "Job", "JobCategory" ], "CommandName": "New-DbaAgentJobCategory", "Name": "New-DbaAgentJobCategory", "Author": "Sander Stad (@sqlstad), sqlstad.nl", "Syntax": "New-DbaAgentJobCategory [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Category] \u003cString[]\u003e [[-CategoryType] \u003cString\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Agent.JobCategory\nReturns one JobCategory object for each category created. The output is returned via Get-DbaAgentJobCategory after creation completes.\nDefault display properties (via Get-DbaAgentJobCategory):\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 job category\r\n- ID: Unique identifier for the category\r\n- CategoryType: Type of category (LocalJob, MultiServerJob, or None)\nAll properties from the base SMO JobCategory object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaAgentJobCategory -SqlInstance sql1 -Category \u0027Category 1\u0027\nCreates a new job category with the name \u0027Category 1\u0027.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaAgentJobCategory -SqlInstance sql1 -Category \u0027Category 2\u0027 -CategoryType MultiServerJob\nCreates a new job category with the name \u0027Category 2\u0027 and assign the category type for a multi server job.", "Description": "Creates custom job categories in SQL Server Agent to help organize and classify jobs by function, department, or priority level. Job categories provide a way to group related jobs together for easier management and reporting, replacing the need to manually create categories through SQL Server Management Studio. You can specify whether the category is for local jobs, multi-server jobs, or general use, with LocalJob being the default type.", "Links": "https://dbatools.io/New-DbaAgentJobCategory", "Synopsis": "Creates new SQL Server Agent job categories for organizing and managing jobs.", "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", "", "" ], [ "Category", "Specifies the name of the SQL Agent job category to create. Accepts multiple category names when you need to create several categories at once.\r\nUse descriptive names that reflect job functions like \u0027Database Maintenance\u0027, \u0027ETL Jobs\u0027, or \u0027Reporting\u0027 to help organize jobs by purpose or department.", "", true, "false", "", "" ], [ "CategoryType", "Defines the scope and purpose of the job category. Valid options are \"LocalJob\" for jobs that run on the local instance, \"MultiServerJob\" for jobs in multi-server environments, or \"None\" for \r\ngeneral-purpose categories.\r\nDefaults to \"LocalJob\" when not specified, which is appropriate for most standalone SQL Server instances.", "", false, "false", "", "LocalJob,MultiServerJob,None" ], [ "Force", "Suppresses confirmation prompts during category creation. Sets the confirmation preference to bypass interactive confirmation requests.\r\nUse this when automating category creation in scripts where manual confirmation is not desired or possible.", "", 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": [ "Agent", "Job", "JobStep" ], "CommandName": "New-DbaAgentJobStep", "Name": "New-DbaAgentJobStep", "Author": "Sander Stad (@sqlstad), sqlstad.nl", "Syntax": "New-DbaAgentJobStep [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Job] \u003cObject[]\u003e [[-StepId] \u003cInt32\u003e] [-StepName] \u003cString\u003e [[-Subsystem] \u003cString\u003e] [[-SubsystemServer] \u003cString\u003e] [[-Command] \u003cString\u003e] [[-CmdExecSuccessCode] \u003cInt32\u003e] [[-OnSuccessAction] \u003cString\u003e] [[-OnSuccessStepId] \u003cInt32\u003e] [[-OnFailAction] \u003cString\u003e] [[-OnFailStepId] \u003cInt32\u003e] [[-Database] \u003cString\u003e] [[-DatabaseUser] \u003cString\u003e] [[-RetryAttempts] \u003cInt32\u003e] [[-RetryInterval] \u003cInt32\u003e] [[-OutputFileName] \u003cString\u003e] [-Insert] [[-Flag] \u003cString[]\u003e] [[-ProxyName] \u003cString\u003e] [-Force] [-EnableException] [-WhatIf] \r\n[-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Agent.JobStep\nReturns the newly created JobStep object with all properties configured according to the specified parameters.\nReturned properties (includes all standard SMO JobStep properties plus configured settings):\r\n- Name: The descriptive name of the job step\r\n- ID: The execution sequence number for this step within the job (starting at 1)\r\n- Parent: Reference to the parent Job object containing this step\r\n- Subsystem: The execution engine type (TransactSql, PowerShell, CmdExec, Ssis, etc.)\r\n- Command: The actual code or command to be executed\r\n- DatabaseName: The database context for T-SQL steps\r\n- DatabaseUserName: The database user context for T-SQL execution\r\n- OnSuccessAction: Action to take when step completes successfully (QuitWithSuccess, GoToNextStep, GoToStep, QuitWithFailure)\r\n- OnSuccessStep: Step ID to jump to on success when using GoToStep\r\n- OnFailAction: Action to take when step fails (QuitWithFailure, GoToNextStep, GoToStep, QuitWithSuccess)\r\n- OnFailStep: Step ID to jump to on failure when using GoToStep\r\n- RetryAttempts: Number of times to retry the step on failure\r\n- RetryInterval: Minutes to wait between retry attempts\r\n- OutputFileName: File path where step output will be logged\r\n- ProxyName: SQL Server Agent proxy account used for step execution\r\n- JobStepFlags: Logging and output flags (AppendToJobHistory, AppendToLogFile, etc.)\r\n- Server: Analysis Services server for SSAS job steps\r\n- CommandExecutionSuccessCode: Exit code indicating success for CmdExec steps\nAll properties from the base SMO JobStep object are accessible even though only the configured properties above are set during creation.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaAgentJobStep -SqlInstance sql1 -Job Job1 -StepName Step1\nCreate a step in \"Job1\" with the name Step1 with the default subsystem TransactSql.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaAgentJobStep -SqlInstance sql1 -Job Job1 -StepName Step1 -Database msdb\nCreate a step in \"Job1\" with the name Step1 where the database will the msdb\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eNew-DbaAgentJobStep -SqlInstance sql1, sql2, sql3 -Job Job1 -StepName Step1 -Database msdb\nCreate a step in \"Job1\" with the name Step1 where the database will the \"msdb\" for multiple servers\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eNew-DbaAgentJobStep -SqlInstance sql1, sql2, sql3 -Job Job1, Job2, \u0027Job Three\u0027 -StepName Step1 -Database msdb\nCreate a step in \"Job1\" with the name Step1 where the database will the \"msdb\" for multiple servers for multiple jobs\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003esql1, sql2, sql3 | New-DbaAgentJobStep -Job Job1 -StepName Step1 -Database msdb\nCreate a step in \"Job1\" with the name Step1 where the database will the \"msdb\" for multiple servers using pipeline\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eNew-DbaAgentJobStep -SqlInstance sq1 -Job Job1 -StepName StepA -Database msdb -StepId 2 -Insert\nAssuming Job1 already has steps Step1 and Step2, will create a new step Step A and set the step order as Step1, StepA, Step2\r\nInternal StepIds will be updated, and any specific OnSuccess/OnFailure step references will also be updated", "Description": "Creates individual job steps within SQL Server Agent jobs, allowing you to build complex automation workflows without manually configuring each step through SSMS. Each step can execute different types of commands (T-SQL, PowerShell, SSIS packages, OS commands) and includes retry logic, success/failure branching, and output capture. When you need to add steps to existing jobs or build multi-step processes, this function handles the step ordering and dependency management automatically, including the ability to insert steps between existing ones without breaking the workflow sequence.", "Links": "https://dbatools.io/New-DbaAgentJobStep", "Synopsis": "Creates a new step within an existing SQL Server Agent job with configurable execution options and flow control", "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", "", "" ], [ "Job", "Specifies the SQL Server Agent job name where the new step will be added. Accepts job names or job objects from Get-DbaAgentJob.\r\nUse this to target specific jobs when building multi-step automation workflows.", "", true, "false", "", "" ], [ "StepId", "Sets the execution order position for this step within the job sequence. Step numbers start at 1 and must be sequential.\r\nUse this to control step execution order or when inserting steps between existing ones. If not specified, adds the step at the end.", "", false, "false", "0", "" ], [ "StepName", "Defines a descriptive name for the job step that appears in SQL Server Agent and job history logs.\r\nChoose meaningful names that clearly identify the step\u0027s purpose for easier troubleshooting and maintenance.", "", true, "false", "", "" ], [ "Subsystem", "Determines what execution engine SQL Server Agent uses to run the step command. Defaults to \u0027TransactSql\u0027 for T-SQL scripts.\r\nUse \u0027PowerShell\u0027 for PowerShell scripts, \u0027CmdExec\u0027 for operating system commands, \u0027Ssis\u0027 for SSIS packages, or replication subsystems for replication tasks.\r\nAnalysis subsystems require SQL Server Analysis Services and the SubSystemServer parameter.", "", false, "false", "TransactSql", "ActiveScripting,AnalysisCommand,AnalysisQuery,CmdExec,Distribution,LogReader,Merge,PowerShell,QueueReader,Snapshot,Ssis,TransactSql" ], [ "SubsystemServer", "Specifies the Analysis Services server name when using AnalysisScripting, AnalysisCommand, or AnalysisQuery subsystems.\r\nRequired for Analysis Services job steps to connect to the appropriate SSAS instance for cube processing or MDX queries.", "", false, "false", "", "" ], [ "Command", "Contains the actual code or command that the job step will execute, such as T-SQL scripts, PowerShell code, or operating system commands.\r\nThe command syntax must match the specified subsystem type. For T-SQL steps, include complete SQL statements or stored procedure calls.", "", false, "false", "", "" ], [ "CmdExecSuccessCode", "Defines the exit code that indicates successful completion for CmdExec subsystem steps. Most applications return 0 for success.\r\nUse this when running batch files or executables that return non-zero success codes to prevent the job from failing incorrectly.", "", false, "false", "0", "" ], [ "OnSuccessAction", "Controls job flow when this step completes successfully. Default \u0027QuitWithSuccess\u0027 ends the job with success status.\r\nUse \u0027GoToNextStep\u0027 for sequential execution, \u0027GoToStep\u0027 to jump to a specific step, or \u0027QuitWithFailure\u0027 for conditional failure handling.\r\nEssential for building complex workflows with branching logic based on step outcomes.", "", false, "false", "QuitWithSuccess", "QuitWithSuccess,QuitWithFailure,GoToNextStep,GoToStep" ], [ "OnSuccessStepId", "Specifies which step to execute next when OnSuccessAction is set to \u0027GoToStep\u0027 and this step succeeds.\r\nUse this to create conditional branching in job workflows, such as skipping cleanup steps when data processing completes successfully.", "", false, "false", "0", "" ], [ "OnFailAction", "Determines job behavior when this step fails. Default \u0027QuitWithFailure\u0027 stops the job and reports failure.\r\nUse \u0027GoToNextStep\u0027 to continue despite failures, \u0027GoToStep\u0027 for error handling routines, or \u0027QuitWithSuccess\u0027 when failure is acceptable.\r\nCritical for implementing error handling and recovery procedures in automated processes.", "", false, "false", "QuitWithFailure", "QuitWithSuccess,QuitWithFailure,GoToNextStep,GoToStep" ], [ "OnFailStepId", "Identifies the step to execute when OnFailAction is \u0027GoToStep\u0027 and this step fails.\r\nUse this to implement error handling workflows, such as sending notifications or running cleanup procedures when critical steps fail.", "", false, "false", "0", "" ], [ "Database", "Specifies the database context for TransactSql subsystem steps. Defaults to \u0027master\u0027 if not specified.\r\nSet this to the appropriate database where your T-SQL commands should execute, as it determines schema resolution and object access.", "", false, "false", "", "" ], [ "DatabaseUser", "Sets the database user context for executing T-SQL steps, overriding the SQL Server Agent service account permissions.\r\nUse this when the step needs specific database-level permissions that differ from the Agent service account\u0027s access rights.", "", false, "false", "", "" ], [ "RetryAttempts", "Sets how many times SQL Server Agent will retry this step if it fails before considering it permanently failed.\r\nUse this for steps that might fail due to temporary issues like network connectivity or resource contention. Defaults to 0 (no retries).", "", false, "false", "0", "" ], [ "RetryInterval", "Defines the wait time in minutes between retry attempts when a step fails. Defaults to 0 (immediate retry).\r\nSet appropriate intervals to allow temporary issues to resolve, such as waiting for locked resources or network recovery.", "", false, "false", "0", "" ], [ "OutputFileName", "Specifies a file path where the step\u0027s output will be written for logging and troubleshooting purposes.\r\nUse this to capture command results, error messages, or progress information for later analysis when jobs fail or need auditing.", "", false, "false", "", "" ], [ "Insert", "Inserts the new step at the specified StepId position, automatically renumbering subsequent steps and updating their references.\r\nUse this when adding steps to existing jobs without breaking the workflow sequence, such as inserting validation steps between existing processes.", "", false, "false", "False", "" ], [ "Flag", "Controls how job step output and history are logged and stored. Multiple flags can be specified for comprehensive logging.\r\nUse \u0027AppendAllCmdExecOutputToJobHistory\u0027 to capture command output in job history, \u0027AppendToLogFile\u0027 for SQL Server error log entries, or \u0027AppendToTableLog\u0027 for database table logging.\r\nEssential for troubleshooting and auditing job execution, especially for steps that generate important output or error information.\nFlag Description\r\n----------------------------------------------------------------------------\r\nAppendAllCmdExecOutputToJobHistory Job history, including command output, is appended to the job history file.\r\nAppendToJobHistory Job history is appended to the job history file.\r\nAppendToLogFile Job history is appended to the SQL Server log file.\r\nAppendToTableLog Job history is appended to a log table.\r\nLogToTableWithOverwrite Job history is written to a log table, overwriting previous contents.\r\nNone Job history is not appended to a file.\r\nProvideStopProcessEvent Job processing is stopped.", "", false, "false", "", "AppendAllCmdExecOutputToJobHistory,AppendToJobHistory,AppendToLogFile,AppendToTableLog,LogToTableWithOverwrite,None,ProvideStopProcessEvent" ], [ "ProxyName", "Specifies a SQL Server Agent proxy account to use for step execution instead of the Agent service account.\r\nUse this when steps need specific Windows credentials for file system access, network resources, or applications that require different security contexts.", "", false, "false", "", "" ], [ "Force", "Bypasses validation checks and overwrites existing steps with the same name or ID.\r\nUse this when recreating steps during development or when you need to replace existing steps without manual deletion 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", "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": [ "Agent", "Operator" ], "CommandName": "New-DbaAgentOperator", "Name": "New-DbaAgentOperator", "Author": "Tracy Boggiano (@TracyBoggiano), databasesuperhero.com", "Syntax": "New-DbaAgentOperator [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [-Operator] \u003cString\u003e [[-EmailAddress] \u003cString\u003e] [[-NetSendAddress] \u003cString\u003e] [[-PagerAddress] \u003cString\u003e] [[-PagerDay] \u003cString\u003e] [[-SaturdayStartTime] \u003cString\u003e] [[-SaturdayEndTime] \u003cString\u003e] [[-SundayStartTime] \u003cString\u003e] [[-SundayEndTime] \u003cString\u003e] [[-WeekdayStartTime] \u003cString\u003e] [[-WeekdayEndTime] \u003cString\u003e] [-IsFailsafeOperator] [[-FailsafeNotificationMethod] \u003cString\u003e] [-Force] [[-InputObject] \u003cServer[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Agent.Operator\nReturns one Operator object for the newly created SQL Server Agent operator.\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 operator\r\n- EmailAddress: Email address for alert notifications\r\n- NetSendAddress: Network send address for notifications\r\n- PagerAddress: Pager email address for urgent alerts\r\n- Enabled: Boolean indicating if the operator is active\r\n- LastEmailDate: DateTime of the most recent email sent to this operator\r\n- LastNetSendDate: DateTime of the most recent net send notification\r\n- LastPagerDate: DateTime of the most recent pager notification\nAdditional properties available (from SMO Operator object):\r\n- ID: Unique identifier for the operator\r\n- CategoryName: Alert category classification\r\n- PagerDays: Bitmask indicating which days pager notifications are active\r\n- WeekdayPagerStartTime: Start time for weekday pager notifications (HH:MM:SS format)\r\n- WeekdayPagerEndTime: End time for weekday pager notifications (HH:MM:SS format)\r\n- SaturdayPagerStartTime: Start time for Saturday pager notifications (HH:MM:SS format)\r\n- SaturdayPagerEndTime: End time for Saturday pager notifications (HH:MM:SS format)\r\n- SundayPagerStartTime: Start time for Sunday pager notifications (HH:MM:SS format)\r\n- SundayPagerEndTime: End time for Sunday pager notifications (HH:MM:SS format)\r\n- Parent: Reference to the parent JobServer object\nAll properties from the base SMO Operator object are accessible even though only default properties are displayed without using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaAgentOperator -SqlInstance sql01 -Operator DBA -EmailAddress operator@operator.com -PagerDay Everyday -Force\nThis sets a new operator named DBA with the above email address with default values to alerts everyday\r\nfor all hours of the day.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaAgentOperator -SqlInstance sql01 -Operator DBA -EmailAddress operator@operator.com `\n\u003e\u003e -NetSendAddress dbauser1 -PagerAddress dbauser1@pager.dbatools.io -PagerDay Everyday `\r\n\u003e\u003e -SaturdayStartTime 070000 -SaturdayEndTime 180000 -SundayStartTime 080000 `\r\n\u003e\u003e -SundayEndTime 170000 -WeekdayStartTime 060000 -WeekdayEndTime 190000\nCreates a new operator named DBA on the sql01 instance with email address operator@operator.com, net send address of dbauser1, pager address of dbauser1@pager.dbatools.io, page day as every day, \r\nSaturday start time of 7am, Saturday end time of 6pm, Sunday start time of 8am, Sunday end time of 5pm, Weekday start time of 6am, and Weekday end time of 7pm.", "Description": "Creates SQL Server Agent operators who receive notifications when alerts fire or jobs fail. Operators are contacts that SQL Server Agent can notify via email, pager, or net send when specific events occur. You can configure pager schedules with different time windows for weekdays, weekends, and specific days to control when pager notifications are sent. This replaces the manual process of creating operators through SQL Server Management Studio and ensures consistent operator setup across multiple instances. If the operator already exists, it will not be created unless -Force is used to drop and recreate it.", "Links": "https://dbatools.io/New-DbaAgentOperator", "Synopsis": "Creates a new SQL Server Agent operator with notification settings for alerts and job failures.", "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.", "", 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", "", "" ], [ "Operator", "Name of the SQL Server Agent operator to create. This becomes the operator name that shows up in SSMS and can be referenced by alerts and jobs for notifications.\r\nUse descriptive names like \u0027DBA Team\u0027 or \u0027On-Call Admin\u0027 to identify who receives notifications.", "", true, "false", "", "" ], [ "EmailAddress", "Email address where SQL Server Agent sends alert notifications and job failure notifications. This is the primary notification method for most operators.\r\nSpecify a monitored email address or distribution list that reaches the appropriate support staff.", "", false, "false", "", "" ], [ "NetSendAddress", "Network address for receiving net send messages from SQL Server Agent. This is a legacy Windows messaging system rarely used in modern environments.\r\nMost organizations use email notifications instead since net send requires specific network configurations and may not work across subnets.", "", false, "false", "", "" ], [ "PagerAddress", "Email address for pager notifications, typically used for SMS gateways or mobile alerts. This works with email-to-SMS services provided by cellular carriers.\r\nConfigure pager schedules with PagerDay and time parameters to control when these urgent notifications are sent.", "", false, "false", "", "" ], [ "PagerDay", "Controls which days pager notifications are active for this operator. Use this to match on-call schedules or business hours when immediate alerts are needed.\r\nChoose \u0027Weekdays\u0027 for business-hour coverage, \u0027EveryDay\u0027 for 24/7 support, or specific days like \u0027Monday\u0027 through \u0027Sunday\u0027 for rotation schedules.", "", false, "false", "", "EveryDay,Weekdays,Weekend,Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday" ], [ "SaturdayStartTime", "Starting time for Saturday pager notifications in HHMMSS format (e.g., \u0027080000\u0027 for 8:00 AM). Required when PagerDay includes Saturday, Weekend, or EveryDay.\r\nUse \u0027000000\u0027 for midnight start times or specify business hours to limit when urgent alerts are sent.", "", false, "false", "", "" ], [ "SaturdayEndTime", "Ending time for Saturday pager notifications in HHMMSS format (e.g., \u0027180000\u0027 for 6:00 PM). Must be specified with SaturdayStartTime.\r\nUse \u0027235959\u0027 for end-of-day coverage or match your organization\u0027s Saturday support hours.", "", false, "false", "", "" ], [ "SundayStartTime", "Starting time for Sunday pager notifications in HHMMSS format (e.g., \u0027090000\u0027 for 9:00 AM). Required when PagerDay includes Sunday, Weekend, or EveryDay.\r\nConfigure based on your weekend support schedule or emergency-only coverage requirements.", "", false, "false", "", "" ], [ "SundayEndTime", "Ending time for Sunday pager notifications in HHMMSS format (e.g., \u0027170000\u0027 for 5:00 PM). Must be specified with SundayStartTime.\r\nSet to match your organization\u0027s weekend support availability or use \u0027235959\u0027 for full-day coverage.", "", false, "false", "", "" ], [ "WeekdayStartTime", "Starting time for weekday pager notifications in HHMMSS format (e.g., \u0027060000\u0027 for 6:00 AM). Required when PagerDay includes Weekdays or individual weekdays.\r\nTypically set to business hours start time or earlier for critical production monitoring.", "", false, "false", "", "" ], [ "WeekdayEndTime", "Ending time for weekday pager notifications in HHMMSS format (e.g., \u0027190000\u0027 for 7:00 PM). Must be specified with WeekdayStartTime.\r\nConfigure to match business hours end time or extend for after-hours support coverage.", "", false, "false", "", "" ], [ "IsFailsafeOperator", "Designates this operator as the failsafe operator for the SQL Server instance. The failsafe operator receives notifications when all other operators are unavailable.\r\nOnly one failsafe operator can exist per instance, and this setting replaces any existing failsafe operator configuration.", "", false, "false", "False", "" ], [ "FailsafeNotificationMethod", "Specifies how the failsafe operator receives notifications when used with IsFailsafeOperator. Choose \u0027NotifyEmail\u0027 for email notifications or \u0027NotifyPager\u0027 for pager alerts.\r\nDefaults to \u0027NotifyEmail\u0027 which works with most modern notification systems and email-to-SMS gateways.", "", false, "false", "NotifyEmail", "" ], [ "Force", "Drops and recreates the operator if it already exists on the target instance. Without this switch, the function will skip existing operators to prevent accidental overwrites.\r\nUse this when updating operator configurations or when you need to ensure consistent settings across multiple environments.", "", false, "false", "False", "" ], [ "InputObject", "Accepts SQL Server Management Objects (SMO) server instances from Connect-DbaInstance via pipeline. This allows you to create operators on pre-authenticated server connections.\r\nUse this when you have existing server connections or need to process multiple instances with specific connection properties.", "", 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": [ "Agent", "Proxy" ], "CommandName": "New-DbaAgentProxy", "Name": "New-DbaAgentProxy", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "New-DbaAgentProxy [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Name] \u003cString[]\u003e [-ProxyCredential] \u003cString[]\u003e [[-SubSystem] \u003cString[]\u003e] [[-Description] \u003cString\u003e] [[-Login] \u003cString[]\u003e] [[-ServerRole] \u003cString[]\u003e] [[-MsdbRole] \u003cString[]\u003e] [-Disabled] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Agent.ProxyAccount\nReturns one ProxyAccount object for the newly created SQL Server Agent proxy 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- ID: Unique identifier for the proxy account\r\n- Name: The name of the proxy account\r\n- CredentialName: Name of the SQL Server credential used by this proxy\r\n- CredentialIdentity: The Windows account or identity associated with the credential\r\n- Description: Text description of the proxy\u0027s purpose or usage\r\n- Logins: Array of SQL Server logins that have permission to use this proxy\r\n- ServerRoles: Array of server roles that have permission to use this proxy\r\n- MsdbRoles: Array of msdb database roles that have permission to use this proxy\r\n- SubSystems: Array of SQL Agent subsystems this proxy can execute (CmdExec, PowerShell, SSIS, etc.)\r\n- IsEnabled: Boolean indicating if the proxy is currently enabled and usable\nAdditional properties available (from SMO ProxyAccount object):\r\n- CredentialID: Internal identifier for the associated credential\r\n- Parent: Reference to the parent JobServer object\r\n- Urn: The Uniform Resource Name for the proxy account object\r\n- State: Current state of the object (Existing, Creating, Pending, etc.)\nAll properties from the base SMO ProxyAccount object are accessible even though only default properties are displayed without using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaAgentProxy -SqlInstance sql2016 -Name STIG -ProxyCredential \u0027PowerShell Proxy\u0027\nCreates an Agent Proxy on sql2016 with the name STIG with the \u0027PowerShell Proxy\u0027 credential.\r\nThe proxy is automatically added to the CmdExec subsystem.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaAgentProxy -SqlInstance localhost\\sql2016 -Name STIG -ProxyCredential \u0027PowerShell Proxy\u0027 -Description \"Used for auditing purposes\" -Login ad\\sqlstig -SubSystem CmdExec, PowerShell \r\n-ServerRole securityadmin -MsdbRole ServerGroupAdministratorRole\nCreates an Agent Proxy on sql2016 with the name STIG with the \u0027PowerShell Proxy\u0027 credential and the following principals:\nLogin: ad\\sqlstig\r\nServerRole: securityadmin\r\nMsdbRole: ServerGroupAdministratorRole\nBy default, only sysadmins have access to create job steps with proxies. This will allow 3 additional principals access:\r\nThe proxy is then added to the CmdExec and PowerShell subsystems", "Description": "Creates SQL Server Agent proxy accounts that allow job steps to execute under different security contexts than the SQL Agent service account. Proxy accounts use existing SQL Server credentials and can be assigned to specific subsystems like CmdExec, PowerShell, SSIS, or Analysis Services. This enables secure delegation of permissions for automated tasks without granting elevated privileges to the service account itself.\n\nYou can control which users, server roles, or msdb database roles have permission to use each proxy, providing granular security for job execution. The proxy must reference an existing SQL Server credential that contains the Windows account under which job steps will actually run.\n\nNote: ActiveScripting (ActiveX scripting) was discontinued in SQL Server 2016: https://docs.microsoft.com/en-us/sql/database-engine/discontinued-database-engine-functionality-in-sql-server", "Links": "https://dbatools.io/New-DbaAgentProxy", "Synopsis": "Creates SQL Server Agent proxy accounts to enable job steps to run under different security contexts", "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", "", "" ], [ "Name", "Specifies the name for the SQL Agent proxy account being created. The name must be unique within the SQL Server instance.\r\nUse a descriptive name that indicates the proxy\u0027s purpose or the credential it represents for easier management.", "", true, "false", "", "" ], [ "ProxyCredential", "Specifies the name of an existing SQL Server credential that the proxy will use for authentication. The credential must already exist on the instance.\r\nThis credential defines the Windows account under which job steps will run when using this proxy.", "", true, "false", "", "" ], [ "SubSystem", "Specifies which SQL Agent subsystems can use this proxy account for job step execution. Defaults to CmdExec if not specified.\r\nMultiple subsystems can be assigned to a single proxy, allowing it to run different types of job steps under the same security context.\nValid options include:\r\nActiveScripting\r\nAnalysisCommand\r\nAnalysisQuery\r\nCmdExec\r\nDistribution\r\nLogReader\r\nMerge\r\nPowerShell\r\nQueueReader\r\nSnapshot\r\nSsis", "", false, "false", "CmdExec", "ActiveScripting,AnalysisCommand,AnalysisQuery,CmdExec,Distribution,LogReader,Merge,PowerShell,QueueReader,Snapshot,Ssis" ], [ "Description", "Provides a text description for the proxy account to document its purpose or usage requirements.\r\nUse this to help other DBAs understand when and how this proxy should be used in job steps.", "", false, "false", "", "" ], [ "Login", "Specifies which SQL Server logins can use this proxy account in their job steps. By default, only sysadmin members can use proxy accounts.\r\nAdd specific logins here to grant non-sysadmin users the ability to create job steps that run under this proxy\u0027s security context.", "", false, "false", "", "" ], [ "ServerRole", "Specifies which SQL Server fixed server roles can use this proxy account in job steps. Members of these server roles will inherit proxy usage permissions.\r\nThis provides role-based access control for proxy usage without needing to grant permissions to individual logins.", "", false, "false", "", "" ], [ "MsdbRole", "Specifies which msdb database roles can use this proxy account in job steps. Common roles include SQLAgentUserRole, SQLAgentReaderRole, and SQLAgentOperatorRole.\r\nThis allows you to grant proxy access based on existing Agent role membership rather than individual user assignments.", "", false, "false", "", "" ], [ "Disabled", "Creates the proxy account in a disabled state, preventing its immediate use in job steps.\r\nUse this when you need to set up the proxy configuration first before allowing job steps to use it.", "", false, "false", "False", "" ], [ "Force", "Drops and recreates the proxy account if one with the same name already exists on the instance.\r\nWithout this switch, the function will skip existing proxy accounts and display a warning message.", "", 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": [ "Agent", "Job", "JobStep" ], "CommandName": "New-DbaAgentSchedule", "Name": "New-DbaAgentSchedule", "Author": "Sander Stad (@sqlstad), sqlstad.nl", "Syntax": "New-DbaAgentSchedule [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Job] \u003cObject[]\u003e] [[-Schedule] \u003cObject\u003e] [-Disabled] [[-FrequencyType] \u003cObject\u003e] [[-FrequencyInterval] \u003cObject[]\u003e] [[-FrequencySubdayType] \u003cObject\u003e] [[-FrequencySubdayInterval] \u003cInt32\u003e] [[-FrequencyRelativeInterval] \u003cObject\u003e] [[-FrequencyRecurrenceFactor] \u003cInt32\u003e] [[-FrequencyText] \u003cString\u003e] [[-StartDate] \u003cString\u003e] [[-EndDate] \u003cString\u003e] [[-StartTime] \u003cString\u003e] [[-EndTime] \u003cString\u003e] [[-Owner] \u003cString\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Agent.JobSchedule\nReturns the newly created SQL Server Agent schedule object. When the -Job parameter is specified, the schedule is attached to the specified jobs before being 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- Name: The name of the schedule\r\n- IsEnabled: Boolean indicating if the schedule is enabled\r\n- FrequencyTypes: The frequency type (Once, Daily, Weekly, Monthly, etc.)\r\n- NextRunDate: DateTime of the next scheduled execution\r\n- LastRunDate: DateTime of the last scheduled execution\nAdditional properties available from the SMO JobSchedule object include:\r\n- FrequencyInterval: The frequency interval value\r\n- FrequencySubDayTypes: The subday frequency type (Once, Hours, Minutes, Seconds)\r\n- FrequencySubDayInterval: The subday frequency interval\r\n- FrequencyRelativeIntervals: The relative interval for monthly relative schedules\r\n- FrequencyRecurrenceFactor: How often the schedule repeats (weeks or months)\r\n- ActiveStartDate: The date when the schedule becomes active\r\n- ActiveEndDate: The date when the schedule stops being active\r\n- ActiveStartTimeOfDay: The time when the schedule starts each day\r\n- ActiveEndTimeOfDay: The time when the schedule stops each day\r\n- OwnerLoginName: The login that owns the schedule\r\n- DateCreated: DateTime when the schedule was created\r\n- ID: Unique identifier for the schedule\r\n- ScheduleUid: Unique GUID for the schedule\nAll properties from the base SMO JobSchedule object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaAgentSchedule -SqlInstance sql01 -Schedule DailyAt6 -FrequencyType Daily -StartTime \"060000\" -Force\nCreates a schedule that runs jobs every day at 6 in the morning. It assumes default values for the start date, start time, end date and end time due to -Force.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaAgentSchedule -SqlInstance localhost\\SQL2016 -Schedule daily -FrequencyType Daily -FrequencyInterval Everyday -Force\nCreates a schedule with a daily frequency every day. It assumes default values for the start date, start time, end date and end time due to -Force.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eNew-DbaAgentSchedule -SqlInstance sstad-pc -Schedule MonthlyTest -FrequencyType Monthly -FrequencyInterval 10 -FrequencyRecurrenceFactor 1 -Force\nCreate a schedule with a monthly frequency occuring every 10th of the month. It assumes default values for the start date, start time, end date and end time due to -Force.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eNew-DbaAgentSchedule -SqlInstance sstad-pc -Schedule RunWeekly -FrequencyType Weekly -FrequencyInterval Sunday -StartTime 010000 -Force\nCreate a schedule that will run jobs once a week on Sunday @ 1:00AM\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eNew-DbaAgentSchedule -SqlInstance sstad-pc -FrequencyText \u0027Every sunday at 02:00:00\u0027\nCreate a schedule with the name \"Every sunday at 02:00:00\" that will run jobs once a week on Sunday @ 2:00AM\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e$splatSchedule = @{\nSqlInstance = \"sql01\"\r\n Schedule = \"HourlyBusinessHours\"\r\n FrequencyType = \"Daily\"\r\n FrequencySubdayType = \"Hours\"\r\n FrequencySubdayInterval = 1\r\n StartTime = \"080000\"\r\n EndTime = \"170000\"\r\n Force = $true\r\n}\r\nPS C:\\\u003e New-DbaAgentSchedule @splatSchedule\nCreates a schedule that runs every hour between 8:00 AM and 5:00 PM. Jobs using this schedule execute at 8 AM, 9 AM, 10 AM, etc., stopping at 5 PM.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003e$splatSchedule = @{\nSqlInstance = \"sql01\"\r\n Schedule = \"EveryFiveMinutes\"\r\n FrequencyType = \"Daily\"\r\n FrequencySubdayType = \"Minutes\"\r\n FrequencySubdayInterval = 5\r\n Force = $true\r\n}\r\nPS C:\\\u003e New-DbaAgentSchedule @splatSchedule\nCreates a schedule that runs every 5 minutes throughout the day. Useful for frequent monitoring jobs that need to check system health regularly.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003e$splatSchedule = @{\nSqlInstance = \"sql01\"\r\n Schedule = \"TwiceDaily\"\r\n FrequencyType = \"Daily\"\r\n FrequencySubdayType = \"Hours\"\r\n FrequencySubdayInterval = 12\r\n StartTime = \"060000\"\r\n Force = $true\r\n}\r\nPS C:\\\u003e New-DbaAgentSchedule @splatSchedule\nCreates a schedule that runs twice per day at 6:00 AM and 6:00 PM. The 12-hour interval ensures jobs execute exactly twice daily.\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003e$splatSchedule = @{\nSqlInstance = \"sql01\"\r\n Schedule = \"FirstMondayOfMonth\"\r\n FrequencyType = \"MonthlyRelative\"\r\n FrequencyInterval = \"Monday\"\r\n FrequencyRelativeInterval = \"First\"\r\n FrequencyRecurrenceFactor = 1\r\n StartTime = \"020000\"\r\n Force = $true\r\n}\r\nPS C:\\\u003e New-DbaAgentSchedule @splatSchedule\nCreates a schedule that runs on the first Monday of every month at 2:00 AM. Perfect for monthly maintenance tasks that should run on a specific weekday.\n-------------------------- EXAMPLE 10 --------------------------\nPS C:\\\u003e$splatSchedule = @{\nSqlInstance = \"sql01\"\r\n Schedule = \"MaintenanceWindow\"\r\n FrequencyType = \"Weekly\"\r\n FrequencyInterval = \"Saturday\", \"Sunday\"\r\n StartTime = \"220000\"\r\n EndTime = \"060000\"\r\n StartDate = \"20250101\"\r\n EndDate = \"20251231\"\r\n Force = $true\r\n}\r\nPS C:\\\u003e New-DbaAgentSchedule @splatSchedule\nCreates a schedule for weekend maintenance windows running Saturday and Sunday nights from 10:00 PM to 6:00 AM. The schedule is active only during 2025.\n-------------------------- EXAMPLE 11 --------------------------\nPS C:\\\u003e$splatSchedule = @{\nSqlInstance = \"sql01\"\r\n Schedule = \"PreprodRefresh\"\r\n Disabled = $true\r\n FrequencyType = \"Weekly\"\r\n FrequencyInterval = \"Sunday\"\r\n StartTime = \"040000\"\r\n Force = $true\r\n}\r\nPS C:\\\u003e New-DbaAgentSchedule @splatSchedule\nCreates a disabled schedule for pre-production database refreshes. The schedule is configured but won\u0027t execute until manually enabled, allowing you to prepare schedules in advance.\n-------------------------- EXAMPLE 12 --------------------------\nPS C:\\\u003e$splatSchedule = @{\nSqlInstance = \"sql01\"\r\n Job = \"BackupUserDatabases\", \"CheckDBIntegrity\", \"UpdateStatistics\"\r\n Schedule = \"NightlyMaintenance\"\r\n FrequencyType = \"Daily\"\r\n StartTime = \"010000\"\r\n Force = $true\r\n}\r\nPS C:\\\u003e New-DbaAgentSchedule @splatSchedule\nCreates a schedule and immediately attaches it to three different jobs. This demonstrates how to apply a single schedule to multiple jobs in one command.\n-------------------------- EXAMPLE 13 --------------------------\nPS C:\\\u003e$splatSchedule = @{\nSqlInstance = \"sql01\"\r\n Schedule = \"QuarterEndReports\"\r\n FrequencyType = \"Monthly\"\r\n FrequencyInterval = 31\r\n FrequencyRecurrenceFactor = 3\r\n StartTime = \"180000\"\r\n Owner = \"DOMAIN\\SQLServiceAccount\"\r\n Force = $true\r\n}\r\nPS C:\\\u003e New-DbaAgentSchedule @splatSchedule\nCreates a schedule that runs every 3 months on the 31st (or last day of month) at 6:00 PM. The Owner parameter specifies which account owns the schedule for permission management.\n-------------------------- EXAMPLE 14 --------------------------\nPS C:\\\u003e$splatSchedule = @{\nSqlInstance = \"sql01\"\r\n Schedule = \"BusinessHoursEvery30Min\"\r\n FrequencyType = \"Daily\"\r\n FrequencySubdayType = \"Minutes\"\r\n FrequencySubdayInterval = 30\r\n StartTime = \"083000\"\r\n EndTime = \"173000\"\r\n Force = $true\r\n}\r\nPS C:\\\u003e New-DbaAgentSchedule @splatSchedule\nCreates a schedule that runs every 30 minutes during business hours (8:30 AM to 5:30 PM). First execution is at 8:30 AM, last execution at 5:00 PM.", "Description": "Creates a new schedule in the msdb database that defines when SQL Server Agent jobs should execute. Schedules can be created as standalone objects or immediately attached to existing jobs, allowing you to standardize timing across multiple jobs without recreating the same schedule repeatedly. This replaces the need to manually create schedules through SQL Server Management Studio or T-SQL, while providing comprehensive validation of schedule parameters and frequency options. Supports all SQL Server Agent scheduling options including one-time, daily, weekly, monthly, and relative monthly frequencies with full control over start/end dates, times, and recurrence patterns.", "Links": "https://dbatools.io/New-DbaAgentSchedule", "Synopsis": "Creates a new SQL Server Agent schedule for automated job execution", "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", "", "" ], [ "Job", "Specifies existing SQL Server Agent jobs to immediately attach this schedule to after creation.\r\nUse this when you want to apply the same schedule to multiple jobs without manually attaching it later through SSMS.", "", false, "false", "", "" ], [ "Schedule", "The name for the new schedule that will appear in SQL Server Agent.\r\nChoose descriptive names like \"DailyAt6AM\" or \"WeeklyMaintenanceWindow\" to make schedule management easier for your team.", "", false, "false", "", "" ], [ "Disabled", "Creates the schedule in a disabled state, preventing any attached jobs from running until the schedule is manually enabled.\r\nUse this when you need to set up schedules in advance but don\u0027t want them active immediately.", "", false, "false", "False", "" ], [ "FrequencyType", "Determines the basic execution pattern for jobs using this schedule.\r\nDaily runs every day or every N days, Weekly runs on specific days of the week, Monthly runs on specific dates, and MonthlyRelative runs on relative dates like \"first Monday.\"\r\nOnce/OneTime creates single-execution schedules, while AgentStart/AutoStart and IdleComputer/OnIdle create event-triggered schedules.\nAllowed values: \u0027Once\u0027, \u0027OneTime\u0027, \u0027Daily\u0027, \u0027Weekly\u0027, \u0027Monthly\u0027, \u0027MonthlyRelative\u0027, \u0027AgentStart\u0027, \u0027AutoStart\u0027, \u0027IdleComputer\u0027, \u0027OnIdle\u0027\nThe following synonyms provide flexibility to the allowed values for this function parameter:\r\nOnce=OneTime\r\nAgentStart=AutoStart\r\nIdleComputer=OnIdle\nIf force is used the default will be \"Once\".", "", false, "false", "", "Once,OneTime,Daily,Weekly,Monthly,MonthlyRelative,AgentStart,AutoStart,IdleComputer,OnIdle" ], [ "FrequencyInterval", "Defines which specific days the job executes based on the FrequencyType selected.\r\nFor Daily: use numbers 1-365 for \"every N days\" or \"EveryDay\" for daily execution.\r\nFor Weekly: specify day names like \"Monday,Friday\" or use \"Weekdays,\" \"Weekend,\" or \"EveryDay.\"\r\nFor Monthly: use numbers 1-31 to run on specific dates of each month.\nAllowed values for FrequencyType \u0027Daily\u0027: EveryDay or a number between 1 and 365.\r\nAllowed values for FrequencyType \u0027Weekly\u0027: Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Weekdays, Weekend or EveryDay.\r\nAllowed values for FrequencyType \u0027Monthly\u0027: Numbers 1 to 31 for each day of the month.\nIf \"Weekdays\", \"Weekend\" or \"EveryDay\" is used it over writes any other value that has been passed before.\nIf force is used the default will be 1.", "", false, "false", "", "" ], [ "FrequencySubdayType", "Sets the time interval unit when jobs need to run multiple times per day.\r\nUse \"Once\" for single daily execution, \"Hours\" for hourly intervals, \"Minutes\" for minute-based intervals, or \"Seconds\" for very frequent execution.\r\nMost maintenance jobs use \"Once\" while monitoring jobs might use \"Minutes\" or \"Hours.\"\nAllowed values: \u0027Once\u0027, \u0027Time\u0027, \u0027Seconds\u0027, \u0027Second\u0027, \u0027Minutes\u0027, \u0027Minute\u0027, \u0027Hours\u0027, \u0027Hour\u0027\nThe following synonyms provide flexibility to the allowed values for this function parameter:\r\nOnce=Time\r\nSeconds=Second\r\nMinutes=Minute\r\nHours=Hour", "", false, "false", "", "Once,Time,Seconds,Second,Minutes,Minute,Hours,Hour" ], [ "FrequencySubdayInterval", "Specifies how often the job repeats within a day when FrequencySubdayType is not \"Once.\"\r\nFor example, with FrequencySubdayType \"Hours\" and FrequencySubdayInterval 4, the job runs every 4 hours.\r\nMinimum interval is 10 seconds for second-based scheduling.", "", false, "false", "0", "" ], [ "FrequencyRelativeInterval", "Determines which occurrence of a day type to use for MonthlyRelative schedules.\r\nUse \"First\" for first occurrence, \"Second\" for second occurrence, etc., or \"Last\" for the final occurrence of that day in the month.\r\nFor example, \"Second\" with \"Friday\" runs on the second Friday of each month.\nAllowed values: First, Second, Third, Fourth or Last", "", false, "false", "", "Unused,First,Second,Third,Fourth,Last" ], [ "FrequencyRecurrenceFactor", "Controls how many weeks or months to skip between executions for Weekly, Monthly, and MonthlyRelative schedules.\r\nUse 1 for every week/month, 2 for every other week/month, 3 for every third, etc.\r\nThis allows schedules like \"every 2 weeks on Monday\" or \"every 3 months on the 15th.\"\nFrequencyRecurrenceFactor is used only if FrequencyType is \"Weekly\", \"Monthly\" or \"MonthlyRelative\".", "", false, "false", "0", "" ], [ "FrequencyText", "Describe common frequencies as a text. Sample text:\nEvery minute\r\nEvery 5 minutes\r\nEvery 10 minutes starting at 00:02:30\r\nEvery hour\r\nEvery 2 hours\r\nEvery 4 hours starting at 02:00:00\r\nEvery day at 05:00:00\r\nEvery sunday at 02:00:00\nThis is the used regex: every(\\s+(?\u003cinterval\u003e\\d+))?\\s+(?\u003cunit\u003eminute|hour|day|sunday|monday|tuesday|wednesday|thursday|friday|saturday)s?(\\s+starting)?(\\s+at\\s+(?\u003cstart\u003e\\d\\d:\\d\\d:\\d\\d))?\nIf parameter Schedule is not provided, the FrequencyText will be used as the name of the schedule.\r\nParameter Force will be set to $true.", "", false, "false", "", "" ], [ "StartDate", "The earliest date this schedule can execute jobs, formatted as yyyyMMdd (e.g., \"20240315\" for March 15, 2024).\r\nUse this to delay schedule activation until a future date or to document when recurring maintenance should begin.\r\nWith -Force, defaults to today\u0027s date.", "", false, "false", "", "" ], [ "EndDate", "The latest date this schedule can execute jobs, formatted as yyyyMMdd (e.g., \"20241231\" for December 31, 2024).\r\nUse this for temporary schedules or to automatically deactivate seasonal jobs.\r\nWith -Force, defaults to \"99991231\" (no expiration).", "", false, "false", "", "" ], [ "StartTime", "The time of day when job execution can begin, formatted as HHmmss in 24-hour format (e.g., \"143000\" for 2:30 PM).\r\nFor subday schedules, this is when the first execution occurs each day.\r\nWith -Force, defaults to \"000000\" (midnight).", "", false, "false", "", "" ], [ "EndTime", "The time of day when job execution must stop, formatted as HHmmss in 24-hour format (e.g., \"180000\" for 6:00 PM).\r\nFor subday schedules, no new executions start after this time, but running jobs can complete.\r\nWith -Force, defaults to \"235959\" (one second before midnight).", "", false, "false", "", "" ], [ "Owner", "The SQL Server login that owns this schedule, which determines permissions for schedule modification.\r\nDefaults to the login running this command, but you can specify a service account or DBA login for centralized schedule management.", "", false, "false", "", "" ], [ "Force", "Bypasses parameter validation and applies default values for missing required parameters like dates and times.\r\nAlso removes any existing schedule with the same name before creating the new one, preventing naming 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", "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": "New-DbaAvailabilityGroup", "Name": "New-DbaAvailabilityGroup", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "New-DbaAvailabilityGroup [[-Primary] \u003cDbaInstanceParameter\u003e] [[-PrimarySqlCredential] \u003cPSCredential\u003e] [[-Secondary] \u003cDbaInstanceParameter[]\u003e] [[-SecondarySqlCredential] \u003cPSCredential\u003e] [-Name] \u003cString\u003e [-IsContained] [-ReuseSystemDatabases] [-DtcSupport] [[-ClusterType] \u003cString\u003e] [[-AutomatedBackupPreference] \u003cString\u003e] [[-FailureConditionLevel] \u003cString\u003e] [[-HealthCheckTimeout] \u003cInt32\u003e] [-Basic] [-DatabaseHealthTrigger] [-Passthru] [[-Database] \u003cString[]\u003e] [[-SharedPath] \u003cString\u003e] [-UseLastBackup] [-Force] [[-AvailabilityMode] \u003cString\u003e] [[-FailoverMode] \u003cString\u003e] [[-BackupPriority] \u003cInt32\u003e] \r\n[[-ConnectionModeInPrimaryRole] \u003cString\u003e] [[-ConnectionModeInSecondaryRole] \u003cString\u003e] [[-SeedingMode] \u003cString\u003e] [[-Endpoint] \u003cString\u003e] [[-EndpointUrl] \u003cString[]\u003e] [[-Certificate] \u003cString\u003e] [-ConfigureXESession] [[-IPAddress] \u003cIPAddress[]\u003e] [[-SubnetMask] \u003cIPAddress\u003e] [[-Port] \u003cInt32\u003e] [-Dhcp] [[-ClusterConnectionOption] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.AvailabilityGroup (when -Passthru is not specified)\nReturns the newly created SQL Server availability group object after full setup is complete. The returned object includes all configured replicas, databases, and listeners.\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 availability group\r\n- PrimaryReplica: The server name of the primary replica\r\n- LocalReplicaRole: The role of the local replica (Primary or Secondary)\r\n- AvailabilityReplicas: Collection of replica objects in the availability group\r\n- AvailabilityDatabases: Collection of databases in the availability group\r\n- AvailabilityGroupListeners: Collection of listeners configured for the AG\nAdditional properties available from the SMO AvailabilityGroup object include:\r\n- AutomatedBackupPreference: Which replicas are preferred for backups (Primary, Secondary, SecondaryOnly, None)\r\n- FailureConditionLevel: The level that triggers automatic failover\r\n- HealthCheckTimeout: Timeout in milliseconds for health checks (default 30000)\r\n- BasicAvailabilityGroup: Boolean indicating if this is a Basic AG\r\n- DatabaseHealthTrigger: Boolean indicating if database health triggers failover\r\n- DtcSupportEnabled: Boolean indicating if DTC is enabled (SQL Server 2016+)\r\n- ClusterType: The cluster type (Wsfc, External, or None)\r\n- IsContained: Boolean indicating if this is a contained AG (SQL Server 2022+)\r\n- ClusterConnectionOptions: Connection options for cluster communication (SQL Server 2025+)\r\n- DateCreated: DateTime when the availability group was created\nPassthru behavior (when -Passthru is specified):\r\nReturns the AvailabilityGroup object immediately after configuration but before creation, with these properties displayed:\r\n- LocalReplicaRole: The role of the local replica\r\n- AvailabilityGroup: The name of the AG\r\n- PrimaryReplica: The primary replica server name\r\n- AutomatedBackupPreference: Backup preference setting\r\n- AvailabilityReplicas: Configured replicas\r\n- AvailabilityDatabases: Databases to be added\r\n- AvailabilityGroupListeners: Listeners to be created\nAll properties from the base SMO AvailabilityGroup object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaAvailabilityGroup -Primary sql2016a -Name SharePoint\nCreates a new availability group on sql2016a named SharePoint\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaAvailabilityGroup -Primary sql2016a -Name SharePoint -Secondary sql2016b\nCreates a new availability group on sql2016a named SharePoint with a secondary replica, sql2016b\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eNew-DbaAvailabilityGroup -Primary sql2016std -Name BAG1 -Basic -Confirm:$false\nCreates a basic availability group named BAG1 on sql2016std and does not confirm when setting up\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eNew-DbaAvailabilityGroup -Primary sql2022n01 -Secondary sql2022n02 -Name AgContained -IsContained\nCreates a contained availability group named AgContained on nodes sql2022n01 and sql2022n02\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eNew-DbaAvailabilityGroup -Primary sql2016b -Name AG1 -Dhcp -Database db1 -UseLastBackup\nCreates an availability group on sql2016b with the name ag1. Uses the last backups available to add the database db1 to the AG.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eNew-DbaAvailabilityGroup -Primary sql2017 -Name SharePoint -ClusterType None -FailoverMode Manual\nCreates a new availability group on sql2017 named SharePoint with a cluster type of none and a failover mode of manual\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eNew-DbaAvailabilityGroup -Primary sql1 -Secondary sql2 -Name ag1 -Database pubs -ClusterType None -SeedingMode Automatic -FailoverMode Manual\nCreates a new availability group with a primary replica on sql1 and a secondary on sql2. Automatically adds the database pubs.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eNew-DbaAvailabilityGroup -Primary sql1 -Secondary sql2 -Name ag1 -Database pubs -EndpointUrl \u0027TCP://sql1.specialnet.local:5022\u0027, \u0027TCP://sql2.specialnet.local:5022\u0027\nCreates a new availability group with a primary replica on sql1 and a secondary on sql2 with custom endpoint urls. Automatically adds the database pubs.\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e $params = @{\r\n\u003e\u003e Primary = \"sql1\"\r\n\u003e\u003e PrimarySqlCredential = $cred\r\n\u003e\u003e Secondary = \"sql2\"\r\n\u003e\u003e SecondarySqlCredential = $cred\r\n\u003e\u003e Name = \"test-ag\"\r\n\u003e\u003e Database = \"pubs\"\r\n\u003e\u003e ClusterType = \"None\"\r\n\u003e\u003e SeedingMode = \"Automatic\"\r\n\u003e\u003e FailoverMode = \"Manual\"\r\n\u003e\u003e Confirm = $false\r\n\u003e\u003e }\r\nPS C:\\\u003e New-DbaAvailabilityGroup @params\nThis exact command was used to create an availability group on docker!", "Description": "Creates availability groups with full automation, eliminating the manual multi-step process typically required through T-SQL or SSMS. This command handles the entire workflow from initial validation through final configuration, so you don\u0027t have to manually coordinate across multiple servers and troubleshoot common setup issues.\n\nPerfect for setting up high availability environments, disaster recovery solutions, or read-scale deployments. Supports both traditional Windows Server Failover Cluster (WSFC) environments and modern cluster-less configurations for containers and Linux.\n\n* Validates prerequisites across all instances\n* Creates availability group and configures primary replica\n* Sets up database mirroring endpoints with proper authentication\n* Adds and joins secondary replicas automatically\n* Seeds databases using backup/restore or direct seeding\n* Configures listeners with static IP or DHCP\n* Grants necessary cluster and endpoint permissions\n* Enables AlwaysOn_health extended events sessions\n\nThe command handles the complex coordination between servers that trips up manual setups - endpoint permissions, service account access, database seeding modes, and cluster integration.\n\nNOTES:\n- If a backup / restore is performed, the backups will be left intact on the network share.\n- If you\u0027re using SQL Server on Linux and a fully qualified domain name is required, please use the FQDN to create a proper Endpoint\n\nPLEASE NOTE THE CHANGED DEFAULTS:\nStarting with version 1.1.x we changed the defaults of the following parameters to have the same defaults\nas the T-SQL command \"CREATE AVAILABILITY GROUP\" and the wizard in SQL Server Management Studio:\n* ClusterType from External to Wsfc (Windows Server Failover Cluster).\n* FailureConditionLevel from OnServerDown (Level 1) to OnCriticalServerErrors (Level 3).\n* ConnectionModeInSecondaryRole from AllowAllConnections (ALL) to AllowNoConnections (NO).\nTo change these defaults we have introduced configuration parameters for all of them, see documentation of the parameters for details.\n\nThanks for this, Thomas Stringer! https://blogs.technet.microsoft.com/heyscriptingguy/2013/04/29/set-up-an-alwayson-availability-group-with-powershell/", "Links": "https://dbatools.io/New-DbaAvailabilityGroup", "Synopsis": "Creates SQL Server availability groups with automated replica setup, database seeding, and listener configuration.", "Availability": "Windows, Linux, macOS", "Params": [ [ "Primary", "Specifies the SQL Server instance that will host the primary replica of the availability group.\r\nThis instance must have AlwaysOn Availability Groups enabled and be running SQL Server 2012 or higher.\r\nUse this when setting up the main server that will handle write operations and coordinate with secondary replicas.", "", false, "true (ByValue)", "", "" ], [ "PrimarySqlCredential", "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", "", "" ], [ "Secondary", "Specifies one or more SQL Server instances that will host secondary replicas in the availability group.\r\nAll instances must have AlwaysOn enabled and be running SQL Server 2012 or higher.\r\nThese servers will receive synchronized copies of your databases and can serve read-only workloads or provide disaster recovery.", "", false, "false", "", "" ], [ "SecondarySqlCredential", "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 availability group.\r\nThis name must be unique across all availability groups in the Windows Server Failover Cluster.\r\nChoose a descriptive name that reflects the application or purpose, as this will be used for monitoring and management.", "", true, "false", "", "" ], [ "IsContained", "Creates a contained availability group that includes system databases alongside user databases.\r\nOnly supported in SQL Server 2022 and above, this eliminates the need to manually synchronize logins and jobs.\r\nUse this for simplified management when you need consistent security objects across all replicas.", "", false, "false", "False", "" ], [ "ReuseSystemDatabases", "Reuses existing system databases when recreating a contained availability group with the same name.\r\nOnly applicable with contained availability groups (-IsContained).\r\nUse this when rebuilding an AG to avoid conflicts with previously created system database copies.", "", false, "false", "False", "" ], [ "DtcSupport", "Enables support for distributed transactions using Microsoft Distributed Transaction Coordinator (DTC).\r\nRequired when applications use distributed transactions that span databases in the availability group.\r\nNote that DTC support is not available on Linux SQL Server instances.", "", false, "false", "False", "" ], [ "ClusterType", "Defines the clustering technology used by the availability group (SQL Server 2017+).\r\nOptions: Wsfc (Windows Server Failover Cluster), External (Linux Pacemaker), or None (no cluster).\r\nUse \u0027None\u0027 for read-scale scenarios without automatic failover, \u0027External\u0027 for Linux environments, or \u0027Wsfc\u0027 for traditional Windows clustering.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027AvailabilityGroups.Default.ClusterType\u0027 -Fallback \u0027Wsfc\u0027)", "Wsfc,External,None" ], [ "AutomatedBackupPreference", "Controls which replicas are preferred for automated backup operations.\r\nOptions: Primary, Secondary, SecondaryOnly, or None.\r\nUse \u0027Secondary\u0027 to offload backup I/O from the primary, or \u0027SecondaryOnly\u0027 to ensure backups never impact primary performance.", "", false, "false", "Secondary", "None,Primary,Secondary,SecondaryOnly" ], [ "FailureConditionLevel", "Determines what conditions trigger automatic failover in the availability group.\r\nDefault is Level 3 (OnCriticalServerErrors), which balances protection against false positives.\r\nUse Level 1 for fastest failover, Level 5 for maximum sensitivity, or adjust based on your tolerance for automatic failover events.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027AvailabilityGroups.Default.FailureConditionLevel\u0027 -Fallback \u0027OnCriticalServerErrors\u0027)", "OnAnyQualifiedFailureCondition,OnCriticalServerErrors,OnModerateServerErrors,OnServerDown,OnServerUnresponsive" ], [ "HealthCheckTimeout", "Sets the timeout in milliseconds for health check responses from the sp_server_diagnostics procedure.\r\nDefault is 30000 (30 seconds). Lower values provide faster failure detection but may cause false positives.\r\nIncrease this value in environments with high I/O load or slower storage to prevent unnecessary failovers.", "", false, "false", "30000", "" ], [ "Basic", "Creates a Basic Availability Group limited to one database and two replicas.\r\nAvailable in SQL Server 2016 Standard Edition and above as an alternative to Database Mirroring.\r\nUse this for simple two-node high availability scenarios when you don\u0027t need multiple databases or advanced features.", "", false, "false", "False", "" ], [ "DatabaseHealthTrigger", "Enables database-level health monitoring that can trigger automatic failover.\r\nWhen enabled, database corruption or other critical database errors can initiate failover.\r\nUse this for additional protection when database integrity is more critical than minimizing failover events.", "", false, "false", "False", "" ], [ "Passthru", "Returns the availability group object without creating it, allowing further customization.\r\nUse this when you need to modify advanced properties or add custom configurations before creating the AG.\r\nThe returned object can be passed to other dbatools commands or have properties modified directly.", "", false, "false", "False", "" ], [ "Database", "Specifies which databases to add to the availability group during creation.\r\nDatabases must be in Full recovery model and have recent transaction log backups.\r\nUse this to automatically include databases rather than adding them separately after AG creation.", "", false, "false", "", "" ], [ "SharedPath", "Specifies the network path where database backups will be stored during secondary replica initialization.\r\nAll SQL Server service accounts must have read/write access to this location.\r\nRequired for manual seeding mode when adding databases - backups remain on the share after completion.", "", false, "false", "", "" ], [ "UseLastBackup", "Uses existing backup files instead of creating new ones for database initialization.\r\nThe most recent full backup and subsequent log backups will be restored to secondary replicas.\r\nUse this to save time and storage when recent backups are already available and accessible.", "", false, "false", "False", "" ], [ "Force", "Removes existing databases on secondary replicas before restoring from backup.\r\nUse this when databases already exist on secondary servers but you want to refresh them.\r\nRequires SharedPath or UseLastBackup to be specified for the restore operation.", "", false, "false", "False", "" ], [ "AvailabilityMode", "Controls whether transaction commits wait for secondary replica acknowledgment.\r\nSynchronousCommit ensures zero data loss but may impact performance over distance.\r\nUse AsynchronousCommit for disaster recovery replicas or when network latency affects performance.", "", false, "false", "SynchronousCommit", "AsynchronousCommit,SynchronousCommit" ], [ "FailoverMode", "Determines how failover occurs for the availability group.\r\nAutomatic enables cluster-managed failover with synchronous replicas, Manual requires DBA intervention.\r\nUse External for Linux environments with Pacemaker cluster management.", "", false, "false", "Automatic", "Automatic,Manual,External" ], [ "BackupPriority", "Sets the priority for backup operations on this replica (0-100, default 50).\r\nHigher values make this replica more preferred for automated backup jobs.\r\nUse lower values on primary replicas to offload backup I/O, higher values on dedicated backup servers.", "", false, "false", "50", "" ], [ "ConnectionModeInPrimaryRole", "Controls what connections are allowed to the primary replica.\r\nAllowAllConnections (default) permits both read-write and read-intent connections.\r\nUse AllowReadWriteConnections to restrict read-only workloads to secondary replicas only.", "", false, "false", "AllowAllConnections", "AllowAllConnections,AllowReadWriteConnections" ], [ "ConnectionModeInSecondaryRole", "Controls what connections are allowed to secondary replicas.\r\nDefault is AllowNoConnections to prevent accidental writes or outdated reads.\r\nUse AllowReadIntentConnectionsOnly for reporting workloads, or AllowAllConnections for maximum flexibility.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027AvailabilityGroups.Default.ConnectionModeInSecondaryRole\u0027 -Fallback \u0027AllowNoConnections\u0027)", "AllowNoConnections,AllowReadIntentConnectionsOnly,AllowAllConnections,No,Read-intent only,Yes" ], [ "SeedingMode", "Determines how databases are initialized on secondary replicas.\r\nManual (default) uses backup/restore through shared storage, Automatic uses direct network streaming.\r\nUse Automatic for SQL Server 2016+ to simplify setup when network bandwidth is sufficient and shared storage is limited.", "", false, "false", "Manual", "Automatic,Manual" ], [ "Endpoint", "Specifies the name for the database mirroring endpoint used for availability group communication.\r\nIf not specified, the command searches for existing endpoints or creates \u0027hadr_endpoint\u0027.\r\nUse a custom name when you have specific endpoint naming standards or multiple AGs on the same instance.", "", false, "false", "", "" ], [ "EndpointUrl", "Specifies custom TCP URLs for availability group endpoints when automatic detection isn\u0027t suitable.\r\nRequired format: \u0027TCP://hostname:port\u0027 for each instance (primary first, then secondaries).\r\nUse this in complex network environments with custom DNS, firewalls, or when instances use non-default ports.", "", false, "false", "", "" ], [ "Certificate", "Specifies the certificate name for endpoint authentication instead of Windows authentication.\r\nBoth endpoints must have matching certificates with corresponding public/private key pairs.\r\nUse this for cross-domain scenarios or when Windows authentication is not available between replicas.", "", false, "false", "", "" ], [ "ConfigureXESession", "Automatically starts the AlwaysOn_health Extended Events session on all replicas.\r\nThis session captures availability group events for monitoring and troubleshooting.\r\nUse this to match the behavior of the SQL Server Management Studio AG wizard and enable built-in diagnostics.", "", false, "false", "False", "" ], [ "IPAddress", "Specifies one or more static IP addresses for the availability group listener.\r\nEach IP should correspond to a different subnet if replicas span multiple subnets.\r\nUse static IPs when DHCP is not available or when you need predictable listener addresses for applications.", "", false, "false", "", "" ], [ "SubnetMask", "Specifies the subnet mask for static IP listener configuration.\r\nDefault is 255.255.255.0, which works for most standard network configurations.\r\nAdjust this to match your network\u0027s subnet configuration when using custom IP addressing.", "", false, "false", "255.255.255.0", "" ], [ "Port", "Specifies the TCP port for the availability group listener.\r\nDefault is 1433 (standard SQL Server port). Applications connect to this port to reach the current primary.\r\nUse a different port when 1433 is already in use or for security through obscurity.", "", false, "false", "1433", "" ], [ "Dhcp", "Configures the availability group listener to use DHCP for IP address assignment.\r\nThe cluster will request an IP address from DHCP servers on each replica\u0027s subnet.\r\nUse this when static IP management is not desired and DHCP reservations can provide consistent addressing.", "", false, "false", "False", "" ], [ "ClusterConnectionOption", "Specifies connection options for TDS 8.0 support in SQL Server 2025 and above.\r\nThis allows the Windows Server Failover Cluster (WSFC) to connect to SQL Server instances using ODBC with TLS 1.3 encryption.\r\nThe value is a string containing semicolon-delimited key-value pairs.\nAvailable keys:\r\n- Encrypt: Controls connection encryption\r\n- TrustServerCertificate: Whether to trust the server certificate\r\n- HostNameInCertificate: Expected hostname in the certificate\r\n- ServerCertificate: Path to server certificate\nThis setting is persisted by WSFC in the registry and used continuously for cluster-to-instance communication.\r\nNote: PowerShell does not validate these values - invalid combinations will be rejected by SMO or the ODBC driver.\nExample: \"Encrypt=Strict;TrustServerCertificate=False\"\nFor detailed documentation, see:\r\nhttps://learn.microsoft.com/en-us/sql/t-sql/statements/create-availability-group-transact-sql", "", 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": [ "Connect", "Connection", "Azure" ], "CommandName": "New-DbaAzAccessToken", "Name": "New-DbaAzAccessToken", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "New-DbaAzAccessToken [-Type] \u003cString\u003e [[-Subtype] \u003cString\u003e] [[-Config] \u003cObject\u003e] [[-Credential] \u003cPSCredential\u003e] [[-Tenant] \u003cString\u003e] [[-Thumbprint] \u003cString\u003e] [[-Store] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.String (when -Type is ManagedIdentity or ServicePrincipal)\nReturns a plain-text OAuth2 access token that can be used with Connect-DbaInstance and other Azure-aware dbatools commands.\nPSObjectIRenewableToken (when -Type is RenewableServicePrincipal)\nReturns a custom IRenewableToken object that automatically refreshes tokens for long-running connections. This object implements Microsoft.SqlServer.Management.Common.IRenewableToken.\nProperties:\r\n- ClientSecret: The application secret/password used for token renewal\r\n- Resource: The Azure resource URI (e.g., \"https://database.windows.net/\")\r\n- Tenant: The Azure AD tenant ID or domain name\r\n- UserID: The service principal application ID\r\n- TokenExpiry: DateTime when the token expires; automatically updated when GetAccessToken() is called", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaAzAccessToken -Type ManagedIdentity\nReturns a plain-text token for Managed Identities for SQL Azure Db.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$token = New-DbaAzAccessToken -Type ManagedIdentity -Subtype AzureSqlDb\nPS C:\\\u003e $server = Connect-DbaInstance -SqlInstance myserver.database.windows.net -Database mydb -AccessToken $token -DisableException\nGenerates a token then uses it to connect to Azure SQL DB then connects to an Azure SQL Db\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$token = New-DbaAzAccessToken -Type ServicePrincipal -Tenant whatup.onmicrosoft.com -Credential ee590f55-9b2b-55d4-8bca-38ab123db670\nPS C:\\\u003e $server = Connect-DbaInstance -SqlInstance myserver.database.windows.net -Database mydb -AccessToken $token -DisableException\r\nPS C:\\\u003e Invoke-DbaQuery -SqlInstance $server -Query \"select 1 as test\"\nGenerates a token then uses it to connect to Azure SQL DB then connects to an Azure SQL Db.\r\nOnce the connection is made, it is used to perform a test query.", "Description": "Creates OAuth2 access tokens for connecting to Azure SQL Database and other Azure services without storing passwords in scripts. Supports Managed Identity authentication from Azure VMs, Service Principal authentication for applications, and renewable tokens for long-running connections. The generated tokens can be used directly with Connect-DbaInstance and other dbatools commands to establish secure, modern authentication to Azure resources.\n\nWant to know more about Access Tokens? This page explains it well: https://dzone.com/articles/using-managed-identity-to-securely-access-azure-re", "Links": "https://dbatools.io/New-DbaAzAccessToken", "Synopsis": "Generates OAuth2 access tokens for Azure SQL Database and other Azure services authentication.", "Availability": "Windows, Linux, macOS", "Params": [ [ "Type", "Specifies the authentication method for generating the access token. ManagedIdentity uses Azure VM identity for password-free authentication, ServicePrincipal uses application credentials for \r\nautomated scripts, and RenewableServicePrincipal creates tokens that automatically refresh for long-running connections.", "", true, "false", "", "ManagedIdentity,ServicePrincipal,RenewableServicePrincipal" ], [ "Subtype", "Determines which Azure service resource to generate the token for. AzureSqlDb creates tokens for Azure SQL Database connections, while other options like KeyVault, Storage, and ResourceManager target \r\ntheir respective Azure services. Defaults to AzureSqlDb for database connections.", "", false, "false", "AzureSqlDb", "AzureSqlDb,ResourceManager,DataLake,EventHubs,KeyVault,ResourceManager,ServiceBus,Storage" ], [ "Config", "Optional configuration object for advanced token generation scenarios. Typically auto-generated based on the Subtype parameter and rarely needs manual specification. Use this only when you need \r\ncustom resource URLs or API versions not covered by standard subtypes.", "", false, "false", "", "" ], [ "Credential", "When using the ServicePrincipal type, a Credential is required. The username is the App ID and Password is the App Password\nhttps://docs.microsoft.com/en-us/azure/active-directory/user-help/multi-factor-authentication-end-user-app-passwords", "", false, "false", "", "" ], [ "Tenant", "Specifies the Azure Active Directory tenant ID or domain name for Service Principal authentication. Required when using ServicePrincipal or RenewableServicePrincipal types. Use your organization\u0027s \r\ntenant ID (GUID format) or domain name like \u0027contoso.onmicrosoft.com\u0027.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027azure.tenantid\u0027)", "" ], [ "Thumbprint", "Certificate thumbprint for Managed Service Identity authentication. Use this when your Azure VM or service uses certificate-based authentication instead of the default metadata endpoint. Defaults to \r\nthe value stored in dbatools configuration.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027azure.certificate.thumbprint\u0027)", "" ], [ "Store", "Specifies the certificate store location for MSI certificates. Choose CurrentUser for user-specific certificates or LocalMachine for system-wide certificates. Use with Thumbprint parameter for \r\ncertificate-based Managed Service Identity authentication.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027azure.certificate.store\u0027)", "CurrentUser,LocalMachine" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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": "New-DbaClientAlias", "Name": "New-DbaClientAlias", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "New-DbaClientAlias [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-ServerName] \u003cDbaInstanceParameter\u003e [-Alias] \u003cString\u003e [[-Protocol] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.RegisteredServer\nReturns one client alias object for each alias created on the specified computer(s). The object represents the SQL Server client alias created in the Windows registry.\nDefault display properties:\r\n- ComputerName: The computer where the alias was created\r\n- AliasName: The alias name that was created\r\n- ServerName: The SQL Server instance the alias points to\r\n- Protocol: The network protocol used (TCPIP or NamedPipes)\r\n- InstanceName: The instance name portion if specified\r\n- PipeName: The pipe name for NamedPipes protocol aliases\r\n- Port: The TCP port number if specified in ServerName\nAll properties from the base SMO RegisteredServer object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaClientAlias -ServerName sqlcluster\\sharepoint -Alias sp\nCreates a new TCP alias on the local workstation called sp, which points sqlcluster\\sharepoint\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaClientAlias -ServerName \u0027sqlcluster,14443\u0027 -Alias spinstance\nCreates a new TCP alias on the local workstation called spinstance, which points to sqlcluster, port 14443.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eNew-DbaClientAlias -ServerName sqlcluster\\sharepoint -Alias sp -Protocol NamedPipes\nCreates a new NamedPipes alias on the local workstation called sp, which points sqlcluster\\sharepoint", "Description": "Creates or updates SQL Server client aliases by modifying registry keys in HKLM:\\SOFTWARE\\Microsoft\\MSSQLServer\\Client\\ConnectTo, replacing the need for manual cliconfg.exe configuration. This allows applications and connections to use simple alias names instead of complex server names, instance names, or custom port numbers. Particularly useful when standardizing connections across multiple workstations, managing port changes, or simplifying named instance connections without modifying application connection strings.", "Links": "https://dbatools.io/New-DbaClientAlias", "Synopsis": "Creates SQL Server client aliases in the Windows registry for simplified connection management", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the target computer(s) where the client alias will be created in the registry.\r\nUse this when configuring aliases on remote workstations or when managing multiple computers centrally.\r\nDefaults to the local computer if not specified.", "", false, "false", "$env:COMPUTERNAME", "" ], [ "Credential", "Allows you to login to remote computers using alternative credentials", "", false, "false", "", "" ], [ "ServerName", "Specifies the actual SQL Server instance that the alias will point to.\r\nCan include instance names (server\\instance) or custom ports (server,1433) for non-standard configurations.\r\nThis is the real connection target that applications will reach when using the alias name.", "", true, "true (ByValue)", "", "" ], [ "Alias", "Defines the short, friendly name that applications will use to connect to SQL Server.\r\nChoose a simple name that\u0027s easier to remember and type than the full server\\instance name.\r\nThis alias name will appear in connection strings and SQL management tools.", "", true, "false", "", "" ], [ "Protocol", "Sets the network protocol for the connection, either TCPIP or NamedPipes.\r\nTCPIP is recommended for most scenarios and works across network boundaries.\r\nNamedPipes may be preferred for local connections or specific security requirements. Defaults to TCPIP.", "", false, "false", "TCPIP", "TCPIP,NamedPipes" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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", "", "" ] ] }, { "Name": "New-DbaCmConnection", "Description": "Creates connection objects that optimize remote computer management for SQL Server environments using CIM and WMI protocols.\nThese objects cache successful authentication methods and connection protocols, reducing authentication errors and improving performance when connecting to multiple SQL Server instances across different servers.\n\nThe function pre-configures connection settings including credentials, preferred protocols (CIM over WinRM or DCOM), and failover behavior.\nThis eliminates the need to repeatedly authenticate and negotiate protocols when running dbatools commands against remote SQL Server instances.\n\nNew-DbaCmConnection creates a new connection object and overwrites any existing cached connection for the specified computer.\nAll connection information beyond the computer name gets replaced with the new settings you specify.\n\nUnless connection caching has been disabled globally, all connections are automatically stored in the connection cache for reuse.\nThe returned object is primarily informational, though it can be used to bypass the cache if needed.\n\nNote: This function is typically optional since dbatools commands like Get-DbaCmObject automatically create default connections when first connecting to a computer.\nUse this function when you need to pre-configure specific authentication or protocol settings before running other dbatools commands.", "Tags": [ "ComputerManagement", "CIM" ], "Synopsis": "Creates and configures connection objects for remote computer management using CIM/WMI protocols.", "Outputs": "Dataplat.Dbatools.Connection.ManagementConnection\nReturns one management connection object per computer name provided. The connection object caches authentication credentials and CIM/WMI session settings for reuse across multiple dbatools commands.\nUnless connection caching is disabled globally (via dbatools configuration), the returned object is automatically stored in the connection cache and used transparently for subsequent operations. The \r\nreturned object itself is primarily informational but can be used to verify connection settings or to bypass the cache if needed.\nKey properties include:\r\n- ComputerName: The target computer name for the connection\r\n- Credentials: The PSCredential object for authentication, or null if using Windows credentials\r\n- UseWindowsCredentials: Boolean indicating if current Windows credentials are used\r\n- OverrideExplicitCredential: Boolean forcing use of cached credentials instead of explicit ones\r\n- DisabledConnectionTypes: ManagementConnectionType flags specifying which protocols to disable (CimRM, CimDCOM, etc.)\r\n- DisableBadCredentialCache: Boolean preventing storage of failed credentials\r\n- DisableCimPersistence: Boolean forcing new CIM sessions instead of reusing existing ones\r\n- DisableCredentialAutoRegister: Boolean preventing auto-storage of successful credentials\r\n- WindowsCredentialsAreBad: Boolean marking Windows credentials as invalid for this connection\r\n- CimWinRMOptions: WSManSessionOptions for configuring CIM over WinRM protocol settings\r\n- CimDCOMOptions: DComSessionOptions for configuring DCOM protocol settings", "Alias": "", "CommandName": "New-DbaCmConnection", "Availability": "Windows, Linux, macOS", "Links": "https://dbatools.io/New-DbaCmConnection", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaCmConnection -ComputerName sql2014 -UseWindowsCredentials -OverrideExplicitCredential -DisabledConnectionTypes CimRM\nReturns a new configuration object for connecting to the computer sql2014.\r\n- The current user credentials are set as valid\r\n- The connection is configured to ignore explicit credentials (so all connections use the windows credentials)\r\n- The connections will not try using CIM over WinRM\nUnless caching is globally disabled, this is automatically stored in the connection cache and will be applied automatically.\r\nIn that (the default) case, the output is for information purposes only and need not be used.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-Content computers.txt | New-DbaCmConnection -Credential $cred -CimWinRMOptions $options -DisableBadCredentialCache -OverrideExplicitCredential\nGathers a list of computers from a text file, then creates and registers connections for each of them, setting them to ...\r\n- use the credentials stored in $cred\r\n- use the options stored in $options when connecting using CIM over WinRM\r\n- not store credentials that are known to not work\r\n- to ignore explicitly specified credentials\nEssentially, this configures all connections to those computers to prefer failure with the specified credentials over using alternative credentials.", "Params": [ [ "ComputerName", "Specifies the target computer name or IP address where SQL Server instances are running.\r\nUse this to pre-configure connection settings before running other dbatools commands against remote SQL Server hosts.\r\nAccepts pipeline input for bulk configuration of multiple servers.", "", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "The credential to register.", "", false, "false", "", "" ], [ "UseWindowsCredentials", "Confirms that the current Windows user credentials are valid for connecting to the target computer.\r\nUse this when your current domain account has administrative rights on the SQL Server host.\r\nPre-validates these credentials to avoid authentication delays during subsequent dbatools operations.", "", false, "false", "False", "" ], [ "OverrideExplicitCredential", "Forces the connection to use cached working credentials instead of any explicitly provided credentials.\r\nUse this when you want to ensure consistent authentication across multiple dbatools commands.\r\nPrevents authentication failures when mixed credentials are accidentally specified in scripts.", "", false, "false", "False", "" ], [ "DisabledConnectionTypes", "Specifies which connection protocols to disable when connecting to the remote computer.\r\nUse this to force specific connection methods when certain protocols are blocked by network policies.\r\nCommon values include \u0027CimRM\u0027 to disable CIM over WinRM or \u0027CimDCOM\u0027 to disable DCOM connections.", "", false, "false", "None", "" ], [ "DisableBadCredentialCache", "Prevents failed credentials from being stored in the credential cache.\r\nUse this in environments where credentials change frequently or when testing different authentication methods.\r\nHelps avoid repeated authentication attempts with known bad credentials.", "", false, "false", "False", "" ], [ "DisableCimPersistence", "Forces creation of new CIM sessions for each connection instead of reusing existing sessions.\r\nUse this when troubleshooting connection issues or when working with servers that have session limits.\r\nMay impact performance but ensures fresh connections for each dbatools operation.", "", false, "false", "False", "" ], [ "DisableCredentialAutoRegister", "Prevents successful credentials from being automatically stored in the connection cache.\r\nUse this for one-time operations where you don\u0027t want credentials persisted for future use.\r\nUseful in high-security environments where credential caching is not permitted.", "", false, "false", "False", "" ], [ "EnableCredentialFailover", "Automatically switches to cached working credentials when the initially provided credentials fail.\r\nUse this to ensure dbatools operations continue even if incorrect credentials are accidentally specified.\r\nPrevents script interruptions due to authentication failures when multiple credential sets are available.", "", false, "false", "False", "" ], [ "WindowsCredentialsAreBad", "Explicitly marks the current Windows user credentials as invalid for this computer connection.\r\nUse this when your domain account lacks privileges on the target SQL Server host.\r\nForces the use of alternative credentials and prevents authentication attempts with insufficient privileges.", "", false, "false", "False", "" ], [ "CimWinRMOptions", "Configures advanced WinRM connection settings for CIM sessions to the target computer.\r\nUse this to specify custom ports, authentication methods, or SSL settings required by your network configuration.\r\nCreate the options object using New-CimSessionOption with specific timeout, encryption, or proxy settings.", "", false, "false", "", "" ], [ "CimDCOMOptions", "Configures advanced DCOM connection settings for legacy CIM sessions to the target computer.\r\nUse this when connecting to older Windows servers or when WinRM is not available.\r\nCreate the options object using New-CimSessionOption with DCOM-specific authentication and timeout settings.", "", 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", "", "" ] ], "Syntax": "New-DbaCmConnection [-ComputerName \u003cDbaCmConnectionParameter[]\u003e] [-Credential \u003cPSCredential\u003e] [-OverrideExplicitCredential] [-DisabledConnectionTypes {None | CimRM | CimDCOM | Wmi | PowerShellRemoting}] [-DisableBadCredentialCache] [-DisableCimPersistence] [-DisableCredentialAutoRegister] [-EnableCredentialFailover] [-WindowsCredentialsAreBad] [-CimWinRMOptions \u003cWSManSessionOptions\u003e] [-CimDCOMOptions \u003cDComSessionOptions\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nNew-DbaCmConnection [-ComputerName \u003cDbaCmConnectionParameter[]\u003e] [-UseWindowsCredentials] [-OverrideExplicitCredential] [-DisabledConnectionTypes {None | CimRM | CimDCOM | Wmi | PowerShellRemoting}] [-DisableBadCredentialCache] [-DisableCimPersistence] [-DisableCredentialAutoRegister] [-EnableCredentialFailover] [-CimWinRMOptions \u003cWSManSessionOptions\u003e] [-CimDCOMOptions \u003cDComSessionOptions\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]" }, { "Tags": [ "Certificate", "Security" ], "CommandName": "New-DbaComputerCertificate", "Name": "New-DbaComputerCertificate", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "New-DbaComputerCertificate [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-CaServer] \u003cString\u003e] [[-CaName] \u003cString\u003e] [[-ClusterInstanceName] \u003cString\u003e] [[-SecurePassword] \u003cSecureString\u003e] [[-FriendlyName] \u003cString\u003e] [[-CertificateTemplate] \u003cString\u003e] [[-KeyLength] \u003cInt32\u003e] [[-Store] \u003cString\u003e] [[-Folder] \u003cString\u003e] [[-Flag] \u003cString[]\u003e] [[-Dns] \u003cString[]\u003e] [-SelfSigned] [-EnableException] [[-HashAlgorithm] \u003cString\u003e] [[-MonthsValid] \u003cInt32\u003e] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.Security.Cryptography.X509Certificates.X509Certificate2\nReturns one or more X.509 certificate objects for the computers where certificates were successfully created and installed.\nFor local host (-ComputerName localhost or not specified): Returns the certificate object created or imported on the local machine after certificate generation/signing completes.\nFor remote hosts: Returns the certificate object after successful import on the remote computer via WinRM. When creating certificates for SQL Server failover clusters (-ClusterInstanceName \r\nspecified), a single certificate is created and imported on each cluster node specified in -ComputerName.\nDefault display properties (via Select-DefaultView):\r\n- FriendlyName: The friendly name assigned to the certificate (defaults to \"SQL Server\")\r\n- DnsNameList: Collection of DNS names in the certificate\u0027s Subject Alternative Name (SAN) extension\r\n- Thumbprint: The SHA-1 hash fingerprint of the certificate, used for certificate identification\r\n- NotBefore: DateTime when the certificate becomes valid\r\n- NotAfter: DateTime when the certificate expires\r\n- Subject: The certificate subject Distinguished Name (DN) containing the CN (Common Name)\r\n- Issuer: The issuer Distinguished Name (DN) for the certificate (either self-signed or CA name)\nAdditional properties available via Select-Object *:\r\n- SerialNumber: The certificate\u0027s serial number\r\n- Version: The X.509 version number (typically 3)\r\n- SignatureAlgorithm: The signing algorithm used (e.g., sha256RSA, sha1RSA)\r\n- PublicKey: The certificate\u0027s public key information\r\n- PrivateKey: The private key associated with this certificate (if present and accessible)\r\n- Extensions: Collection of X.509 extensions (e.g., Subject Alternative Name, Enhanced Key Usage)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaComputerCertificate\nCreates a computer certificate signed by the local domain CA for the local machine with the keylength of 1024.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaComputerCertificate -ComputerName Server1\nCreates a computer certificate signed by the local domain CA _on the local machine_ for server1 with the keylength of 1024.\nThe certificate is then copied to the new machine over WinRM and imported.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eNew-DbaComputerCertificate -ComputerName sqla, sqlb -ClusterInstanceName sqlcluster -KeyLength 4096\nCreates a computer certificate for sqlcluster, signed by the local domain CA, with the keylength of 4096.\nThe certificate is then copied to sqla _and_ sqlb over WinRM and imported.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eNew-DbaComputerCertificate -ComputerName Server1 -WhatIf\nShows what would happen if the command were run\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eNew-DbaComputerCertificate -SelfSigned\nCreates a self-signed certificate\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eNew-DbaComputerCertificate -SelfSigned -HashAlgorithm Sha256 -MonthsValid 60\nCreates a self-signed certificate using the SHA256 hashing algorithm that does not expire for 5 years", "Description": "Creates a new computer certificate - self-signed or signed by an Active Directory CA, using the Web Server certificate.\n\nBy default, a key with a length of 1024 and a friendly name of the machines FQDN is generated.\n\nThis command was originally intended to help automate the process so that SSL certificates can be available for enforcing encryption on connections.\n\nIt makes a lot of assumptions - namely, that your account is allowed to auto-enroll and that you have permission to do everything it needs to do ;)\n\nReferences:\nhttps://www.itprotoday.com/sql-server/7-steps-ssl-encryption\nhttps://azurebi.jppp.org/2016/01/23/using-lets-encrypt-certificates-for-secure-sql-server-connections/\nhttps://blogs.msdn.microsoft.com/sqlserverfaq/2016/09/26/creating-and-registering-ssl-certificates/\n\nThe certificate is generated using AD\u0027s webserver SSL template on the client machine and pushed to the remote machine.", "Links": "https://dbatools.io/New-DbaComputerCertificate", "Synopsis": "Creates a new computer certificate useful for Forcing Encryption", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the target computer or computers where the certificate will be created and installed. Defaults to localhost.\r\nFor SQL Server clusters, specify each cluster node here and use ClusterInstanceName for the cluster\u0027s virtual name.\r\nThe certificate is created locally and then copied to remote machines via WinRM if needed.", "", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Allows you to login to $ComputerName using alternative credentials.", "", false, "false", "", "" ], [ "CaServer", "Specifies the Certificate Authority server that will sign the certificate request.\r\nWhen omitted, the function automatically discovers the CA server from Active Directory.\r\nRequired for domain-signed certificates when automatic discovery fails.", "", false, "false", "", "" ], [ "CaName", "Specifies the Certificate Authority name on the CA server.\r\nWhen omitted, the function automatically discovers the CA name from Active Directory.\r\nMust match the exact CA name as registered in the domain\u0027s PKI infrastructure.", "", false, "false", "", "" ], [ "ClusterInstanceName", "Specifies the virtual cluster name when creating certificates for SQL Server failover clusters.\r\nThe certificate subject and SAN will use this cluster name instead of individual node names.\r\nUse ComputerName to specify each physical cluster node where the certificate will be installed.", "", false, "false", "", "" ], [ "SecurePassword", "Specifies the password used to protect the private key during certificate export and import operations.\r\nRequired when installing certificates on remote machines to secure the private key during transport.\r\nThe same password is used for both export from the local machine and import on remote machines.", "Password", false, "false", "", "" ], [ "FriendlyName", "Specifies the friendly name displayed in the certificate store to help identify the certificate.\r\nDefaults to \"SQL Server\" making it easy to locate certificates intended for SQL Server encryption.\r\nChoose descriptive names like \"SQL Prod Cluster\" or \"SQL Dev Server\" for better organization.", "", false, "false", "SQL Server", "" ], [ "CertificateTemplate", "Specifies the Active Directory Certificate Template used for certificate generation.\r\nDefaults to \"WebServer\" which provides the necessary server authentication capabilities for SQL Server encryption.\r\nThe template must exist in your domain\u0027s PKI and allow auto-enrollment for your account.", "", false, "false", "WebServer", "" ], [ "KeyLength", "Specifies the RSA key size in bits for the certificate\u0027s private key.\r\nDefaults to 1024 bits, though 2048 or 4096 bits provide better security for production environments.\r\nLonger keys provide stronger encryption but may slightly impact performance during SSL handshakes.", "", false, "false", "1024", "" ], [ "Store", "Specifies the certificate store location where the certificate will be installed.\r\nDefaults to \"LocalMachine\" which makes certificates available to services like SQL Server.\r\nUse \"CurrentUser\" only for user-specific certificates that don\u0027t need service access.", "", false, "false", "LocalMachine", "" ], [ "Folder", "Specifies the certificate store folder where the certificate will be placed.\r\nDefaults to \"My\" (Personal certificates) which is where SQL Server looks for server certificates.\r\nUse \"TrustedPeople\" or other folders only for specific certificate trust scenarios.", "", false, "false", "My", "" ], [ "Flag", "Specifies how the certificate\u0027s private key should be handled during import operations.\r\nDefaults to \"Exportable, PersistKeySet\" allowing the key to be backed up and persisted on disk.\r\nUse \"NonExportable\" for high-security environments where private keys should never leave the machine.\r\n\"UserProtected\" requires interactive confirmation and only works on localhost installations.", "", false, "false", "@(\"Exportable\", \"PersistKeySet\")", "EphemeralKeySet,Exportable,PersistKeySet,UserProtected,NonExportable" ], [ "Dns", "Specifies additional DNS names to include in the certificate\u0027s Subject Alternative Name (SAN) extension.\r\nBy default, includes the computer name and FQDN, or cluster name and cluster FQDN for clusters.\r\nAdd extra DNS names that clients will use to connect, such as aliases or load balancer names.", "", false, "false", "", "" ], [ "SelfSigned", "Creates a self-signed certificate instead of requesting one from a Certificate Authority.\r\nUseful for development environments or when no domain CA is available.\r\nSelf-signed certificates will generate trust warnings unless manually added to client trust stores.", "", 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", "" ], [ "HashAlgorithm", "Specifies the cryptographic hash algorithm used for certificate signing.\r\nDefaults to \"sha1\" for compatibility, though \"Sha256\" or higher is recommended for production security.\r\nModern browsers and applications prefer SHA-256 or higher; avoid MD5 and MD4 for security reasons.", "", false, "false", "sha1", "Sha256,sha384,sha512,sha1,md5,md4,md2" ], [ "MonthsValid", "Specifies how many months the self-signed certificate remains valid from the creation date.\r\nDefaults to 12 months; use longer periods like 60 months (5 years) to reduce certificate renewal frequency.\r\nOnly applies to self-signed certificates; CA-signed certificates use the CA\u0027s validity period.", "", false, "false", "12", "" ], [ "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": "New-DbaComputerCertificateSigningRequest", "Name": "New-DbaComputerCertificateSigningRequest", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "New-DbaComputerCertificateSigningRequest [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-ClusterInstanceName] \u003cString\u003e] [[-Path] \u003cString\u003e] [[-FriendlyName] \u003cString\u003e] [[-KeyLength] \u003cInt32\u003e] [[-Dns] \u003cString[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.IO.FileInfo\nReturns file information objects for each certificate file created. Two files are returned per computer:\r\n- request.inf - Certificate configuration file containing certificate settings and Subject Alternative Names\r\n- \u003cfqdn\u003e.csr - Certificate signing request file that is submitted to the Certificate Authority\nProperties:\r\n- Name: The file name (request.inf or \u003cfqdn\u003e.csr)\r\n- FullName: The complete file path\r\n- DirectoryName: The directory containing the file\r\n- Length: The file size in bytes\r\n- LastWriteTime: DateTime when the file was created\r\n- CreationTime: DateTime of file creation\r\n- Extension: The file extension (.inf or .csr)\nAll standard System.IO.FileInfo properties are available for use with Select-Object.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaComputerCertificateSigningRequest\nCreates a computer certificate signing request for the local machine with the keylength of 1024.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaComputerCertificateSigningRequest -ComputerName Server1\nCreates a computer certificate signing request for server1 with the keylength of 1024.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eNew-DbaComputerCertificateSigningRequest -ComputerName sqla, sqlb -ClusterInstanceName sqlcluster -KeyLength 4096\nCreates a computer certificate signing request for sqlcluster with the keylength of 4096.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eNew-DbaComputerCertificateSigningRequest -ComputerName Server1 -WhatIf\nShows what would happen if the command were run", "Description": "Creates certificate signing requests (CSRs) that can be submitted to your Certificate Authority to obtain SSL/TLS certificates for SQL Server instances. This eliminates the manual process of creating certificate requests and ensures proper configuration for SQL Server\u0027s encryption requirements.\n\nThe function generates both the certificate configuration file (.inf) and the signing request file (.csr) with proper Subject Alternative Names (SAN) to support SQL Server\u0027s certificate validation. This is essential when implementing Force Encryption, configuring encrypted connections, or meeting compliance requirements that mandate encrypted database communications.\n\nSupports both standalone SQL Server instances and cluster configurations, automatically resolving FQDNs and configuring appropriate DNS entries. The generated certificates work with SQL Server\u0027s encryption features including encrypted client connections, mirroring, and backup encryption scenarios.\n\nBy default, creates RSA certificates with 1024-bit keys, though this can be customized for stronger encryption requirements. All certificates are configured as machine certificates with the Microsoft RSA SChannel Cryptographic Provider for compatibility with SQL Server\u0027s encryption stack.", "Links": "https://dbatools.io/New-DbaComputerCertificateSigningRequest", "Synopsis": "Generates certificate signing requests for SQL Server instances to enable SSL/TLS encryption and connection security.", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "The target computer name hosting the SQL Server instance where the certificate will be installed. Accepts multiple computer names for batch processing.\r\nFor standalone servers, this creates certificates for the specified machine. For clusters, specify each cluster node here and use ClusterInstanceName for the virtual cluster name.", "", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Allows you to login to $ComputerName using alternative credentials.", "", false, "false", "", "" ], [ "ClusterInstanceName", "Specifies the virtual cluster name for SQL Server failover cluster instances. This becomes the certificate\u0027s Common Name (CN) and primary DNS entry.\r\nRequired when generating certificates for clustered SQL Server instances to ensure proper SSL validation during failovers between cluster nodes.", "", false, "false", "", "" ], [ "Path", "Directory where the certificate configuration (.inf) and signing request (.csr) files will be created. Defaults to the dbatools export path.\r\nEach computer gets its own subdirectory containing the certificate files needed for submission to your Certificate Authority.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027Path.DbatoolsExport\u0027)", "" ], [ "FriendlyName", "Sets a descriptive name for the certificate that appears in the Windows Certificate Store. Defaults to \"SQL Server\".\r\nThis name helps administrators identify the certificate\u0027s purpose when managing multiple certificates on the same server.", "", false, "false", "SQL Server", "" ], [ "KeyLength", "Specifies the RSA key length in bits for the certificate. Defaults to 1024 for compatibility, though 2048 or 4096 is recommended for production.\r\nHigher key lengths provide stronger encryption but may impact SQL Server connection performance on older hardware.", "", false, "false", "1024", "" ], [ "Dns", "Additional DNS names to include in the certificate\u0027s Subject Alternative Name (SAN) field. By default includes both short and FQDN names.\r\nAdd extra DNS entries here if clients connect using aliases, load balancer names, or other DNS records that point to your SQL Server 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", "" ], [ "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", "Connect", "ConnectionString" ], "CommandName": "New-DbaConnectionString", "Name": "New-DbaConnectionString", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "New-DbaConnectionString [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-Credential] \u003cPSCredential\u003e] [[-AccessToken] \u003cString\u003e] [[-ApplicationIntent] \u003cString\u003e] [[-BatchSeparator] \u003cString\u003e] [[-ClientName] \u003cString\u003e] [[-ConnectTimeout] \u003cInt32\u003e] [[-Database] \u003cString\u003e] [-EncryptConnection] [[-FailoverPartner] \u003cString\u003e] [-IsActiveDirectoryUniversalAuth] [[-LockTimeout] \u003cInt32\u003e] [[-MaxPoolSize] \u003cInt32\u003e] [[-MinPoolSize] \u003cInt32\u003e] [-MultipleActiveResultSets] [-MultiSubnetFailover] [[-NetworkProtocol] \u003cString\u003e] [-NonPooledConnection] [[-PacketSize] \u003cInt32\u003e] [[-PooledConnectionLifetime] \u003cInt32\u003e] \r\n[[-SqlExecutionModes] \u003cString\u003e] [[-StatementTimeout] \u003cInt32\u003e] [-TrustServerCertificate] [[-WorkstationId] \u003cString\u003e] [-Legacy] [[-AppendConnectionString] \u003cString\u003e] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.String\nReturns one or more SQL Server connection strings as plain text strings. Each connection string contains all the connection parameters in standard SQL Server connection string format.\nThe output format varies by usage path:\r\n- When an SMO Server object is passed via pipeline, the existing connection string is extracted and optionally modified with new parameters\r\n- When SQL instance names are specified, new connection strings are built with the specified parameters\r\n- When using the legacy code path, connection strings are constructed using SMO ServerConnection objects\nConnection string examples:\r\n- Windows Authentication: \"Data Source=sql2016;Connection Timeout=15;Integrated Security=true;Application Name=\"custom connection\"\"\r\n- SQL Authentication: \"Data Source=sql2016;User ID=sqladmin;Password=P@ssw0rd;Connection Timeout=15;Application Name=\"custom connection\"\"\r\n- Azure SQL with AD: \"Data Source=tcp:mydb.database.windows.net,1433;Initial Catalog=db;User ID=user@domain.onmicrosoft.com;Password=pwd;MultipleActiveResultSets=False;Connect \r\nTimeout=30;Encrypt=Mandatory;TrustServerCertificate=False;Authentication=Active Directory Password;Application Name=\"custom connection\"\"\nThe returned string can be used directly with SqlClient, ADO.NET applications, or any tool that accepts SQL Server connection strings. Use `Write-Host` to display in a terminal or pipe to other \r\ncommands that accept connection strings.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaConnectionString -SqlInstance sql2014\nCreates a connection string that connects using Windows Authentication\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eConnect-DbaInstance -SqlInstance sql2016 | New-DbaConnectionString\nBuilds a connected SMO object using Connect-DbaInstance then extracts and displays the connection string\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$wincred = Get-Credential ad\\sqladmin\nPS C:\\\u003e New-DbaConnectionString -SqlInstance sql2014 -Credential $wincred\nCreates a connection string that connects using alternative Windows credentials\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$sqlcred = Get-Credential sqladmin\nPS C:\\\u003e $server = New-DbaConnectionString -SqlInstance sql2014 -Credential $sqlcred\nLogin to sql2014 as SQL login sqladmin.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$connstring = New-DbaConnectionString -SqlInstance mydb.database.windows.net -SqlCredential me@myad.onmicrosoft.com -Database db\nCreates a connection string for an Azure Active Directory login to Azure SQL db. Output looks like this:\r\nData Source=TCP:mydb.database.windows.net,1433;Initial Catalog=db;User ID=me@myad.onmicrosoft.com;Password=fakepass;MultipleActiveResultSets=False;Connect \r\nTimeout=30;Encrypt=True;TrustServerCertificate=False;Application Name=\"dbatools PowerShell module - dbatools.io\";Authentication=\"Active Directory Password\"\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e$server = New-DbaConnectionString -SqlInstance sql2014 -ClientName \"mah connection\"\nCreates a connection string that connects using Windows Authentication and uses the client name \"mah connection\". So when you open up profiler or use extended events, you can search for \"mah \r\nconnection\".\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003e$server = New-DbaConnectionString -SqlInstance sql2014 -AppendConnectionString \"Packet Size=4096;AttachDbFilename=C:\\MyFolder\\MyDataFile.mdf;User Instance=true;\"\nCreates a connection string 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 8 --------------------------\nPS C:\\\u003e$server = New-DbaConnectionString -SqlInstance sql2014 -NetworkProtocol TcpIp -MultiSubnetFailover\nCreates a connection string with Windows Authentication that uses TCPIP and has MultiSubnetFailover enabled.\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003e$connstring = New-DbaConnectionString sql2016 -ApplicationIntent ReadOnly\nCreates a connection string with ReadOnly ApplicationIntent.", "Description": "Creates properly formatted SQL Server connection strings without having to manually construct complex connection string syntax. Instead of remembering obscure keywords like \"Data Source\" or \"Initial Catalog\", you can use familiar PowerShell parameters like -SqlInstance and -Database.\n\nThis function handles the complexity of connection string building for you, including authentication methods (Windows, SQL Server, Azure AD), encryption settings, timeout values, and Azure SQL Database specifics. It supports both legacy System.Data.SqlClient and modern Microsoft.Data.SqlClient providers.\n\nParticularly useful when building custom applications, automation scripts, or when you need to generate connection strings for other tools that require them. The function can also extract connection strings from existing SMO server objects for reuse or modification.\n\nSee https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring.aspx\nand https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder.aspx\nand https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.aspx", "Links": "https://dbatools.io/New-DbaConnectionString", "Synopsis": "Creates connection strings for SQL Server instances using PowerShell-friendly parameters", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "ServerInstance,SqlServer,Server,DataSource", true, "true (ByValue)", "", "" ], [ "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. 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.", "SqlCredential", false, "false", "", "" ], [ "AccessToken", "Specifies that Azure Active Directory access token authentication should be used. When specified, the connection string is configured for token-based authentication.\r\nUse this when connecting to Azure SQL with an access token you\u0027ve obtained separately from Azure AD authentication flows.", "", false, "false", "", "" ], [ "ApplicationIntent", "Specifies whether the application workload is read-only or read-write when connecting to an Always On availability group. Valid values are ReadOnly and ReadWrite.\r\nUse ReadOnly to connect to secondary replicas for reporting queries, which helps offload read traffic from the primary replica.", "", false, "false", "", "ReadOnly,ReadWrite" ], [ "BatchSeparator", "Sets the batch separator for SQL commands. Defaults to \"GO\" if not specified.\r\nChange this when working with tools or scripts that use different batch separators, or when \"GO\" conflicts with your SQL code.", "", false, "false", "", "" ], [ "ClientName", "Sets the application name that appears in SQL Server monitoring tools like Activity Monitor, Extended Events, and Profiler. Defaults to \"dbatools PowerShell module - dbatools.io\".\r\nUse a descriptive name when you need to identify specific scripts or applications in SQL Server logs and monitoring for troubleshooting or performance analysis.", "", false, "false", "custom connection", "" ], [ "ConnectTimeout", "Sets the number of seconds to wait while attempting to establish a connection before timing out. Valid range is 0 to 2147483647.\r\nIncrease this value for slow networks or when connecting to busy servers. Azure SQL Database connections automatically default to 30 seconds due to network latency considerations.", "", false, "false", "0", "" ], [ "Database", "Specifies the initial database to connect to when the connection is established. Sets the Initial Catalog property in the connection string.\r\nRequired for Azure SQL Database connections, and useful for ensuring connections start in the correct database context for your operations.", "", false, "false", "", "" ], [ "EncryptConnection", "Forces SSL/TLS encryption for the connection to protect data in transit. Automatically enabled for Azure SQL Database connections.\r\nEnable this for connections over untrusted networks or when your security policy requires encrypted database connections. Requires proper SSL certificates when TrustServerCertificate is false.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027sql.connection.encrypt\u0027)", "" ], [ "FailoverPartner", "Specifies the failover partner server name for database mirroring configurations. Limited to 128 characters or less.\r\nUse this when connecting to databases configured with database mirroring to enable automatic failover if the primary server becomes unavailable. Requires the Database parameter to be specified.", "", false, "false", "", "" ], [ "IsActiveDirectoryUniversalAuth", "Enables Azure Active Directory Universal Authentication with Multi-Factor Authentication (MFA) support for Azure SQL connections.\r\nUse this when connecting to Azure SQL Database or Managed Instance with accounts that require MFA or when using Azure AD guest accounts.", "", false, "false", "False", "" ], [ "LockTimeout", "Sets the number of seconds to wait for locks to be released before timing out. Not supported in connection strings - this parameter generates a warning.\r\nThis parameter is included for legacy compatibility but has no effect on the generated connection string.", "", false, "false", "0", "" ], [ "MaxPoolSize", "Sets the maximum number of connections allowed in the connection pool for this connection string. Defaults to 100 if not specified.\r\nIncrease this value for applications with high concurrency requirements, or decrease it to limit resource usage on the SQL Server.", "", false, "false", "0", "" ], [ "MinPoolSize", "Sets the minimum number of connections maintained in the connection pool for this connection string. Defaults to 0 if not specified.\r\nSet this to a higher value when you want to maintain warm connections for faster subsequent connection requests, especially for frequently accessed databases.", "", false, "false", "0", "" ], [ "MultipleActiveResultSets", "Enables Multiple Active Result Sets (MARS) allowing multiple commands to be executed simultaneously on a single connection.\r\nEnable this when your application needs to execute multiple queries concurrently on the same connection, such as reading from one result set while executing another query.", "", false, "false", "False", "" ], [ "MultiSubnetFailover", "Enables faster failover detection when connecting to Always On availability groups across different subnets.\r\nUse this when your availability group replicas are distributed across multiple subnets to reduce connection timeout during failover scenarios.", "", false, "false", "False", "" ], [ "NetworkProtocol", "Forces a specific network protocol for the connection. Valid values include TcpIp, NamedPipes, SharedMemory, and others.\r\nUse TcpIp for remote connections or NamedPipes for local connections when you need to override default protocol selection or troubleshoot connectivity issues.", "", false, "false", "", "TcpIp,NamedPipes,Multiprotocol,AppleTalk,BanyanVines,Via,SharedMemory,NWLinkIpxSpx" ], [ "NonPooledConnection", "Disables connection pooling for this connection, creating a dedicated connection that isn\u0027t shared.\r\nUse this for long-running operations, debugging scenarios, or when you need to ensure complete isolation of the database connection.", "", false, "false", "False", "" ], [ "PacketSize", "Sets the network packet size in bytes for communication with SQL Server. Must be between 512 and 32767 bytes.\r\nIncrease this value for bulk operations or large result sets to improve performance, but ensure the server\u0027s network packet size setting can accommodate the specified value.", "", false, "false", "0", "" ], [ "PooledConnectionLifetime", "Sets the maximum lifetime in seconds for pooled connections. Connections older than this value are destroyed when returned to the pool.\r\nUse this in clustered environments to force load balancing across cluster nodes or to ensure connections don\u0027t remain open indefinitely. Zero means no lifetime limit.", "", false, "false", "0", "" ], [ "SqlExecutionModes", "Controls how SQL commands are processed - immediately executed, captured for review, or both. Not supported in connection strings - this parameter generates a warning.\r\nThis parameter is included for legacy compatibility but has no effect on the generated connection string.", "", false, "false", "", "CaptureSql,ExecuteAndCaptureSql,ExecuteSql" ], [ "StatementTimeout", "Sets the number of seconds before SQL commands timeout. Not supported in connection strings - this parameter generates a warning.\r\nThis parameter is included for legacy compatibility but has no effect on the generated connection string. Use the CommandTimeout property on SqlCommand objects instead.", "", false, "false", "0", "" ], [ "TrustServerCertificate", "Bypasses SSL certificate validation when EncryptConnection is enabled. The connection will be encrypted but the server certificate won\u0027t be verified.\r\nUse this for development environments or when connecting to servers with self-signed certificates, but avoid in production due to security risks.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027sql.connection.trustcert\u0027)", "" ], [ "WorkstationId", "Sets the workstation identifier that appears in SQL Server system views and logs. Defaults to the local computer name if not specified.\r\nUse this to identify connections from specific machines or applications when monitoring SQL Server activity or troubleshooting connection issues.", "", false, "false", "", "" ], [ "Legacy", "Forces the use of the older System.Data.SqlClient provider instead of the modern Microsoft.Data.SqlClient provider.\r\nUse this only when connecting to applications or tools that specifically require the legacy provider for compatibility reasons.", "", false, "false", "False", "" ], [ "AppendConnectionString", "Adds custom connection string parameters to the generated connection string. Authentication parameters cannot be passed this way.\r\nUse this when you need to add specialized connection parameters like AttachDbFilename, User Instance, or custom driver-specific settings that aren\u0027t available through other parameters.", "", 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": [ "SqlBuild", "ConnectionString", "Connection" ], "CommandName": "New-DbaConnectionStringBuilder", "Name": "New-DbaConnectionStringBuilder", "Author": "zippy1981 | Chrissy LeMaire (@cl)", "Syntax": "New-DbaConnectionStringBuilder [[-ConnectionString] \u003cString[]\u003e] [[-ApplicationName] \u003cString\u003e] [[-DataSource] \u003cString\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-InitialCatalog] \u003cString\u003e] [-IntegratedSecurity] [[-UserName] \u003cString\u003e] [[-Password] \u003cString\u003e] [-MultipleActiveResultSets] [[-ColumnEncryptionSetting] \u003cString\u003e] [-Legacy] [-NonPooledConnection] [[-WorkstationID] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.Data.SqlClient.SqlConnectionStringBuilder (default) or System.Data.SqlClient.SqlConnectionStringBuilder (when -Legacy is specified)\nReturns one SqlConnectionStringBuilder object for each connection string provided via the pipeline or -ConnectionString parameter. The builder object allows programmatic access and modification of \r\nall SQL Server connection string properties.\nThe returned object exposes all connection string settings as accessible properties including:\r\n- Application Name: The application name for connection identification\r\n- Data Source: The SQL Server instance name and port\r\n- Initial Catalog: The default database for the connection\r\n- Integrated Security: Boolean indicating Windows Authentication usage\r\n- User ID: SQL Server login name (if using SQL Authentication)\r\n- Password: SQL Server login password (if using SQL Authentication)\r\n- Workstation ID: The workstation identifier for connection tracking\r\n- MultipleActiveResultSets: Boolean indicating if MARS is enabled\r\n- Column Encryption Setting: Setting for Always Encrypted support (Enabled or null)\r\n- Pooling: Boolean indicating if connection pooling is enabled\nAll properties from the base SqlConnectionStringBuilder are accessible through normal PowerShell property access or by converting the builder to a connection string using the ToString() method.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaConnectionStringBuilder\nReturns an empty ConnectionStringBuilder\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\"Data Source=localhost,1433;Initial Catalog=AlwaysEncryptedSample;UID=sa;PWD=alwaysB3Encrypt1ng;Application Name=Always Encrypted Sample MVC App;Column Encryption Setting=enabled\" | \r\nNew-DbaConnectionStringBuilder\nReturns a connection string builder that can be used to connect to the local sql server instance on the default port.", "Description": "Creates a Microsoft.Data.SqlClient.SqlConnectionStringBuilder object from either an existing connection string or individual connection parameters. This allows you to programmatically build, modify, or validate connection strings without manually concatenating string values. The function handles authentication methods, encryption settings, connection pooling, and other SQL Server connection options, making it useful for scripts that need to connect to different SQL Server instances with varying configurations.", "Links": "https://dbatools.io/New-DbaConnectionStringBuilder", "Synopsis": "Creates a SqlConnectionStringBuilder object for constructing properly formatted SQL Server connection strings", "Availability": "Windows, Linux, macOS", "Params": [ [ "ConnectionString", "Specifies an existing SQL Server connection string to use as the foundation for the builder object. The function will parse this string and populate the builder with its values.\r\nUse this when you need to modify or validate an existing connection string rather than building one from scratch.", "", false, "true (ByValue)", "", "" ], [ "ApplicationName", "Sets the application name that identifies your script or application to SQL Server in monitoring tools and logs. Defaults to \"dbatools Powershell Module\".\r\nUseful for tracking connection sources in SQL Server\u0027s sys.dm_exec_sessions and activity monitor when troubleshooting performance or connection issues.", "", false, "false", "dbatools Powershell Module", "" ], [ "DataSource", "Specifies the SQL Server instance name for the connection string. Can include server name, instance name, and port (e.g., \"ServerName\\InstanceName,1433\").\r\nUse this to set or override the server target when building connection strings for different environments or instances.", "SqlInstance", false, "false", "", "" ], [ "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", "", "" ], [ "InitialCatalog", "Sets the default database context for the connection. When specified, queries will execute in this database unless explicitly changed.\r\nUse this when your script needs to work with a specific database rather than connecting to the server\u0027s default database.", "Database", false, "false", "", "" ], [ "IntegratedSecurity", "Enables Windows Authentication for the connection, using the current user\u0027s Windows credentials to authenticate to SQL Server.\r\nUse this when connecting to SQL Server instances configured for Windows Authentication mode or mixed mode with your current Windows account.", "", false, "false", "False", "" ], [ "UserName", "Specifies the SQL Server login name for SQL Server Authentication. Cannot be used with SqlCredential parameter.\r\nConsider using SqlCredential parameter instead for better security as it avoids exposing credentials in plain text.", "", false, "false", "", "" ], [ "Password", "Specifies the password for SQL Server Authentication when using the UserName parameter. Cannot be used with SqlCredential parameter.\r\nConsider using SqlCredential parameter instead for better security as it avoids exposing passwords in plain text or command history.", "", false, "false", "", "" ], [ "MultipleActiveResultSets", "Enables Multiple Active Result Sets (MARS) allowing multiple commands to be executed concurrently on a single connection.\r\nUse this when your script needs to execute overlapping commands or maintain multiple data readers on the same connection simultaneously.", "MARS", false, "false", "False", "" ], [ "ColumnEncryptionSetting", "Enables Always Encrypted functionality for the connection, allowing access to encrypted columns in SQL Server databases.\r\nUse this when connecting to databases with Always Encrypted columns that your application needs to decrypt and work with.", "AlwaysEncrypted", false, "false", "", "Enabled" ], [ "Legacy", "Creates the connection string builder using the older System.Data.SqlClient library instead of the newer Microsoft.Data.SqlClient library.\r\nUse this only when working with legacy applications or frameworks that specifically require the older SQL Client library for compatibility.", "", false, "false", "False", "" ], [ "NonPooledConnection", "Disables connection pooling, creating a dedicated connection that bypasses the connection pool. By default, connections are pooled for better performance.\r\nUse this for diagnostic scenarios or when you need to ensure complete connection isolation, though it may impact performance.", "", false, "false", "False", "" ], [ "WorkstationID", "Sets the workstation identifier that appears in SQL Server logs and monitoring tools to identify the source computer. Defaults to the current computer name.\r\nUseful for tracking connections by source machine in sys.dm_exec_sessions or when troubleshooting connection issues in multi-server environments.", "", false, "false", "$env:COMPUTERNAME", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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", "Credential", "Security" ], "CommandName": "New-DbaCredential", "Name": "New-DbaCredential", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "New-DbaCredential [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Name] \u003cString\u003e] [-Identity] \u003cString\u003e [[-SecurePassword] \u003cSecureString\u003e] [[-MappedClassType] \u003cString\u003e] [[-ProviderName] \u003cString\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Credential\nReturns one Credential object for each credential successfully created on the target instance. The credential object contains both SMO-level properties and dbatools-specific NoteProperties for \r\nconnection 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- Name: The name of the credential\r\n- Identity: The authentication identity for the credential (account name, URI, or special value)\r\n- CreateDate: DateTime when the credential was created on the instance\r\n- MappedClassType: The mapped class type - 0 for None (standard credentials), 1 for CryptographicProvider (EKM scenarios)\r\n- ProviderName: The name of the cryptographic provider (if MappedClassType is CryptographicProvider)\nAdditional properties available from the SMO Credential object:\r\n- Owner: The owner/principal that owns the credential\r\n- ID: The unique identifier for the credential within the instance\r\n- DateLastModified: DateTime when the credential was last modified\r\n- Urn: The Uniform Resource Name for the credential object\r\n- State: The current state of the SMO object (Existing, Creating, Deleting, etc.)\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:\\\u003eNew-DbaCredential -SqlInstance Server1 -Name MyCredential -Identity \"ad\\user\" -SecurePassword (Get-Credential NoUsernameNeeded).Password\nIt will create a credential named \"MyCredential\" that as \"ad\\user\" as identity and a password on server1 if it does not exist.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaCredential -SqlInstance Server1 -Identity \"MyIdentity\"\nIt will create a credential with identity value \"MyIdentity\" and same name but without a password on server1 if it does not exist.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$params = @{\n\u003e\u003eSqlInstance = \"Server1\"\r\n\u003e\u003eName = \"AzureBackupBlobStore\"\r\n\u003e\u003eIdentity = \"https://\u003cAzure Storage Account Name\u003e.blob.core.windows.net/\u003cBlob Container Name\u003e\"\r\n\u003e\u003eSecurePassword = (Get-Credential NoUsernameNeeded).Password # \u003cAzure Storage Account Access Key\u003e\r\n\u003e\u003e}\r\nPS C:\\\u003e New-DbaCredential @params\nCreates a credential, \"AzureBackupBlobStore\", on Server1 using the Access Keys for Backup To URL. Identity must be the full URI for the blob container that will be the backup target. The \r\nSecurePassword supplied is one of the two Access Keys for the Azure Storage Account.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$sasParams = @{\n\u003e\u003eSqlInstance = \"server1\"\r\n\u003e\u003eName = \"https://\u003cazure storage account name\u003e.blob.core.windows.net/\u003cblob container\u003e\"\r\n\u003e\u003eIdentity = \"SHARED ACCESS SIGNATURE\"\r\n\u003e\u003eSecurePassword = (Get-Credential NoUsernameNeeded).Password # \u003cShared Access Token\u003e\r\n\u003e\u003e}\r\nPS C:\\\u003e New-DbaCredential @sasParams\nCreate a credential on Server1 using a SAS token for Backup To URL. The Name is the full URI for the blob container that will be the backup target.\r\nThe SecurePassword will be the Shared Access Token (SAS), as a SecureString.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$managedIdentityParams = @{\n\u003e\u003eSqlInstance = \"server1\"\r\n\u003e\u003eName = \"https://\u003cazure storage account name\u003e.blob.core.windows.net/\u003cblob container\u003e\"\r\n\u003e\u003eIdentity = \"Managed Identity\"\r\n\u003e\u003e}\r\nPS C:\\\u003e New-DbaCredential @managedIdentityParams\nCreate a credential on Server1 using a Managed Identity for Backup To URL. The Name is the full URI for the blob container that will be the backup target.\r\nAs no password is needed in this case, we just don\u0027t pass the -SecurePassword parameter.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e$s3Params = @{\n\u003e\u003eSqlInstance = \"server1\"\r\n\u003e\u003eName = \"s3://mybucket.s3.us-west-2.amazonaws.com/backups\"\r\n\u003e\u003eIdentity = \"S3 Access Key\"\r\n\u003e\u003eSecurePassword = (ConvertTo-SecureString -String \"AKIAIOSFODNN7EXAMPLE:wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY\" -AsPlainText -Force)\r\n\u003e\u003e}\r\nPS C:\\\u003e New-DbaCredential @s3Params\nCreates a credential on Server1 for SQL Server 2022+ Backup to URL with S3-compatible object storage. The Name must be the S3 URL path matching your backup destination. The Identity must be exactly \r\n\u0027S3 Access Key\u0027. The SecurePassword contains your Access Key ID and Secret Key ID separated by a colon (AccessKeyID:SecretKeyID).", "Description": "Creates a SQL Server credential that stores authentication information for connecting to external resources like Azure storage accounts, network shares, or service accounts. Credentials are commonly used for backup to URL operations, SQL Agent job authentication, and accessing external data sources. The function supports various authentication methods including traditional username/password, Azure storage access keys, SAS tokens, and managed identities.", "Links": "https://dbatools.io/New-DbaCredential", "Synopsis": "Creates a SQL Server credential for authentication to external resources", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server(s)", "", 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", "", "" ], [ "Name", "Specifies the name for the SQL Server credential object. Defaults to the Identity value if not provided.\r\nUse a descriptive name that identifies the purpose, like \u0027AzureBackupStorage\u0027 or \u0027NetworkShareAccess\u0027.", "", false, "false", "$Identity", "" ], [ "Identity", "Defines the authentication identity for the credential. Can be a Windows account, service account, Azure storage URI, or special values like \u0027SHARED ACCESS SIGNATURE\u0027 or \u0027Managed Identity\u0027.\r\nFor Azure backup scenarios, use the full blob container URI or SAS/Managed Identity authentication methods.", "CredentialIdentity", true, "false", "", "" ], [ "SecurePassword", "Provides the password or access key as a SecureString for credential authentication. Required for most authentication methods except Managed Identity.\r\nFor Azure storage, this would be the access key or SAS token. Use Get-Credential or ConvertTo-SecureString to create the SecureString.", "Password", false, "false", "", "" ], [ "MappedClassType", "Specifies the credential mapping class type. Use \u0027CryptographicProvider\u0027 for credentials that will use cryptographic providers, or \u0027None\u0027 for standard credentials.\r\nMost common scenarios use \u0027None\u0027 (default). Only specify \u0027CryptographicProvider\u0027 when working with EKM or custom cryptographic providers.", "", false, "false", "None", "CryptographicProvider,None" ], [ "ProviderName", "Specifies the name of the cryptographic provider when MappedClassType is \u0027CryptographicProvider\u0027.\r\nOnly required when using Extensible Key Management (EKM) scenarios with third-party cryptographic providers.", "", false, "false", "", "" ], [ "Force", "Drops and recreates the credential if it already exists on the target instance.\r\nUse this when you need to update an existing credential\u0027s identity or password, as SQL Server credentials cannot be modified once 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": [ "General", "Error" ], "CommandName": "New-DbaCustomError", "Name": "New-DbaCustomError", "Author": "Adam Lancaster, github.com/lancasteradam", "Syntax": "New-DbaCustomError [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-MessageID] \u003cInt32\u003e] [[-Severity] \u003cInt32\u003e] [[-MessageText] \u003cString\u003e] [[-Language] \u003cString\u003e] [-WithLog] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.UserDefinedMessage\nReturns the newly created UserDefinedMessage object from the target SQL Server instance. One object is returned per custom error message created.\nProperties:\r\n- ID (int) - The unique message identifier (50001-2147483647)\r\n- Language (string) - The language of the message (English, French, etc.)\r\n- Severity (int) - The severity level of the message (1-25)\r\n- Text (string) - The error message text (up to 255 characters)\r\n- IsLogged (bool) - Boolean indicating if the message is logged to Windows Application Log and SQL Server Error Log\r\n- CreateDate (datetime) - DateTime when the message was created\nAll properties from the base SMO UserDefinedMessage object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaCustomError -SqlInstance sqldev01, sqldev02 -MessageID 70001 -Severity 16 -MessageText \"test\"\nCreates a new custom message on the sqldev01 and sqldev02 instances with ID 70001, severity 16, and text \"test\".\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaCustomError -SqlInstance sqldev01 -MessageID 70001 -Severity 16 -MessageText \"test\" -Language \"French\"\nCreates a new custom message on the sqldev01 instance for the french language with ID 70001, severity 16, and text \"test\".\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eNew-DbaCustomError -SqlInstance sqldev01 -MessageID 70001 -Severity 16 -MessageText \"test\" -WithLog\nCreates a new custom message on the sqldev01 instance with ID 70001, severity 16, text \"test\", and enables the log mechanism.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$server = Connect-DbaInstance sqldev01\nPS C:\\\u003e $newMessage = New-DbaCustomError -SqlInstance $server -MessageID 70000 -Severity 16 -MessageText \"test_70000\"\nCreates a new custom message on the sqldev01 instance with ID 70000, severity 16, and text \"test_70000\"\nTo modify the custom message at a later time the following can be done to change the severity from 16 to 20:\nPS C:\\\u003e $original = $server.UserDefinedMessages | Where-Object ID -eq 70000\r\nPS C:\\\u003e $messageID = $original.ID\r\nPS C:\\\u003e $severity = 20\r\nPS C:\\\u003e $text = $original.Text\r\nPS C:\\\u003e $language = $original.Language\r\nPS C:\\\u003e $removed = Remove-DbaCustomError -SqlInstance $server -MessageID 70000\r\nPS C:\\\u003e $alteredMessage = New-DbaCustomError -SqlInstance $server -MessageID $messageID -Severity $severity -MessageText $text -Language $language -WithLog\nThe resulting updated message object is available in $alteredMessage.", "Description": "Creates custom error messages in SQL Server\u0027s sys.messages table using sp_addmessage, enabling standardized error handling across applications and stored procedures. This replaces the need to manually execute sp_addmessage for each custom message you want to define.\n\nCustom error messages are essential for application development and database maintenance workflows where you need consistent, meaningful error reporting. Instead of generic SQL Server errors, you can define specific messages like \"Customer record not found\" or \"Data validation failed for field X\" that make troubleshooting much easier for both developers and DBAs.\n\nYou can assign custom message IDs between 50001 and 2147483647, set severity levels from 1-25, and optionally enable logging to both the Windows Application Log and SQL Server Error Log. The function supports multiple languages and can create messages across multiple SQL Server instances simultaneously.\n\nNote: When adding non-English messages, the U.S. English version must be created first with the same severity level. This command does not support Azure SQL Database.", "Links": "https://dbatools.io/New-DbaCustomError", "Synopsis": "Creates custom error messages in SQL Server\u0027s sys.messages table for standardized application and stored procedure error handling", "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).\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", "", "" ], [ "MessageID", "Specifies the unique identifier for the custom error message, ranging from 50001 to 2147483647. Choose an ID that doesn\u0027t conflict with existing custom messages in your environment.\r\nUse sequential numbering for organization, such as 60000-60999 for application errors and 61000-61999 for stored procedure validation errors.", "", false, "false", "0", "" ], [ "Severity", "Sets the severity level from 1 to 25, which determines how SQL Server handles the error when raised. Levels 1-10 are informational, 11-16 are user errors that can be corrected, 17-19 are non-fatal \r\nresource errors, and 20-25 are fatal system errors.\r\nMost custom application errors use severity 16, while validation errors often use 11-15 depending on whether the application should continue processing.", "", false, "false", "0", "" ], [ "MessageText", "Defines the error message text displayed when the custom error is raised, with a maximum length of 255 characters. Use clear, actionable language that helps developers and users understand what went \r\nwrong.\r\nInclude parameter placeholders using printf-style formatting (like %s, %d) when the message needs dynamic values at runtime.", "", false, "false", "", "" ], [ "Language", "Specifies the language for the error message using values from sys.syslanguages (Name or Alias columns). Defaults to \u0027English\u0027 if not specified.\r\nCreate the U.S. English version first before adding other languages, as SQL Server requires the English version to exist with the same severity level before non-English versions can be added.", "", false, "false", "English", "" ], [ "WithLog", "Enables automatic logging of this error message to both the Windows Application Log and SQL Server Error Log whenever the error is raised.\r\nUse this for critical errors that require audit trails or monitoring alerts, but avoid for frequently occurring validation errors to prevent log flooding.", "", 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": [ "Deployment", "Dacpac" ], "CommandName": "New-DbaDacOption", "Name": "New-DbaDacOption", "Author": "Kirill Kravtsov (@nvarscar), nvarscar.wordpress.com", "Syntax": "New-DbaDacOption [[-Type] \u003cString\u003e] [-Action] \u003cString\u003e [[-PublishXml] \u003cString\u003e] [[-Property] \u003cHashtable\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Dac.DacExtractOptions (when Type=Dacpac and Action=Export)\nReturns a DacExtractOptions object for extracting schema and data from a database into a DAC package.\r\nProperties include ExtractAllTableData (boolean), CommandTimeout (int), and other extraction settings.\nMicrosoft.SqlServer.Dac.DacExportOptions (when Type=Bacpac and Action=Export)\nReturns a DacExportOptions object for exporting data only (without schema) from a database into a BAC package.\r\nProperties include CommandTimeout (int) and other export-specific settings.\nMicrosoft.SqlServer.Dac.PublishOptions (when Type=Dacpac and Action=Publish)\nReturns a PublishOptions object for publishing (deploying) a DAC package to a target database.\r\nContains a DeployOptions property (Microsoft.SqlServer.Dac.DacDeployOptions) with settings like DropObjectsNotInSource (boolean) and BlockOnPossibleDataLoss (boolean).\r\nWhen a PublishXml profile is provided, DeployOptions are loaded from the profile file; otherwise DeployOptions can be set via the Property parameter.\r\nThe GenerateDeploymentScript property (boolean) is initialized based on the Property parameter or defaults to false.\nMicrosoft.SqlServer.Dac.DacImportOptions (when Type=Bacpac and Action=Publish)\nReturns a DacImportOptions object for importing (deploying) a BAC package data into a target database.\r\nProperties include CommandTimeout (int) and other import-specific settings.\nAll returned objects can be configured by setting their properties directly or by passing a Property hashtable at creation time. When using PublishOptions with a PublishXml profile, the profile\u0027s \r\nsettings override Property parameter values.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\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 -Options $options\nUses DacOption object to set the CommandTimeout to 0 then extracts the dacpac for SharePoint_Config on sql2016 to C:\\temp\\SharePoint_Config.dacpac including all table data.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$options = New-DbaDacOption -Type Dacpac -Action Export -Property @{ExtractAllTableData=$true;CommandTimeout=0}\nPS C:\\\u003e Export-DbaDacPackage -SqlInstance sql2016 -Database DB1 -Options $options\nCreates a pre-initialized DacOption object and uses it to extrac a DacPac from the database.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$options = New-DbaDacOption -Type Dacpac -Action Publish\nPS C:\\\u003e $options.DeployOptions.DropObjectsNotInSource = $true\r\nPS C:\\\u003e Publish-DbaDacPackage -SqlInstance sql2016 -Database DB1 -Options $options -Path c:\\temp\\db.dacpac\nUses DacOption object to set Deployment Options and publish the db.dacpac dacpac file as DB1 on sql2016", "Description": "Creates a new Microsoft.SqlServer.Dac.DacExtractOptions/DacExportOptions object that can be used during DacPackage extract. Basically saves you the time from remembering the SMO assembly name ;)\n\nSee:\nhttps://msdn.microsoft.com/en-us/library/microsoft.sqlserver.dac.dacexportoptions.aspx\nhttps://msdn.microsoft.com/en-us/library/microsoft.sqlserver.dac.dacextractoptions.aspx\nfor more information", "Links": "https://dbatools.io/New-DbaDacOption", "Synopsis": "Creates a new Microsoft.SqlServer.Dac.DacExtractOptions/DacExportOptions object depending on the chosen Type", "Availability": "Windows, Linux, macOS", "Params": [ [ "Type", "Specifies the package type to create: Dacpac (schema and data) or Bacpac (data only). Defaults to Dacpac.\r\nUse Dacpac when you need to capture database schema structure along with optional data for deployment scenarios.\r\nUse Bacpac when you only need to export and import data without schema changes.", "", false, "false", "Dacpac", "Dacpac,Bacpac" ], [ "Action", "Determines whether you\u0027re exporting from a database or publishing to a database.\r\nUse Export when extracting a package from an existing database for backup or migration purposes.\r\nUse Publish when deploying a package to create or update a target database.", "", true, "false", "", "Publish,Export" ], [ "PublishXml", "Path to a DAC publish profile XML file that contains deployment options and SQLCMD variables.\r\nThese profiles are typically created in SQL Server Data Tools (SSDT) and control how the deployment behaves.\r\nWhen specified, the profile\u0027s settings override any DeployOptions specified in the Property parameter.", "", false, "false", "", "" ], [ "Property", "Hashtable of properties to configure the DAC options object, such as CommandTimeout or ExtractAllTableData.\r\nFor Publish actions, use the DeployOptions key to set deployment behaviors like DropObjectsNotInSource or BlockOnPossibleDataLoss.\r\nCommon properties include CommandTimeout for long operations and ExtractAllTableData when exporting data with schema.\r\nExample: @{CommandTimeout=0; DeployOptions=@{DropObjectsNotInSource=$true}}", "", 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": [ "Dacpac", "Deployment" ], "CommandName": "New-DbaDacPackage", "Name": "New-DbaDacPackage", "Author": "the dbatools team + Claude", "Syntax": "New-DbaDacPackage [-Path] \u003cString\u003e [[-OutputPath] \u003cString\u003e] [[-DacVersion] \u003cVersion\u003e] [[-DacDescription] \u003cString\u003e] [[-DatabaseName] \u003cString\u003e] [-Recursive] [[-SqlServerVersion] \u003cString\u003e] [[-Filter] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one result object per DACPAC build operation.\nOn successful build:\r\n- ComputerName: The local computer name where the DACPAC was built\r\n- Path: Full file path to the created DACPAC file\r\n- Database: The database name embedded in the DACPAC package metadata\r\n- DatabaseName: Database name (same as Database property)\r\n- Version: Version string in semantic version format (e.g., \"1.0.0.0\")\r\n- FileCount: Number of SQL files processed into the DACPAC\r\n- ObjectCount: Number of database objects in the compiled model\r\n- Duration: Elapsed time for the build operation (prettytimespan object, displays as human-readable duration)\r\n- Success: Boolean True indicating successful DACPAC creation\r\n- Errors: Array of error messages encountered (empty array on success)\r\n- Warnings: Array of warning messages from validation (empty array if no warnings)\nDefault display properties (via Select-DefaultView):\r\n- Path: File path to the DACPAC\r\n- DatabaseName: Database name\r\n- Version: Package version\r\n- FileCount: SQL files processed\r\n- ObjectCount: Database objects compiled\r\n- Duration: Build time elapsed\r\n- Success: Build status\nOn build failure (when validation errors prevent DACPAC creation):\r\n- DacpacPath: Null (DACPAC was not created)\r\n- DatabaseName: Database name\r\n- Version: Version string\r\n- FileCount: Number of files attempted\r\n- ObjectCount: Object count at time of failure\r\n- Duration: Elapsed time before failure\r\n- Success: Boolean False\r\n- Errors: Array of validation and processing errors preventing build\r\n- Warnings: Array of warnings encountered before failure\nAll objects are returned as PSCustomObject with properties accessible via dot notation or Select-Object.\r\nThe output is pipeline-compatible with Publish-DbaDacPackage for automated deployment workflows.\nPSCustomObject\nReturns one result object per DACPAC build operation.\nOn successful build:\r\n- ComputerName: The local computer name where the DACPAC was built\r\n- Path: Full file path to the created DACPAC file\r\n- Database: The database name embedded in the DACPAC package metadata\r\n- DatabaseName: Database name (same as Database property)\r\n- Version: Version string in semantic version format (e.g., \"1.0.0.0\")\r\n- FileCount: Number of SQL files processed into the DACPAC\r\n- ObjectCount: Number of database objects in the compiled model\r\n- Duration: Elapsed time for the build operation (prettytimespan object, displays as human-readable duration)\r\n- Success: Boolean True indicating successful DACPAC creation\r\n- Errors: Array of error messages encountered (empty array on success)\r\n- Warnings: Array of warning messages from validation (empty array if no warnings)\nDefault display properties (via Select-DefaultView):\r\n- Path: File path to the DACPAC\r\n- DatabaseName: Database name\r\n- Version: Package version\r\n- FileCount: SQL files processed\r\n- ObjectCount: Database objects compiled\r\n- Duration: Build time elapsed\r\n- Success: Build status\nOn build failure (when validation errors prevent DACPAC creation):\r\n- DacpacPath: Null (DACPAC was not created)\r\n- DatabaseName: Database name\r\n- Version: Version string\r\n- FileCount: Number of files attempted\r\n- ObjectCount: Object count at time of failure\r\n- Duration: Elapsed time before failure\r\n- Success: Boolean False\r\n- Errors: Array of validation and processing errors preventing build\r\n- Warnings: Array of warnings encountered before failure\nAll objects are returned as PSCustomObject with properties accessible via dot notation or Select-Object.\r\nThe output is pipeline-compatible with Publish-DbaDacPackage for automated deployment workflows.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaDacPackage -Path C:\\Projects\\MyDatabase\\Schema -OutputPath C:\\Build\\MyDatabase.dacpac\nCreates a DACPAC from all SQL files in C:\\Projects\\MyDatabase\\Schema and saves it to C:\\Build\\MyDatabase.dacpac.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaDacPackage -Path C:\\Projects\\MyDatabase\\Schema -Recursive -DatabaseName \"MyAppDB\" -DacVersion \"2.1.0.0\"\nCreates a DACPAC from all SQL files in the Schema directory and subdirectories, setting the database name to \"MyAppDB\" and version to \"2.1.0.0\".\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eNew-DbaDacPackage -Path C:\\Projects\\MyDatabase -Recursive | Publish-DbaDacPackage -SqlInstance sql2019 -Database TestDeploy\nCreates a DACPAC from source files and immediately deploys it to the TestDeploy database on sql2019.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eNew-DbaDacPackage -Path C:\\Projects\\MyDatabase\\Schema -SqlServerVersion Sql140 -Recursive\nCreates a DACPAC targeting SQL Server 2017 compatibility, useful when deploying to older SQL Server versions.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eNew-DbaDacPackage -Path C:\\Projects\\MyDatabase -Filter \"*Table*.sql\" -Recursive\nCreates a DACPAC including only SQL files with \"Table\" in their filename.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e$result = New-DbaDacPackage -Path .\\sql\\Schema -Recursive -DatabaseName \"dbatoolspro\" -DacVersion \"1.0.0\"\nPS C:\\\u003e $result | Format-List\nCreates a DACPAC and displays detailed results including object count, duration, and any errors or warnings.", "Description": "Creates a DACPAC (Data-tier Application Package) from SQL source files without requiring MSBuild, Visual Studio, or the .NET SDK. Uses the Microsoft.SqlServer.Dac.Model.TSqlModel API to parse SQL files, validate the model, and generate a deployable DACPAC package.\n\nThis command enables a pure PowerShell-based build workflow for database projects, making it ideal for CI/CD pipelines, development environments without Visual Studio, and cross-platform scenarios (Windows, Linux, macOS).\n\nThe DACPAC output can be deployed using Publish-DbaDacPackage, enabling idempotent schema deployments with automatic dependency ordering and drift detection.", "Links": "https://dbatools.io/New-DbaDacPackage", "Synopsis": "Creates a DACPAC package from SQL source files using the DacFx framework", "Availability": "Windows, Linux, macOS", "Params": [ [ "Path", "Specifies the directory containing SQL files to include in the DACPAC. All .sql files in the directory will be processed. Use -Recursive to include subdirectories.\r\nAlternatively, specify a path to a .sqlproj file to parse project settings and file references from the project definition.", "", true, "false", "", "" ], [ "OutputPath", "Specifies the output path for the generated DACPAC file. Defaults to a file named after the DatabaseName in the current directory with .dacpac extension.\r\nExample: If DatabaseName is \"MyDatabase\", the default output would be \".\\MyDatabase.dacpac\"", "", false, "false", "", "" ], [ "DacVersion", "Specifies the version number for the DACPAC package metadata. Defaults to \"1.0.0.0\".\r\nUse semantic versioning aligned with your build or release process.", "", false, "false", "1.0.0.0", "" ], [ "DacDescription", "Specifies an optional description to embed in the DACPAC package metadata.\r\nUse this to document the package purpose or build context.", "", false, "false", "", "" ], [ "DatabaseName", "Specifies the database name for the DACPAC package metadata. Defaults to the name of the Path directory or current directory.\r\nThis name is used when deploying the DACPAC if no target database name is specified.", "", false, "false", "", "" ], [ "Recursive", "Includes SQL files from subdirectories when Path is a directory.\r\nUse this to process hierarchical folder structures like Schema\\Tables\\, Schema\\Views\\, etc.", "", false, "false", "False", "" ], [ "SqlServerVersion", "Specifies the target SQL Server version for model validation and compatibility checking.\r\nValid values: Sql90 (2005), Sql100 (2008), Sql110 (2012), Sql120 (2014), Sql130 (2016), Sql140 (2017), Sql150 (2019), Sql160 (2022), SqlAzure.\r\nDefaults to Sql160 (SQL Server 2022).", "", false, "false", "Sql160", "Sql90,Sql100,Sql110,Sql120,Sql130,Sql140,Sql150,Sql160,SqlAzure" ], [ "Filter", "Specifies a wildcard pattern to filter which SQL files to include. Defaults to \"*.sql\".\r\nUse this to include only specific file patterns like \"*Table*.sql\" or \"Schema_*.sql\".", "", false, "false", "*.sql", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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 operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Deployment", "Dacpac" ], "CommandName": "New-DbaDacProfile", "Name": "New-DbaDacProfile", "Author": "Richie lee (@richiebzzzt)", "Syntax": "New-DbaDacProfile [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [-Database] \u003cString[]\u003e [[-Path] \u003cString\u003e] [[-ConnectionString] \u003cString[]\u003e] [[-PublishOptions] \u003cHashtable\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one result object per database specified when generating a publish profile. Objects combine connection context and profile metadata.\nProperties:\r\n- ComputerName: Computer name extracted from the DbaInstance object (derived from connection string)\r\n- InstanceName: Instance name extracted from the DbaInstance object (derived from connection string)\r\n- SqlInstance: Full SQL Server instance name in format \"ComputerName\\InstanceName\" (from DbaInstance.FullName)\r\n- Database: Target database name for which the profile was generated\r\n- FileName: Full file path to the generated XML publish profile (e.g., \"C:\\temp\\sql2017-WorldWideImporters-publish.xml\")\r\n- ConnectionString: The connection string embedded in the profile (e.g., \"Server=sql2017;Integrated Security=True;Encrypt=False\")\r\n- ProfileTemplate: Complete XML content of the publish profile (excluded from default display via Select-DefaultView)\nDefault display properties (via Select-DefaultView):\r\n- SqlInstance: SQL Server instance name\r\n- Database: Target database\r\n- FileName: Profile file path\r\n- ConnectionString: Connection string\nOutput Quantity:\r\nReturns one object per database specified in the -Database parameter for each connection string. For example:\r\n- Specifying one database with one connection string returns 1 object\r\n- Specifying multiple databases (DB1, DB2) with one connection string returns 2 objects\r\n- Specifying multiple databases with multiple connection strings returns (databases count × connection strings count) objects\nThe ProfileTemplate property contains the XML used for SqlPackage.exe deployments. This property is excluded from default display but accessible via Select-Object or property access.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaDacProfile -SqlInstance sql2017 -SqlCredential ad\\sqldba -Database WorldWideImporters -Path C:\\temp\nIn this example, a prompt will appear for alternative credentials, then a connection will be made to sql2017. Using that connection,\r\nthe ConnectionString will be extracted and used within the Publish Profile XML file which will be created at C:\\temp\\sql2017-WorldWideImporters-publish.xml\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaDacProfile -Database WorldWideImporters -Path C:\\temp -ConnectionString \"SERVER=(localdb)\\MSSQLLocalDB;Integrated Security=True;Database=master\"\nIn this example, no connections are made, and a Publish Profile XML would be created at C:\\temp\\localdb-MSSQLLocalDB-WorldWideImporters-publish.xml", "Description": "The New-DbaDacProfile command generates standard publish profile XML files that control how DacFx deploys your dacpac files to SQL Server databases. These profile files define deployment settings like target database, connection details, and deployment options.\n\nThe generated XML template includes basic deployment settings sufficient for most dacpac deployments, but you\u0027ll typically want to add additional deployment options to the publish profile for production scenarios.\n\nIf you use Visual Studio with SSDT projects, you can enhance these profiles through the UI. Right-click on an SSDT project, choose \"Publish\", then \"Load Profile\" to load your generated profile. The Advanced button reveals the full list of available deployment options.\n\nFor automation scenarios, these profiles work directly with SqlPackage.exe command-line deployments, eliminating the need to specify connection and deployment settings manually each time.\n\nFor a complete list of deployment options you can add to profiles, search for \"SqlPackage.exe command line switches\" or visit https://msdn.microsoft.com/en-us/library/hh550080(v=vs.103).aspx", "Links": "https://dbatools.io/New-DbaDacProfile", "Synopsis": "Creates DAC publish profile XML files for automated dacpac deployment to SQL Server databases.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. Alternatively, you can provide a ConnectionString.", "", 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 the target database name where the dacpac will be deployed. This sets the TargetDatabaseName property in the generated publish profile.\r\nUse this to define which database will receive the dacpac deployment when the profile is used with SqlPackage.exe or Visual Studio publishing.", "", true, "false", "", "" ], [ "Path", "Specifies the directory where the publish profile XML files will be created. Defaults to your Documents folder if not specified.\r\nFiles are automatically named using the pattern \"instancename-databasename-publish.xml\" for easy identification and organization.", "", false, "false", "\"$home\\Documents\"", "" ], [ "ConnectionString", "Provides a direct connection string for the target SQL Server instance and database. This becomes the TargetConnectionString in the generated publish profile.\r\nUse this instead of SqlInstance when you need specific connection parameters, are connecting to non-standard instances like LocalDB, or when working in environments where Connect-DbaInstance may have \r\nlimitations.\r\nIf you provide SqlInstance, the function will connect and generate the connection string automatically.", "", false, "false", "", "" ], [ "PublishOptions", "Specifies additional deployment options as a hashtable that will be embedded in the publish profile XML. Each key/value pair becomes a PropertyGroup element in the profile.\r\nUse this to control dacpac deployment behavior like blocking data loss (BlockOnPossibleDataLoss), ignoring permissions (IgnorePermissions), or script generation options.\r\nCommon options include IgnoreUserSettingsObjects, GenerateDeploymentScript, and CreateNewDatabase. See SqlPackage.exe documentation for complete option list.", "", 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": "Database", "CommandName": "New-DbaDatabase", "Name": "New-DbaDatabase", "Author": "Matthew Darwin (@evoDBA, naturalselectiondba.wordpress.com) | Chrissy LeMaire (@cl)", "Syntax": "New-DbaDatabase [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Name] \u003cString[]\u003e] [[-Collation] \u003cString\u003e] [[-RecoveryModel] \u003cString\u003e] [[-Owner] \u003cString\u003e] [[-DataFilePath] \u003cString\u003e] [[-LogFilePath] \u003cString\u003e] [[-PrimaryFilesize] \u003cInt32\u003e] [[-PrimaryFileGrowth] \u003cInt32\u003e] [[-PrimaryFileMaxSize] \u003cInt32\u003e] [[-LogSize] \u003cInt32\u003e] [[-LogGrowth] \u003cInt32\u003e] [[-LogMaxSize] \u003cInt32\u003e] [[-SecondaryFilesize] \u003cInt32\u003e] [[-SecondaryFileGrowth] \u003cInt32\u003e] [[-SecondaryFileMaxSize] \u003cInt32\u003e] [[-SecondaryFileCount] \u003cInt32\u003e] [[-DefaultFileGroup] \u003cString\u003e] [[-DataFileSuffix] \u003cString\u003e] \r\n[[-LogFileSuffix] \u003cString\u003e] [[-SecondaryDataFileSuffix] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Database\nReturns one Database object for each database successfully created on the target 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- Name: Name of the newly created database\r\n- Status: Current database status (Normal for a new database)\r\n- IsAccessible: Boolean indicating if the database is currently accessible\r\n- RecoveryModel: Database recovery model (Simple, Full, or BulkLogged as specified)\r\n- LogReuseWaitStatus: Status of transaction log reuse\r\n- Size: Database size in megabytes (MB)\r\n- Compatibility: Database compatibility level\r\n- Collation: Database collation setting (as specified)\r\n- Owner: Database owner login name (as specified)\r\n- Encrypted: Boolean indicating if Transparent Data Encryption is enabled\r\n- LastFullBackup: DateTime of last full backup (null for new database)\r\n- LastDiffBackup: DateTime of last differential backup (null for new database)\r\n- LastLogBackup: DateTime of last transaction log backup (null for new database)\nAdditional properties available via Select-Object * from the SMO Database object include all standard database properties such as MirroringPartner, MirroringRole, PrimaryFilePath, and others \r\ndocumented in the SQL Server Management Objects (SMO) reference.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaDatabase -SqlInstance sql1\nCreates a randomly named database (random-N) on instance sql1\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaDatabase -SqlInstance sql1 -Name dbatools, dbachecks\nCreates a database named dbatools and a database named dbachecks on sql1\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eNew-DbaDatabase -SqlInstance sql1, sql2, sql3 -Name multidb, multidb2 -SecondaryFilesize 20 -SecondaryFileGrowth 20 -LogSize 20 -LogGrowth 20\nCreates two databases, multidb and multidb2, on 3 instances (sql1, sql2 and sql3) and sets the secondary data file size to 20MB, the file growth to 20MB and the log growth to 20MB for each\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eNew-DbaDatabase -SqlInstance sql1 -Name nondefault -DataFilePath M:\\Data -LogFilePath \u0027L:\\Logs with spaces\u0027 -SecondaryFileCount 2\nCreates a database named nondefault and places data files in in the M:\\data directory and log files in \"L:\\Logs with spaces\".\nCreates a secondary group with 2 files in the Secondary filegroup.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$databaseParams = @{\n\u003e\u003e SqlInstance = \"sql1\"\r\n\u003e\u003e Name = \"newDb\"\r\n\u003e\u003e LogSize = 32\r\n\u003e\u003e LogMaxSize = 512\r\n\u003e\u003e PrimaryFilesize = 64\r\n\u003e\u003e PrimaryFileMaxSize = 512\r\n\u003e\u003e SecondaryFilesize = 64\r\n\u003e\u003e SecondaryFileMaxSize = 512\r\n\u003e\u003e LogGrowth = 32\r\n\u003e\u003e PrimaryFileGrowth = 64\r\n\u003e\u003e SecondaryFileGrowth = 64\r\n\u003e\u003e DataFileSuffix = \"_PRIMARY\"\r\n\u003e\u003e LogFileSuffix = \"_Log\"\r\n\u003e\u003e SecondaryDataFileSuffix = \"_MainData\"\r\n\u003e\u003e }\r\n\u003e\u003e New-DbaDatabase @databaseParams\nCreates a new database named newDb on the sql1 instance and sets the file sizes, max sizes, and growth as specified. The resulting filenames will take the form:\nnewDb_PRIMARY\r\nnewDb_Log\r\nnewDb_MainData_1 (Secondary filegroup files)", "Description": "Creates new databases on SQL Server instances with full control over file placement, sizing, and growth settings. Rather than using T-SQL CREATE DATABASE statements manually, this function provides a structured approach to database creation with built-in best practices.\n\nThe function automatically configures growth settings to use fixed MB increments instead of percentage-based growth, which prevents runaway autogrowth issues in production environments. When specific file sizes aren\u0027t provided, it inherits sensible defaults from the model database to ensure new databases start with appropriate baseline configurations.\n\nSupports creating databases with secondary filegroups and multiple data files for performance optimization, making it useful for both simple development databases and complex production systems that require specific file layouts for optimal I/O distribution.", "Links": "https://dbatools.io/New-DbaDatabase", "Synopsis": "Creates new SQL Server databases with customizable file layout and growth settings", "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", "", "" ], [ "Name", "Specifies the name of the database(s) to create on the SQL Server instance. Accepts multiple database names as an array to create several databases in a single operation. If not provided, creates a \r\ndatabase with a randomly generated name like \"random-12345\".", "Database", false, "false", "", "" ], [ "Collation", "Specifies the collation for the new database, which determines sorting rules, case sensitivity, and accent sensitivity for string data. Use this when creating databases that need specific language or \r\ncultural sorting requirements different from the server default. If not specified, inherits the server\u0027s default collation.", "", false, "false", "", "" ], [ "RecoveryModel", "Sets the recovery model which determines how transaction log backups work and how much data loss is acceptable. Simple recovery model doesn\u0027t require log backups but limits point-in-time recovery, \r\nFull enables complete point-in-time recovery with log backups, BulkLogged offers a compromise for bulk operations. If not specified, inherits from the model database.", "", false, "false", "", "Simple,Full,BulkLogged" ], [ "Owner", "Specifies which SQL Server login will be assigned as the database owner (dbo). Use this to assign ownership to a specific service account or administrator instead of the default creator. The login \r\nmust already exist on the SQL Server instance. If not specified, the connecting user becomes the database owner.", "", false, "false", "", "" ], [ "DataFilePath", "Specifies the directory path where database data files (.mdf and .ndf) will be created. Use this when you need to place database files on specific drives for performance or storage management. If not \r\nspecified, uses the SQL Server instance\u0027s default data directory. The function will create the directory if it doesn\u0027t exist.", "", false, "false", "", "" ], [ "LogFilePath", "Specifies the directory path where transaction log files (.ldf) will be created. Best practice is to place log files on separate drives from data files for performance and availability. If not \r\nspecified, uses the SQL Server instance\u0027s default log directory. The function will create the directory if it doesn\u0027t exist.", "", false, "false", "", "" ], [ "PrimaryFilesize", "Sets the initial size in MB for the primary data file (.mdf). Use this to create databases with appropriate initial sizing based on expected data volume to reduce autogrowth events. If the specified \r\nsize is smaller than the model database\u0027s primary file, the model size is used instead to maintain minimum requirements.", "", false, "false", "0", "" ], [ "PrimaryFileGrowth", "Specifies the autogrowth increment in MB for the primary data file when it needs more space. Using fixed MB increments prevents runaway percentage-based growth that can cause performance issues and \r\ndisk space problems in production environments. If not specified, inherits the model database\u0027s growth settings.", "", false, "false", "0", "" ], [ "PrimaryFileMaxSize", "Sets the maximum size limit in MB that the primary data file can grow to during autogrowth events. Use this to prevent database files from consuming all available disk space in case of runaway \r\nprocesses or data imports. If set smaller than the initial file size, the initial size becomes the maximum.", "", false, "false", "0", "" ], [ "LogSize", "Sets the initial size in MB for the transaction log file (.ldf). Proper log sizing prevents frequent autogrowth during normal operations which can impact performance. Size the log based on your \r\ntransaction volume and backup frequency - larger logs for high-activity databases or infrequent log backups. If not specified, uses the model database\u0027s log size.", "", false, "false", "0", "" ], [ "LogGrowth", "Specifies the autogrowth increment in MB for the transaction log file when additional space is needed. Fixed MB growth prevents percentage-based growth that can cause performance delays during \r\nhigh-activity periods. Consider setting this to handle your typical transaction volume between log backups. If not specified, uses the model database\u0027s growth settings.", "", false, "false", "0", "" ], [ "LogMaxSize", "Sets the maximum size limit in MB for the transaction log file during autogrowth. This prevents transaction logs from consuming all disk space during bulk operations or when log backups are delayed. \r\nConsider your available disk space and typical maintenance windows when setting this limit. If set smaller than the initial log size, the initial size becomes the maximum.", "", false, "false", "0", "" ], [ "SecondaryFilesize", "Sets the initial size in MB for each file in the secondary filegroup. All secondary files will be created with this same size. Use this to establish consistent file sizes across the filegroup for \r\nbalanced I/O distribution. If not specified and secondary files are created, uses the model database\u0027s file size.", "", false, "false", "0", "" ], [ "SecondaryFileGrowth", "Specifies the autogrowth increment in MB for each secondary data file when additional space is needed. All secondary files will use the same growth increment to maintain balanced file sizes. Set to 0 \r\nto disable autogrowth for controlled file management. Fixed MB increments provide predictable growth behavior.", "", false, "false", "0", "" ], [ "SecondaryFileMaxSize", "Sets the maximum size limit in MB for each secondary data file during autogrowth. This prevents individual files from consuming excessive disk space while allowing controlled growth. All secondary \r\nfiles will use this same maximum size limit to maintain consistency across the filegroup.", "", false, "false", "0", "" ], [ "SecondaryFileCount", "Specifies how many data files to create in the secondary filegroup. Multiple files allow parallel I/O operations which can improve performance for large databases with high activity. Consider your \r\nstorage configuration and available CPU cores when determining the file count - typically one file per CPU core up to the number of available drives.", "", false, "false", "0", "" ], [ "DefaultFileGroup", "Specifies which filegroup becomes the default for new tables and indexes when no filegroup is explicitly specified. Primary uses the standard PRIMARY filegroup, Secondary uses the created secondary \r\nfilegroup. Setting the secondary filegroup as default directs new objects to use the optimized multi-file configuration for better performance.", "", false, "false", "", "Primary,Secondary" ], [ "DataFileSuffix", "Specifies a custom suffix to append to the primary data file name. The full filename becomes DatabaseName + DataFileSuffix + .mdf. Use this to follow organizational naming conventions or to \r\ndifferentiate between environments (like \"_PROD\" or \"_DEV\"). If not specified, no suffix is added.", "", false, "false", "", "" ], [ "LogFileSuffix", "Specifies the suffix to append to the transaction log file name. The full filename becomes DatabaseName + LogFileSuffix + .ldf. Use this to follow naming conventions that distinguish log files from \r\ndata files. Defaults to \"_log\" if not specified, creating files like \"MyDatabase_log.ldf\".", "", false, "false", "_log", "" ], [ "SecondaryDataFileSuffix", "Specifies the suffix used for the secondary filegroup name and its data files. The filegroup becomes DatabaseName + SecondaryDataFileSuffix, and files are named like DatabaseName + \r\nSecondaryDataFileSuffix + \"_1.ndf\". Use descriptive suffixes like \"_Data\" or \"_Indexes\" to indicate the intended use of the secondary filegroup.", "", 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": [ "Certificate", "Security" ], "CommandName": "New-DbaDbAsymmetricKey", "Name": "New-DbaDbAsymmetricKey", "Author": "Stuart Moore (@napalmgram), stuart-moore.com", "Syntax": "New-DbaDbAsymmetricKey [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Name] \u003cString[]\u003e] [[-Database] \u003cString[]\u003e] [[-SecurePassword] \u003cSecureString\u003e] [[-Owner] \u003cString\u003e] [[-KeySource] \u003cString\u003e] [[-KeySourceType] \u003cString\u003e] [[-InputObject] \u003cDatabase[]\u003e] [[-Algorithm] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.AsymmetricKey\nReturns one AsymmetricKey object for each asymmetric key successfully created in the target database(s).\nDisplay 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 asymmetric key\r\n- Name: The name of the asymmetric key\r\n- Owner: The database user who owns the key\r\n- KeyEncryptionAlgorithm: The RSA algorithm used (Rsa512, Rsa1024, Rsa2048, Rsa3072, or Rsa4096)\r\n- KeyLength: The key length in bits (512, 1024, 2048, 3072, or 4096)\r\n- PrivateKeyEncryptionType: How the private key is encrypted (Password, MasterKey, or None)\r\n- Thumbprint: The SHA-1 hash of the public key for identification\nAdditional properties available via Select-Object * from the SMO AsymmetricKey object include standard SMO object properties such as Parent (reference to the parent Database), Urn (Uniform Resource \r\nName), and State (current SMO object state).", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaDbAsymmetricKey -SqlInstance Server1\nYou will be prompted to securely enter your password, then an asymmetric key will be created in the master database on server1 if it does not exist.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaDbAsymmetricKey -SqlInstance Server1 -Database db1 -Confirm:$false\nSuppresses all prompts to install but prompts to securely enter your password and creates an asymmetric key in the \u0027db1\u0027 database\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eNew-DbaDbAsymmetricKey -SqlInstance Server1 -Database enctest -KeySourceType File -KeySource c:\\keys\\NewKey.snk -Name BackupKey -Owner KeyOwner\nInstalls the key pair held in NewKey.snk into the enctest database creating an AsymmetricKey called BackupKey, which will be owned by KeyOwner", "Description": "Creates asymmetric keys within SQL Server databases using RSA encryption algorithms (512-4096 bit). These keys are essential for database-level encryption features like Transparent Data Encryption (TDE), column-level encryption, and digital signing of assemblies or stored procedures. You can generate new key pairs directly on the server or import existing keys from files, executables, or assemblies. Keys can be password-protected or secured using the database master key, and ownership can be assigned to specific database users.", "Links": "https://dbatools.io/New-DbaDbAsymmetricKey", "Synopsis": "Creates RSA asymmetric keys in SQL Server databases for encryption and digital signing", "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 the name for the asymmetric key object within the database. Defaults to the database name if not provided.\r\nChoose meaningful names that reflect the key\u0027s purpose, such as \u0027TDE_Key\u0027 or \u0027BackupKey\u0027 for easier identification.", "", false, "false", "", "" ], [ "Database", "Specifies the target database where the asymmetric key will be created. Defaults to master database if not specified.\r\nUse this when creating encryption keys for specific user databases rather than system-wide keys.", "", false, "false", "master", "" ], [ "SecurePassword", "Provides a password to encrypt the asymmetric key\u0027s private key. If omitted, the database master key protects the private key.\r\nUse this when you need explicit password control or when the database master key is not available.", "Password", false, "false", "", "" ], [ "Owner", "Specifies the database user who will own the asymmetric key. Defaults to the current user if not specified.\r\nThe specified user must already exist in the target database before creating the key.", "", false, "false", "", "" ], [ "KeySource", "Specifies the path or name of the external key source (file, executable, or SQL assembly name).\r\nThe path must be accessible by the SQL Server service account when using File or Executable types.", "", false, "false", "", "" ], [ "KeySourceType", "Specifies the type of external key source when importing existing keys. Valid values are Executable, File, or SqlAssembly.\r\nRequired when using KeySource parameter to import keys from external files rather than generating new ones.", "", false, "false", "", "Executable,File,SqlAssembly" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase through the pipeline for batch key creation.\r\nUse this when creating asymmetric keys across multiple databases in a single operation.", "", false, "true (ByValue)", "", "" ], [ "Algorithm", "Sets the RSA encryption algorithm strength for newly generated keys. Valid options are Rsa512, Rsa1024, Rsa2048, Rsa3072, or Rsa4096.\r\nDefaults to Rsa2048 which provides good security for most scenarios. Higher bit strengths offer stronger encryption but slower performance.", "", false, "false", "Rsa2048", "Rsa4096,Rsa3072,Rsa2048,Rsa1024,Rsa512" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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": "New-DbaDbCertificate", "Name": "New-DbaDbCertificate", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "New-DbaDbCertificate [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Name] \u003cString[]\u003e] [[-Database] \u003cString[]\u003e] [[-Subject] \u003cString[]\u003e] [[-StartDate] \u003cDateTime\u003e] [[-ExpirationDate] \u003cDateTime\u003e] [-ActiveForServiceBrokerDialog] [[-SecurePassword] \u003cSecureString\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Certificate\nReturns one Certificate object for each certificate created in the specified database. The certificate object contains all the configuration properties defined during creation including expiration \r\ndates, encryption settings, and Service Broker dialog status.\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 certificate\r\n- Name: The name of the certificate\r\n- Subject: The subject field of the certificate for identification purposes\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, or MasterKey)\r\n- Serial: The serial number of the certificate\nAdditional properties available (from SMO Certificate object):\r\n- ID: The unique identifier for 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- Sid: The security identifier (SID) of the certificate owner\r\n- State: The current state of the SMO object (Existing, Creating, Pending, etc.)\nAll properties from the base SMO Certificate object are accessible using Select-Object * even though only default properties are displayed by default.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaDbCertificate -SqlInstance Server1\nYou will be prompted to securely enter your password, then a certificate will be created in the master database on server1 if it does not exist.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaDbCertificate -SqlInstance Server1 -Database db1 -Confirm:$false\nSuppresses all prompts to install but prompts to securely enter your password and creates a certificate in the \u0027db1\u0027 database", "Description": "Creates a new database certificate within a specified database using SQL Server Management Objects. Database certificates are essential for implementing Transparent Data Encryption (TDE), encrypting stored procedures and functions, securing Service Broker dialogs, and enabling column-level encryption. The certificate can be password-protected or secured by the database master key, with configurable expiration dates and subject information. If no database is specified, the certificate will be created in the master database.", "Links": "https://dbatools.io/New-DbaDbCertificate", "Synopsis": "Creates a new database certificate for encryption and security purposes", "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 the name for the certificate. Defaults to the database name if not provided.\r\nUse descriptive names that indicate the certificate\u0027s purpose, such as \u0027TDE_Certificate\u0027 or \u0027ColumnEncryption_Cert\u0027.", "", false, "false", "", "" ], [ "Database", "Specifies the database where the certificate will be created. Defaults to master if not specified.\r\nUse this when you need certificates in specific databases for TDE, column-level encryption, or Service Broker security.", "", false, "false", "master", "" ], [ "Subject", "Specifies the certificate subject field for identification purposes. Defaults to \u0027[DatabaseName] Database Certificate\u0027.\r\nUse meaningful subjects like \u0027CN=MyApp TDE Certificate\u0027 to help identify certificate purposes in production environments.", "", false, "false", "", "" ], [ "StartDate", "Specifies when the certificate becomes valid for use. Defaults to the current date and time.\r\nSet future start dates when you need to prepare certificates in advance for scheduled encryption implementations.", "", false, "false", "(Get-Date)", "" ], [ "ExpirationDate", "Specifies when the certificate expires and becomes invalid. Defaults to 5 years from the start date.\r\nPlan expiration dates carefully as expired certificates will prevent access to encrypted data and require certificate renewal procedures.", "", false, "false", "$StartDate.AddYears(5)", "" ], [ "ActiveForServiceBrokerDialog", "Enables the certificate for Service Broker dialog security and message encryption. Disabled by default.\r\nUse this when implementing Service Broker applications that require encrypted message communication between services.", "", false, "false", "False", "" ], [ "SecurePassword", "Specifies a password to encrypt the certificate\u0027s private key. If not provided, the database master key protects the certificate.\r\nUse passwords when you need to backup/restore certificates across instances or when the database master key is not available.", "Password", false, "false", "", "" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase for pipeline operations.\r\nUse this to create certificates across multiple databases efficiently by piping database objects 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", "" ], [ "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": [ "DataGeneration", "Database" ], "CommandName": "New-DbaDbDataGeneratorConfig", "Name": "New-DbaDbDataGeneratorConfig", "Author": "Sander Stad (@sqlstad, sqlstad.nl)", "Syntax": "New-DbaDbDataGeneratorConfig [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-Table] \u003cString[]\u003e] [-ResetIdentity] [-TruncateTable] [[-Rows] \u003cInt32\u003e] [-Path] \u003cString\u003e [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.IO.FileInfo\nReturns file information for each JSON configuration file that was successfully written to disk.\nProperties:\r\n- Name: The filename of the generated configuration file (format: servername.databasename.DataGeneratorConfig.json)\r\n- FullName: The complete file path where the configuration was saved\r\n- Length: The size of the JSON file in bytes\r\n- CreationTime: The datetime when the file was created\r\n- LastWriteTime: The datetime when the file was last written\r\n- DirectoryName: The directory path containing the configuration file\nThe output object allows you to verify which configuration files were created and their locations for use with Invoke-DbaDbDataGenerator.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaDbDataGeneratorConfig -SqlInstance SQLDB1 -Database DB1 -Path C:\\Temp\\clone\nProcess all tables and columns for database DB1 on instance SQLDB1\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaDbDataGeneratorConfig -SqlInstance SQLDB1 -Database DB1 -Table Customer -Path C:\\Temp\\clone\nProcess only table Customer with all the columns", "Description": "Analyzes database table structures and generates JSON configuration files that define how to populate each column with realistic fake data. The function examines column names, data types, constraints, and relationships to intelligently map appropriate data generation rules using the Bogus library. Column names matching common patterns (like \"Address\", \"Email\", \"Phone\") automatically get contextually appropriate fake data types, while other columns get sensible defaults based on their SQL data types.\n\nThese configuration files serve as the blueprint for Invoke-DbaDbDataGenerator, allowing DBAs to create development databases with realistic test data instead of using production data. Perfect for building demo environments, testing applications with meaningful datasets, or creating training databases that mirror production schemas but contain no sensitive information.\n\nThe function handles identity columns, foreign key relationships, unique indexes, and nullable constraints while skipping unsupported column types like computed columns, spatial data types, and XML. Configuration files are saved with the naming convention \"servername.databasename.DataGeneratorConfig.json\" for easy identification and reuse.\n\nRead more here:\nhttps://sachabarbs.wordpress.com/2018/06/11/bogus-simple-fake-data-tool/\nhttps://github.com/bchavez/Bogus", "Links": "https://dbatools.io/New-DbaDbDataGeneratorConfig", "Synopsis": "Creates JSON configuration files for generating realistic test data in SQL Server database tables", "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 analyze for data generation configuration creation. Accepts multiple database names.\r\nUse this when you need to create test data configs for specific databases instead of all databases on the instance.", "", false, "false", "", "" ], [ "Table", "Specifies which tables to include in the data generation configuration. Accepts multiple table names and supports wildcards.\r\nUse this when you only need test data for specific tables rather than analyzing the entire database schema.", "", false, "false", "", "" ], [ "ResetIdentity", "Controls whether identity columns should reset to their seed values when generating test data. When enabled, identity values start from the original seed.\r\nUse this when you need predictable, consistent identity values across test data generation runs instead of continuing from existing maximum values.", "", false, "false", "False", "" ], [ "TruncateTable", "Enables table truncation before inserting generated test data. When specified, existing data is removed before populating with fake data.\r\nUse this when you need clean test environments or want to replace all existing data rather than appending to current table contents.", "", false, "false", "False", "" ], [ "Rows", "Sets the number of test data rows to generate for each table in the configuration. Defaults to 1000 rows per table.\r\nAdjust this based on your testing needs - use smaller values for development environments or larger values for performance testing scenarios.", "", false, "false", "1000", "" ], [ "Path", "Specifies the directory where JSON configuration files will be saved. Files are named using the pattern \"servername.databasename.DataGeneratorConfig.json\".\r\nChoose a location accessible to your development team since these config files will be used by Invoke-DbaDbDataGenerator to create the actual test data.", "", true, "false", "", "" ], [ "Force", "Allows the function to create the specified Path directory if it doesn\u0027t exist. Without this switch, the function will fail if the target directory is missing.\r\nUse this when setting up new test data workflows where the output directory structure hasn\u0027t been established yet.", "", 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": "New-DbaDbEncryptionKey", "Name": "New-DbaDbEncryptionKey", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "New-DbaDbEncryptionKey [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-EncryptorName] \u003cString\u003e] [[-Type] \u003cString\u003e] [[-EncryptionAlgorithm] \u003cString\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.DatabaseEncryptionKey\nReturns one DatabaseEncryptionKey object per database where the encryption key was successfully created. If creation fails or is skipped (e.g., database already has an encryption key), no object is \r\nreturned 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:\\\u003e$dbs = Get-DbaDatabase -SqlInstance sql01 -Database pubs\nPS C:\\\u003e $db | New-DbaDbEncryptionKey\nCreates an Aes256 encryption key for the pubs database on sql01. Automatically selects a cert database in master if one (and only one) non-system certificate exists.\nPrompts for confirmation.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaDbEncryptionKey -SqlInstance sql01 -Database db1 -EncryptorName \"sql01 cert\" -EncryptionAlgorithm Aes192 -Confirm:$false\nCreates an Aes192 encryption key for the pubs database on sql01 using the certiciated named \"sql01 cert\" in master.\nDoes not prompt for confirmation.", "Description": "Creates database encryption keys (DEKs) required for Transparent Data Encryption, using certificates or asymmetric keys from the master database. This is the essential first step before enabling TDE on any database to encrypt data at rest. The function automatically validates that certificates have been backed up before creating encryption keys, preventing potential data loss scenarios. If no encryptor is specified, it will automatically select an appropriate certificate or asymmetric key from master database.", "Links": "https://dbatools.io/New-DbaDbEncryptionKey", "Synopsis": "Creates database encryption keys for Transparent Data Encryption (TDE)", "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 where the encryption key will be created to enable Transparent Data Encryption.\r\nThis is the user database you want to encrypt, not the master database where certificates are stored.", "", false, "false", "master", "" ], [ "EncryptorName", "Specifies the name of the certificate or asymmetric key in the master database to encrypt the database encryption key.\r\nIf not provided, the function automatically selects an appropriate certificate from master (requires exactly one non-system certificate to exist).\r\nFor asymmetric keys, the key must reside on an extensible key management provider like Azure Key Vault or Hardware Security Module.", "Certificate,CertificateName", false, "false", "", "" ], [ "Type", "Specifies whether to use a Certificate or AsymmetricKey from the master database as the encryptor.\r\nCertificates are more common for TDE implementations, while asymmetric keys are typically used with external key management providers.", "", false, "false", "Certificate", "Certificate,AsymmetricKey" ], [ "EncryptionAlgorithm", "Specifies the symmetric encryption algorithm used for the database encryption key.\r\nAes256 provides the strongest encryption and is recommended for production environments, while Aes128 offers faster performance.\r\nTripleDes is legacy and should be avoided for new implementations.", "", false, "false", "Aes256", "Aes128,Aes192,Aes256,TripleDes" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase to create encryption keys for multiple databases.\r\nUse this when you need to enable TDE on several databases across one or more SQL Server instances.", "", false, "true (ByValue)", "", "" ], [ "Force", "Bypasses the safety check that prevents creating encryption keys with unbackup certificates, which could lead to unrecoverable data loss.\r\nAlso creates the specified certificate automatically if it doesn\u0027t exist in the master database.\r\nUse this only in development environments or when you have verified certificate backups exist 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": [ "Storage", "Data", "File", "FileGroup" ], "CommandName": "New-DbaDbFileGroup", "Name": "New-DbaDbFileGroup", "Author": "Adam Lancaster, github.com/lancasteradam", "Syntax": "New-DbaDbFileGroup [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-FileGroup] \u003cString\u003e] [[-FileGroupType] \u003cString\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.FileGroup\nReturns one FileGroup object per filegroup created. If creation fails or is skipped (e.g., filegroup already exists), no object is returned for that filegroup.\nProperties (all from SMO FileGroup object with added connection context):\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- Parent: The parent Database object reference\r\n- FileGroupType: Type of filegroup (RowsFileGroup, FileStreamFileGroup, or MemoryOptimizedFileGroup)\r\n- Name: Name of the filegroup (the value specified in -FileGroup parameter)\r\n- Size: Total size of the filegroup in kilobytes\r\n- AbsolutePhysicalName: Absolute physical name of the filegroup\r\n- DefaultFileGroup: Boolean indicating if this is the default filegroup\r\n- IsDefault: Boolean indicating if this is the default filegroup\r\n- State: State of the filegroup (Normal, Offline, Defunct)\r\n- Files: Collection of DataFile objects in the filegroup\nAll properties from the base SMO FileGroup object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaDbFileGroup -SqlInstance sqldev1 -Database TestDb -FileGroup HRFG1\nCreates the HRFG1 filegroup on the TestDb database on the sqldev1 instance with the default options for the filegroup.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaDbFileGroup -SqlInstance sqldev1 -Database TestDb -FileGroup HRFG1 -FileGroupType FileStreamDataFileGroup\nCreates a filestream filegroup named HRFG1 on the TestDb database on the sqldev1 instance.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eNew-DbaDbFileGroup -SqlInstance sqldev1 -Database TestDb -FileGroup HRFG1 -FileGroupType MemoryOptimizedDataFileGroup\nCreates a MemoryOptimized data filegroup named HRFG1 on the TestDb database on the sqldev1 instance.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sqldev1 -Database TestDb | New-DbaDbFileGroup -FileGroup HRFG1\nPasses in the TestDB database via pipeline and creates the HRFG1 filegroup on the TestDb database on the sqldev1 instance.", "Description": "Creates a new filegroup for the specified database(s), supporting standard row data, FileStream, and memory-optimized storage types. This is useful when you need to separate table storage across different disk drives for performance optimization, implement compliance requirements, or organize data by department or function. The filegroup is created empty and requires adding data files with Add-DbaDbFile before it can store data. Use Set-DbaDbFileGroup to configure advanced properties like read-only status or default settings after files are added.", "Links": "https://dbatools.io/New-DbaDbFileGroup", "Synopsis": "Creates new filegroups in SQL Server databases for custom data storage organization.", "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) where the new filegroup will be created. Supports multiple database names for bulk operations.\r\nUse this when you need to create the same filegroup structure across multiple databases for consistency.", "", false, "false", "", "" ], [ "FileGroup", "Sets the name for the new filegroup being created. The name must be unique within the database and follow SQL Server naming conventions.\r\nUse descriptive names like \u0027HR_Data\u0027 or \u0027Archive_FG\u0027 to indicate the data\u0027s purpose or department for better organization.", "", false, "false", "", "" ], [ "FileGroupType", "Defines the storage type for the filegroup: RowsFileGroup for regular tables and indexes, FileStreamDataFileGroup for FILESTREAM data like documents and images, or MemoryOptimizedDataFileGroup for \r\nIn-Memory OLTP tables.\r\nMost scenarios use the default RowsFileGroup unless you\u0027re specifically implementing FILESTREAM or In-Memory OLTP features.", "", false, "false", "RowsFileGroup", "FileStreamDataFileGroup,MemoryOptimizedDataFileGroup,RowsFileGroup" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase for pipeline operations. This enables you to filter databases first, then create filegroups on 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": [ "DatabaseMail", "DbMail", "Mail" ], "CommandName": "New-DbaDbMailAccount", "Name": "New-DbaDbMailAccount", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "New-DbaDbMailAccount [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Account] \u003cString\u003e [[-DisplayName] \u003cString\u003e] [[-Description] \u003cString\u003e] [-EmailAddress] \u003cString\u003e [[-ReplyToAddress] \u003cString\u003e] [[-MailServer] \u003cString\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Mail.MailAccount\nReturns a newly created MailAccount object from the specified SQL Server 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- Id: Unique identifier for the mail account\r\n- Name: Name of the mail account\r\n- DisplayName: Friendly name that appears in the \u0027From\u0027 field of emails\r\n- Description: Description of the account\u0027s purpose\r\n- EmailAddress: Sender email address for outgoing messages\r\n- ReplyToAddress: Alternate email address for replies\r\n- IsBusyAccount: Boolean indicating if the account is currently processing emails\r\n- MailServers: Collection of mail servers associated with this account\nAdditional properties available (from SMO MailAccount object):\r\n- Parent: Reference to the parent SqlMail object\r\n- State: Current state of the object (Existing, Creating, Pending, Dropping, etc.)\r\n- Urn: The Uniform Resource Name of the mail account object\nAll properties from the base SMO object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$account = New-DbaDbMailAccount -SqlInstance sql2017 -Account \u0027The DBA Team\u0027 -EmailAddress admin@ad.local -MailServer smtp.ad.local\nCreates a new database mail account with the email address admin@ad.local on sql2017 named \"The DBA Team\" using the smtp.ad.local mail server.", "Description": "Creates a new Database Mail account on SQL Server instances to enable automated email notifications, alerts, and reports. Database Mail accounts define the email settings (SMTP server, sender address, authentication) that SQL Server uses when sending emails through stored procedures like sp_send_dbmail. This is essential for setting up automated maintenance notifications, job failure alerts, and scheduled report delivery.", "Links": "https://dbatools.io/New-DbaDbMailAccount", "Synopsis": "Creates a new Database Mail account for sending emails from SQL Server", "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.", "", 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", "", "" ], [ "Account", "Specifies the unique name for the Database Mail account being created. This name is used internally by SQL Server to identify the account when configuring Database Mail profiles.\r\nChoose a descriptive name that identifies the account\u0027s purpose, such as \u0027MaintenanceAlerts\u0027 or \u0027ReportDelivery\u0027.", "Name", true, "false", "", "" ], [ "DisplayName", "Sets the friendly name that appears in the \u0027From\u0027 field of outgoing emails. Recipients see this name instead of the raw account name.\r\nDefaults to the Account name if not specified. Use descriptive names like \u0027SQL Server Alerts\u0027 or \u0027DBA Team Notifications\u0027.", "", false, "false", "$Account", "" ], [ "Description", "Provides optional documentation text describing the account\u0027s purpose and usage. This helps other DBAs understand when and how the account should be used.\r\nConsider including details like which jobs or applications use this account and any special configuration requirements.", "", false, "false", "", "" ], [ "EmailAddress", "Specifies the sender email address that appears in outgoing messages from this Database Mail account. This must be a valid email address that your SMTP server accepts.\r\nUse addresses that recipients will recognize and trust, such as \u0027sqlserver@company.com\u0027 or \u0027dba-alerts@domain.local\u0027.", "", true, "false", "", "" ], [ "ReplyToAddress", "Specifies an alternate email address for replies when different from the sender address. Recipients who reply to automated emails will send responses to this address instead.\r\nUseful when you want replies to go to a monitored mailbox like \u0027dba-team@company.com\u0027 rather than the automated sender address.", "", false, "false", "", "" ], [ "MailServer", "Specifies the SMTP server hostname or IP address that SQL Server will use to send emails through this account. The server must be accessible from the SQL Server instance.\r\nIf not specified, uses the SQL Server instance name as the mail server. The function validates that the mail server exists unless -Force is used.", "", false, "false", "", "" ], [ "Force", "Bypasses the mail server existence validation and creates the Database Mail account even if the specified SMTP server cannot be found or verified.\r\nUse this when the mail server exists but is not discoverable by SQL Server, or when setting up accounts for servers that will be available later.", "", 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": [ "DatabaseMail", "DbMail", "Mail" ], "CommandName": "New-DbaDbMailProfile", "Name": "New-DbaDbMailProfile", "Author": "Ian Lanham (@ilanham)", "Syntax": "New-DbaDbMailProfile [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Profile] \u003cString\u003e [[-Description] \u003cString\u003e] [[-MailAccountName] \u003cString\u003e] [[-MailAccountPriority] \u003cInt32\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Mail.MailProfile\nReturns one MailProfile object for the Database Mail profile that was created.\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 Database Mail profile\r\n- Name: The name of the Database Mail profile\r\n- Description: The description of the Database Mail profile (if provided)\r\n- IsBusyProfile: Boolean indicating if the profile is currently processing mail\nAdditional properties available (from SMO MailProfile object):\r\n- Parent: Reference to parent SqlMail object\r\n- Urn: The Uniform Resource Name of the profile\r\n- State: Current state of the object (Existing, Creating, etc.)\r\n- MailAccountMemberships: Collection of mail accounts associated with this profile", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$profile = New-DbaDbMailProfile -SqlInstance sql2017 -Profile \u0027The DBA Team\u0027\nCreates a new database mail profile.", "Description": "Creates a new Database Mail profile on SQL Server instances, which serves as a container for organizing mail accounts used by SQL Server for notifications, alerts, and reports. Database Mail profiles allow you to group multiple mail accounts and set priorities for failover scenarios. You can optionally associate an existing mail account to the profile during creation, making this useful for setting up complete email notification systems or organizing different notification types into separate profiles.", "Links": "https://dbatools.io/New-DbaDbMailProfile", "Synopsis": "Creates a new Database Mail profile for organizing SQL Server email notifications", "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.", "", 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", "", "" ], [ "Profile", "Specifies the name for the new Database Mail profile. Profile names must be unique within each SQL Server instance.\r\nUse descriptive names like \u0027DBA Alerts\u0027, \u0027Application Notifications\u0027, or \u0027Backup Reports\u0027 to organize different types of email notifications.", "Name", true, "false", "", "" ], [ "Description", "Provides a detailed description explaining the purpose or intended use of the Database Mail profile.\r\nThis helps document what types of emails will be sent through this profile, making it easier for other DBAs to understand the profile\u0027s purpose.", "", false, "false", "", "" ], [ "MailAccountName", "Specifies an existing Database Mail account to associate with this profile during creation.\r\nThe mail account must already exist on the SQL Server instance and will be used to send emails through this profile.", "", false, "false", "", "" ], [ "MailAccountPriority", "Sets the priority level for the associated mail account within the profile, with 1 being the highest priority.\r\nLower priority accounts serve as failover options when higher priority accounts are unavailable. Defaults to 1 if not specified.", "", 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", "" ], [ "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": [ "Masking", "DataMasking" ], "CommandName": "New-DbaDbMaskingConfig", "Name": "New-DbaDbMaskingConfig", "Author": "Sander Stad (@sqlstad, sqlstad.nl) | Chrissy LeMaire (@cl, netnerds.net)", "Syntax": "New-DbaDbMaskingConfig [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-Table] \u003cString[]\u003e] [[-Column] \u003cString[]\u003e] [-Path] \u003cString\u003e [[-Locale] \u003cString\u003e] [[-CharacterString] \u003cString\u003e] [[-SampleCount] \u003cInt32\u003e] [[-KnownNameFilePath] \u003cString\u003e] [[-PatternFilePath] \u003cString\u003e] [-ExcludeDefaultKnownName] [-ExcludeDefaultPattern] [-Force] [[-InputObject] \u003cObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.IO.FileInfo\nReturns one file information object per generated JSON configuration file. The JSON file contains the masking configuration for all detected sensitive columns in the specified database and tables. If \r\nno sensitive data is detected, nothing is returned.\nFile naming convention:\r\n- Default: \"servername.databasename.DataMaskingConfig.json\"\r\n- With table filter (1-4 tables): \"servername.databasename.table1-table2.DataMaskingConfig.json\"\r\n- With table filter (5+ tables): \"servername.databasename.Tables_yyyyMMddHHmmss.DataMaskingConfig.json\"\nThe returned FileInfo object includes standard properties:\r\n- Name: The generated filename\r\n- FullName: The complete file path\r\n- Length: File size in bytes\r\n- CreationTime: When the configuration file was created\r\n- LastWriteTime: When the configuration file was last modified\nThe JSON file structure contains:\r\n- Name: Database name\r\n- Type: \"DataMaskingConfiguration\"\r\n- Tables: Array of table objects, each containing:\r\n - Name: Table name\r\n - Schema: Table schema\r\n - Columns: Array of column masking specifications\r\n - HasUniqueIndex: Boolean indicating if table has unique indexes\r\n - FilterQuery: Optional query to filter which rows get masked\nThis configuration file is consumed by Invoke-DbaDbDataMasking to perform the actual data masking operations.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaDbMaskingConfig -SqlInstance SQLDB1 -Database DB1 -Path C:\\Temp\\clone\nProcess all tables and columns for database DB1 on instance SQLDB1\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaDbMaskingConfig -SqlInstance SQLDB1 -Database DB1 -Table Customer -Path C:\\Temp\\clone\nProcess only table Customer with all the columns\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eNew-DbaDbMaskingConfig -SqlInstance SQLDB1 -Database DB1 -Table Customer -Column City -Path C:\\Temp\\clone\nProcess only table Customer and only the column named \"City\"", "Description": "Analyzes SQL Server database tables and columns to automatically detect potentially sensitive information (PII) and generates a JSON configuration file that defines how to mask each identified column. The function uses pattern matching against column names and data sampling to identify sensitive data like Social Security Numbers, email addresses, phone numbers, and other PII based on predefined patterns and known column naming conventions.\n\nThe generated configuration file is consumed by Invoke-DbaDbDataMasking to perform the actual data masking operations. This two-step process allows you to review and customize the masking strategy before applying changes to your data, making it safer for creating development and testing environments from production databases.\n\nThe function intelligently determines appropriate masking methods based on data type and detected PII category - for example, dates get randomized to past dates, monetary values use commerce pricing patterns, and strings get realistic fake data rather than simple scrambling. You can customize the detection process using your own pattern files and known name definitions to handle organization-specific sensitive data patterns.\n\nNote that the following column and data types are not currently supported:\nIdentity\nForeignKey\nComputed\nHierarchyid\nGeography\nGeometry\nXml\n\nRead more here:\nhttps://sachabarbs.wordpress.com/2018/06/11/bogus-simple-fake-data-tool/\nhttps://github.com/bchavez/Bogus", "Links": "https://dbatools.io/New-DbaDbMaskingConfig", "Synopsis": "Scans database tables to detect sensitive data and creates a JSON configuration file for data masking", "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", "Databases to process through", "", false, "false", "", "" ], [ "Table", "Tables to process. By default all the tables will be processed", "", false, "false", "", "" ], [ "Column", "Columns to process. By default all the columns will be processed", "", false, "false", "", "" ], [ "Path", "Path where to save the generated JSON files.\r\nTh naming convention will be \"servername.databasename.tables.json\"", "", true, "false", "", "" ], [ "Locale", "Set the local to enable certain settings in the masking", "", false, "false", "en", "" ], [ "CharacterString", "The characters to use in string data. \u0027abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\u0027 by default", "", false, "false", "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", "" ], [ "SampleCount", "Amount of rows to sample to make an assessment. The default is 100", "", false, "false", "100", "" ], [ "KnownNameFilePath", "Points to a file containing the custom known names", "", false, "false", "", "" ], [ "PatternFilePath", "Points to a file containing the custom patterns", "", false, "false", "", "" ], [ "ExcludeDefaultKnownName", "Excludes the default known names", "", false, "false", "False", "" ], [ "ExcludeDefaultPattern", "Excludes the default patterns", "", false, "false", "False", "" ], [ "Force", "Forcefully execute commands when needed", "", false, "false", "False", "" ], [ "InputObject", "Used for piping the values from Invoke-DbaDbPiiScan", "", 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": [ "Certificate", "Security" ], "CommandName": "New-DbaDbMasterKey", "Name": "New-DbaDbMasterKey", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "New-DbaDbMasterKey [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-SecurePassword] \u003cSecureString\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.MasterKey\nReturns one MasterKey object for the database where the master key was created.\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 where the master key was created\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\nAdditional properties available (from SMO MasterKey object):\r\n- Urn: The Uniform Resource Name of the master key\r\n- State: Current state of the object (Existing, Creating, etc.)\r\n- Parent: Reference to parent database object", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaDbMasterKey -SqlInstance Server1\nYou will be prompted to securely enter your password, then a master key will be created in the master database on server1 if it does not exist.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaDbMasterKey -SqlInstance Server1 -Credential usernamedoesntmatter\nYou will be prompted by a credential interface to securely enter your password, then a master key will be created in the master database on server1 if it does not exist.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eNew-DbaDbMasterKey -SqlInstance Server1 -Database db1 -Confirm:$false\nSuppresses all prompts to install but prompts in th console to securely enter your password and creates a master key in the \u0027db1\u0027 database", "Description": "Creates a database master key, which is required for implementing Transparent Data Encryption (TDE), Always Encrypted, or other database-level encryption features. The master key serves as the root encryption key that protects other encryption keys within the database. Defaults to creating the key in the master database if no specific database is specified, and will prompt securely for a password if none is provided.", "Links": "https://dbatools.io/New-DbaDbMasterKey", "Synopsis": "Creates a database master key for encryption operations", "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", "Provides an alternative way to supply the master key password using a PSCredential object.\r\nUse this when you need to pass the password programmatically or when integrating with credential management systems. The password portion of the credential is used to encrypt the master key.", "", false, "false", "", "" ], [ "Database", "Specifies the database where the master key will be created. Defaults to master database if not specified.\r\nUse this when implementing encryption features like TDE or Always Encrypted in specific user databases rather than just the system master database.", "", false, "false", "master", "" ], [ "SecurePassword", "Provides the password used to encrypt the database master key as a SecureString object.\r\nIf not specified, you\u0027ll be prompted to enter the password securely via console. This password is required for SQL Server to decrypt the master key when the service starts.", "Password", false, "false", "", "" ], [ "InputObject", "Accepts database objects from the pipeline, typically from Get-DbaDatabase.\r\nUse this when you want to create master keys across multiple databases in a single pipeline operation or when working 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", "" ], [ "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": "New-DbaDbRole", "Name": "New-DbaDbRole", "Author": "Claudio Silva (@ClaudioESSilva), claudioessilva.eu", "Syntax": "New-DbaDbRole [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-ExcludeDatabase] \u003cString[]\u003e] [[-Role] \u003cString[]\u003e] [[-Owner] \u003cString\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.DatabaseRole\nReturns one DatabaseRole object for each role created. One role is created per Role parameter value in each target 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- Name: The name of the newly created database role\r\n- Parent: The name of the database containing the role\r\n- Owner: The database principal that owns the role (dbo by default, or custom owner if specified)\nAdditional properties available (from SMO DatabaseRole object):\r\n- ID: Unique identifier for the role\r\n- CreateDate: DateTime when the role was created\r\n- DateLastModified: DateTime when the role was last modified\nAll properties from the base SMO DatabaseRole object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaDbRole -SqlInstance sql2017a -Database db1 -Role \u0027dbExecuter\u0027\nWill create a new role named dbExecuter within db1 on sql2017a instance.", "Description": "Creates custom database roles for implementing role-based security in SQL Server databases. This function handles the creation of user-defined database roles that can later be granted specific permissions and have users or other roles assigned to them. You can create the same role across multiple databases for consistency, and optionally specify a custom owner instead of the default dbo. This eliminates the need to manually create roles through SSMS or T-SQL for each database.", "Links": "https://dbatools.io/New-DbaDbRole", "Synopsis": "Creates new database roles in one or more 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 create the new role(s) in. Accepts wildcards for pattern matching.\r\nUse this when you need to create roles in specific databases instead of all databases on the instance.\r\nIf unspecified, the role will be created in all accessible databases.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies databases to exclude from role creation when processing all databases.\r\nUse this to skip system databases or specific user databases where the role shouldn\u0027t be created.\r\nParticularly useful when creating standardized roles across most but not all databases.", "", false, "false", "", "" ], [ "Role", "Specifies the name(s) of the custom database role(s) to create.\r\nUse meaningful names that reflect the role\u0027s intended permissions like \u0027AppReadOnly\u0027 or \u0027ReportUsers\u0027.\r\nThe function will create each specified role in all target databases.", "", false, "false", "", "" ], [ "Owner", "Specifies the database principal that will own the new role. Defaults to \u0027dbo\u0027 if not specified.\r\nUse this when you need a specific user or role to own the new database role for security or organizational requirements.\r\nThe owner must exist in each target database.", "", false, "false", "", "" ], [ "InputObject", "Accepts database objects piped from Get-DbaDatabase for role creation.\r\nUse this for advanced filtering or when working with databases from multiple instances.\r\nThis parameter allows you to chain Get-DbaDatabase with specific filters before creating roles.", "", 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": [ "Schema", "Database" ], "CommandName": "New-DbaDbSchema", "Name": "New-DbaDbSchema", "Author": "Adam Lancaster, github.com/lancasteradam", "Syntax": "New-DbaDbSchema [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-Schema] \u003cString[]\u003e] [[-SchemaOwner] \u003cString\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Schema\nReturns one Schema object for each schema created. One schema is created per Schema parameter value in each target database.\nProperties:\r\n- Name: The name of the newly created schema\r\n- Owner: The database user that owns the schema (dbo by default, or custom owner if SchemaOwner is specified)\r\n- Parent: Reference to the parent Database object\r\n- CreateDate: DateTime when the schema was created\r\n- State: The current state of the schema object (Existing, Creating, Pending, etc.)\r\n- Urn: The Uniform Resource Name of the schema object\nAll properties from the base SMO Schema object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaDbSchema -SqlInstance localhost -Database example1 -Schema TestSchema1\nCreates the TestSchema1 schema in the example1 database in the localhost instance. The dbo user will be the owner of the schema.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaDbSchema -SqlInstance localhost -Database example1 -Schema TestSchema1, TestSchema2 -SchemaOwner dbatools\nCreates the TestSchema1 and TestSchema2 schemas in the example1 database in the localhost instance and assigns the dbatools user as the owner of the schemas.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eNew-DbaDbSchema -SqlInstance localhost, localhost\\sql2017 -Database example1 -Schema TestSchema1, TestSchema2 -SchemaOwner dbatools\nCreates the TestSchema1 and TestSchema2 schemas in the example1 database in the localhost and localhost\\sql2017 instances and assigns the dbatools user as the owner of the schemas.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance localhost, localhost\\sql2017 -Database example1 | New-DbaDbSchema -Schema TestSchema1, TestSchema2 -SchemaOwner dbatools\nPasses in the example1 db via pipeline and creates the TestSchema1 and TestSchema2 schemas and assigns the dbatools user as the owner of the schemas.", "Description": "Creates new database schemas within SQL Server databases, allowing you to organize database objects into logical groups and implement security boundaries. Schemas provide a way to separate tables, views, procedures, and other objects by ownership or function, which is essential for multi-tenant applications, security models, and organized database development. You can create multiple schemas across multiple databases in a single operation and specify the database user who will own each schema.", "Links": "https://dbatools.io/New-DbaDbSchema", "Synopsis": "Creates new database schemas with specified ownership for organizing objects and implementing security boundaries.", "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 target database(s) where the new schemas will be created. Accepts multiple database names.\r\nRequired when using SqlInstance parameter, and supports wildcards for pattern matching across database names.", "", false, "false", "", "" ], [ "Schema", "Specifies the name(s) of the schema(s) to create within the target databases. Accepts multiple schema names for batch creation.\r\nSchema names must be valid SQL Server identifiers and will fail if they already exist in the target database.", "", false, "false", "", "" ], [ "SchemaOwner", "Specifies the database user who will own the created schema(s). Must be an existing user in the target database.\r\nWhen omitted, the schema owner defaults to \u0027dbo\u0027. Use this to implement security boundaries or assign schemas to application users.", "", false, "false", "", "" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase via pipeline input, eliminating the need to specify SqlInstance and Database parameters.\r\nUse this approach when you need to work with a pre-filtered set of databases or want to chain 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", "" ], [ "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": "New-DbaDbSequence", "Name": "New-DbaDbSequence", "Author": "Adam Lancaster, github.com/lancasteradam", "Syntax": "New-DbaDbSequence [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [-Sequence] \u003cString[]\u003e [[-Schema] \u003cString\u003e] [[-IntegerType] \u003cString\u003e] [[-StartWith] \u003cInt64\u003e] [[-IncrementBy] \u003cInt64\u003e] [[-MinValue] \u003cInt64\u003e] [[-MaxValue] \u003cInt64\u003e] [-Cycle] [[-CacheSize] \u003cInt32\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Sequence\nReturns one Sequence object for each sequence successfully created. The returned object represents the newly created 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\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:\\\u003eNew-DbaDbSequence -SqlInstance sqldev01 -Database TestDB -Sequence TestSequence -StartWith 10000 -IncrementBy 10\nCreates a new sequence TestSequence in the TestDB database on the sqldev01 instance. The sequence will start with 10000 and increment by 10.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaDbSequence -SqlInstance sqldev01 -Database TestDB -Sequence TestSequence -Cycle\nCreates a new sequence TestSequence in the TestDB database on the sqldev01 instance. The sequence will cycle the numbers.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sqldev01 -Database TestDB | New-DbaDbSequence -Sequence TestSequence -Schema TestSchema -IntegerType bigint\nUsing a pipeline this command creates a new bigint sequence named TestSchema.TestSequence in the TestDB database on the sqldev01 instance.", "Description": "Creates a new sequence object in one or more SQL Server databases, providing an alternative to IDENTITY columns for generating sequential numbers. This function allows you to configure all sequence properties including data type (system or user-defined), starting value, increment, min/max bounds, cycling behavior, and cache settings. Sequences are particularly useful when you need to share sequential numbers across multiple tables, require more control over number generation than IDENTITY provides, or need to reset or alter the sequence values. The function automatically creates the target schema if it doesn\u0027t exist and supports SQL Server 2012 and higher.", "Links": "https://dbatools.io/New-DbaDbSequence", "Synopsis": "Creates a new sequence object in SQL Server databases with configurable properties and data types.", "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 target database(s) where the sequence will be created. Accepts multiple database names.\r\nRequired when using SqlInstance parameter to specify which databases should contain the new sequence.", "", false, "false", "", "" ], [ "Sequence", "Specifies the name of the sequence object to create. Must be unique within the target schema.\r\nUse descriptive names like \u0027OrderNumber\u0027 or \u0027InvoiceID\u0027 to indicate the sequence\u0027s purpose.", "Name", true, "false", "", "" ], [ "Schema", "Specifies the schema where the sequence will be created. Defaults to \u0027dbo\u0027 if not specified.\r\nThe function will automatically create the schema if it doesn\u0027t exist in the target database.", "", false, "false", "dbo", "" ], [ "IntegerType", "Specifies the data type for the sequence values. Defaults to \u0027bigint\u0027 for maximum range.\r\nSupports system types (tinyint, smallint, int, bigint) and user-defined integer types using \u0027schema.typename\u0027 format.", "", false, "false", "bigint", "" ], [ "StartWith", "Sets the initial value for the sequence. Defaults to 1 if not specified.\r\nUse higher starting values like 10000 when you need to reserve lower numbers or maintain existing numbering schemes.", "", false, "false", "1", "" ], [ "IncrementBy", "Controls how much the sequence increases with each call to NEXT VALUE FOR. Defaults to 1.\r\nUse negative values for descending sequences or larger increments like 10 for spaced numbering.", "", false, "false", "1", "" ], [ "MinValue", "Sets the lowest value the sequence can generate. When omitted, uses the data type\u0027s minimum value.\r\nSpecify this to prevent sequences from generating values below a certain threshold.", "", false, "false", "0", "" ], [ "MaxValue", "Sets the highest value the sequence can generate. When omitted, uses the data type\u0027s maximum value.\r\nDefine this to limit sequence values or enable cycling at a specific upper bound.", "", false, "false", "0", "" ], [ "Cycle", "Enables the sequence to restart from MinValue after reaching MaxValue (or vice versa for descending sequences).\r\nUse this for sequences that should continuously cycle through a range of values rather than stopping at the boundary.", "", false, "false", "False", "" ], [ "CacheSize", "Controls how many sequence values SQL Server pre-allocates in memory for performance. Set to 0 for NO CACHE.\r\nHigher cache sizes improve performance for frequently accessed sequences but may cause gaps if the instance restarts.", "", false, "false", "0", "" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase via pipeline input.\r\nUse this for pipeline operations when you want to create sequences across multiple databases returned by 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", "" ], [ "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": [ "Snapshot", "Restore", "Database" ], "CommandName": "New-DbaDbSnapshot", "Name": "New-DbaDbSnapshot", "Author": "Simone Bizzotto (@niphold)", "Syntax": "New-DbaDbSnapshot [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-AllDatabases] [[-Name] \u003cString\u003e] [[-NameSuffix] \u003cString\u003e] [[-Path] \u003cString\u003e] [-Force] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Database\nReturns one Database object for each snapshot successfully created. The returned object represents the newly created database snapshot with its configuration and usage 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: 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 dbasize object: KB, MB, GB, TB, 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 (always $true for snapshots)\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\r\n- IsAccessible: Boolean indicating if the snapshot is accessible\r\n- Status: Current status of the snapshot database\r\n- Collation: The database collation\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:\\\u003eNew-DbaDbSnapshot -SqlInstance sqlserver2014a -Database HR, Accounting\nCreates snapshot for HR and Accounting, returning a custom object displaying Server, Database, DatabaseCreated, SnapshotOf, SizeMB, DatabaseCreated, PrimaryFilePath, Status, Notes\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaDbSnapshot -SqlInstance sqlserver2014a -Database HR -Name HR_snap\nCreates snapshot named \"HR_snap\" for HR\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eNew-DbaDbSnapshot -SqlInstance sqlserver2014a -Database HR -NameSuffix \u0027fool_{0}_snap\u0027\nCreates snapshot named \"fool_HR_snap\" for HR\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eNew-DbaDbSnapshot -SqlInstance sqlserver2014a -Database HR, Accounting -Path F:\\snapshotpath\nCreates snapshots for HR and Accounting databases, storing files under the F:\\snapshotpath\\ dir\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2016 -Database df | New-DbaDbSnapshot\nCreates a snapshot for the database df on sql2016", "Description": "Creates read-only database snapshots that capture the state of a database at a specific moment in time. Snapshots provide a fast way to revert databases to a previous state without restoring from backup files, making them ideal for pre-maintenance snapshots, testing scenarios, or quick rollback points.\n\nThe function automatically generates snapshot file names with timestamps and handles the underlying file structure creation. Snapshots share pages with the source database until changes occur, making them storage-efficient for short-term use. Note that snapshots are not a replacement for regular backups and should be dropped when no longer needed to avoid performance impacts.", "Links": "https://dbatools.io/New-DbaDbSnapshot", "Synopsis": "Creates database snapshots for point-in-time recovery and testing scenarios", "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 create snapshots for. Accepts an array of database names.\r\nUse this when you need snapshots for specific databases rather than all databases on the instance.\r\nCannot be used together with AllDatabases parameter.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific databases from snapshot creation when using AllDatabases.\r\nUseful when you want to snapshot most databases but skip certain ones like development or staging databases.\r\nAccepts an array of database names to exclude from the operation.", "", false, "false", "", "" ], [ "AllDatabases", "Creates snapshots for all user databases on the instance that support snapshotting.\r\nAutomatically excludes system databases (master, model, tempdb), snapshots, and databases with memory-optimized filegroups.\r\nUse this when you need to create snapshots for disaster recovery or before major maintenance operations.", "", false, "false", "False", "" ], [ "Name", "Sets a custom name for the database snapshot. Only works when targeting a single database.\r\nUse this when you need a meaningful snapshot name like \u0027Sales_PreUpgrade\u0027 instead of the default timestamped name.\r\nFor multiple databases, use NameSuffix parameter instead to avoid naming conflicts.", "", false, "false", "", "" ], [ "NameSuffix", "Customizes the suffix appended to database names when creating snapshots. Defaults to yyyyMMdd_HHmmss format.\r\nUse simple strings like \u0027_PrePatch\u0027 or templates with {0} placeholder where {0} represents the database name.\r\nExamples: \u0027_BeforeMaintenance\u0027 creates \u0027HR_BeforeMaintenance\u0027, or \u0027Snap_{0}_v1\u0027 creates \u0027Snap_HR_v1\u0027.", "", false, "false", "", "" ], [ "Path", "Specifies the directory where snapshot files will be stored. Defaults to the same location as the source database files.\r\nUse this when you need snapshots on different storage for performance or capacity reasons.\r\nThe SQL Server service account must have write access to the specified path.", "", false, "false", "", "" ], [ "Force", "Creates partial snapshots for databases containing FILESTREAM filegroups. FILESTREAM data is excluded and marked offline in the snapshot.\r\nUse this when you need to snapshot databases with FILESTREAM for testing or point-in-time analysis of non-FILESTREAM data.\r\nWarning: Databases cannot be restored from partial snapshots due to the missing FILESTREAM data.", "", false, "false", "False", "" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase for pipeline operations.\r\nEnables scenarios like filtering databases with specific criteria before creating snapshots.\r\nExample: Get-DbaDatabase -SqlInstance sql01 | Where-Object Size -gt 1000 | New-DbaDbSnapshot", "", 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", "wi", false, "false", "", "" ], [ "Confirm", "Prompts for confirmation of every step.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Synonym", "Database" ], "CommandName": "New-DbaDbSynonym", "Name": "New-DbaDbSynonym", "Author": "Mikey Bronowski (@MikeyBronowski), bronowski.it", "Syntax": "New-DbaDbSynonym [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-ExcludeDatabase] \u003cString[]\u003e] [[-Synonym] \u003cString\u003e] [[-Schema] \u003cString\u003e] [[-BaseServer] \u003cString\u003e] [[-BaseDatabase] \u003cString\u003e] [[-BaseSchema] \u003cString\u003e] [-BaseObject] \u003cString\u003e [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Synonym\nReturns one Synonym object for each synonym created. The object includes added properties from the parent SQL Server and database objects for 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 name of the database containing the synonym (ParentName)\r\n- Name: The name of the synonym\r\n- Schema: The schema where the synonym is created (default: dbo)\r\n- BaseServer: The linked server name for cross-server synonyms, or null for same-server synonyms\r\n- BaseDatabase: The target database for the synonym reference, or null if referencing same database\r\n- BaseSchema: The target schema for the synonym reference\r\n- BaseObject: The name of the database object the synonym references\nAdditional properties available (from SMO Synonym object):\r\n- CreateDate: DateTime when the synonym was created\r\n- Urn: The Uniform Resource Name of the synonym object\r\n- State: The current state of the SMO object (Existing, Creating, etc.)\r\n- Parent: Reference to the parent database object\nAll properties from the base SMO Synonym object are accessible using Select-Object * even though only the default properties are displayed by default.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaDbSynonym -SqlInstance sql2017a -Database db1 -Synonym synObj1 -BaseObject Obj1\nWill create a new synonym named synObj1 in db1 database in dbo schema on sql2017a instance for Obj1 object in the same database.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaDbSynonym -SqlInstance sql2017a -Database db1 -Synonym synObj1 -BaseObject Obj1\nWill create a new synonym named synObj1 in db1 database in dbo schema on sql2017a instance for Obj1 object in the same database.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eNew-DbaDbSynonym -SqlInstance sql2017a -Database db1 -Schema sch1 -Synonym synObj1 -BaseObject Obj1\nWill create a new synonym named synObj1 within dbo schema in db1 database on sql2017a instance for Obj1 object in the same database.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eNew-DbaDbSynonym -SqlInstance sql2017a -Database db1 -Schema sch1 -Synonym synObj1 -BaseObject Obj1 -BaseSchema bSch2\nWill create a new synonym named synObj1 within sch1 schema in db1 database on sql2017a instance for Obj1 object within bSch2 schema in the same database.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eNew-DbaDbSynonym -SqlInstance sql2017a -Database db1 -Schema sch1 -Synonym synObj1 -BaseObject Obj1 -BaseSchema bSch2 -BaseDatabase bDb3\nWill create a new synonym named synObj1 within sch1 schema in db1 database on sql2017a instance for Obj1 object within bSch2 schema in bDb3 database.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eNew-DbaDbSynonym -SqlInstance sql2017a -Database db1 -Schema sch1 -Synonym synObj1 -BaseObject Obj1 -BaseSchema bSch2 -BaseDatabase bDb3 -BaseServer bSrv4\nWill create a new synonym named synObj1 within sch1 schema in db1 database on sql2017a instance for Obj1 object within bSch2 schema in bDb3 database on bSrv4 linked server.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2017a -ExcludeSystem | New-DbaDbSynonym -Synonym synObj1 -BaseObject Obj1\nWill create a new synonym named synObj1 within dbo schema in all user databases on sql2017a instance for Obj1 object in the respective databases.", "Description": "Creates database synonyms that serve as alternate names or aliases for database objects like tables, views, stored procedures, and functions. Synonyms simplify object references by providing shorter names, hiding complex schema structures, or creating abstraction layers for applications. You can create synonyms that reference objects in the same database, different databases, or even on linked servers, making cross-database and cross-server object access more manageable for applications and users.", "Links": "https://dbatools.io/New-DbaDbSynonym", "Synopsis": "Creates database synonyms to provide alternate names for tables, views, procedures, and other database objects.", "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 create the synonym in. Accepts wildcards for pattern matching.\r\nWhen omitted, synonyms will be created in all accessible databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific databases from synonym creation when processing multiple databases.\r\nUseful when you want to create synonyms across most databases but skip system databases or specific user databases.", "", false, "false", "", "" ], [ "Synonym", "The name of the synonym to create. This becomes the alternate name that applications and users will reference.\r\nChoose meaningful names that follow your organization\u0027s naming conventions and make object access more intuitive.", "", false, "false", "", "" ], [ "Schema", "The schema where the synonym will be created. Defaults to \u0027dbo\u0027 if not specified.\r\nConsider using application-specific schemas to organize synonyms logically and control access through schema permissions.", "", false, "false", "dbo", "" ], [ "BaseServer", "The linked server name when creating cross-server synonyms. Requires BaseDatabase and BaseSchema parameters.\r\nUse this to create synonyms that reference objects on remote SQL Server instances through established linked server connections.", "", false, "false", "", "" ], [ "BaseDatabase", "The database containing the target object that the synonym will reference. Requires BaseSchema when specified.\r\nUse this for cross-database synonyms or when creating synonyms on linked servers to reference objects in specific databases.", "", false, "false", "", "" ], [ "BaseSchema", "The schema containing the target object that the synonym will reference.\r\nRequired when BaseDatabase is specified, ensuring the synonym points to the correct object in complex multi-schema environments.", "", false, "false", "", "" ], [ "BaseObject", "The name of the database object that the synonym will reference. Supports tables, views, stored procedures, functions, and other schema-scoped objects.\r\nThis is the actual object that users will access through the synonym name, enabling abstraction and simplified references.", "", true, "false", "", "" ], [ "InputObject", "Accepts database objects piped from Get-DbaDatabase for creating synonyms across multiple databases.\r\nUseful for batch operations when you need to create the same synonym in multiple databases selected by specific criteria.", "", 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": "table", "CommandName": "New-DbaDbTable", "Name": "New-DbaDbTable", "Author": "Chrissy LeMaire (@cl)", "Syntax": "New-DbaDbTable [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-Name] \u003cString\u003e] [[-Schema] \u003cString\u003e] [[-ColumnMap] \u003cHashtable[]\u003e] [[-ColumnObject] \u003cColumn[]\u003e] [-AnsiNullsStatus] [-ChangeTrackingEnabled] [[-DataSourceName] \u003cString\u003e] [[-Durability] {SchemaOnly | SchemaAndData}] [[-ExternalTableDistribution] {Sharded | Replicated | RoundRobin | None}] [[-FileFormatName] \u003cString\u003e] [[-FileGroup] \u003cString\u003e] [[-FileStreamFileGroup] \u003cString\u003e] [[-FileStreamPartitionScheme] \u003cString\u003e] [[-FileTableDirectoryName] \u003cString\u003e] \r\n[[-FileTableNameColumnCollation] \u003cString\u003e] [-FileTableNamespaceEnabled] [[-HistoryTableName] \u003cString\u003e] [[-HistoryTableSchema] \u003cString\u003e] [-IsExternal] [-IsFileTable] [-IsMemoryOptimized] [-IsSystemVersioned] [[-Location] \u003cString\u003e] [[-LockEscalation] {Table | Disable | Auto}] [[-Owner] \u003cString\u003e] [[-PartitionScheme] \u003cString\u003e] [-QuotedIdentifierStatus] [[-RejectSampleValue] \u003cDouble\u003e] [[-RejectType] {Value | Percentage | None}] [[-RejectValue] \u003cDouble\u003e] [[-RemoteDataArchiveDataMigrationState] {Disabled | PausedOutbound | PausedInbound | Outbound | Inbound | Paused}] [-RemoteDataArchiveEnabled] \r\n[[-RemoteDataArchiveFilterPredicate] \u003cString\u003e] [[-RemoteObjectName] \u003cString\u003e] [[-RemoteSchemaName] \u003cString\u003e] [[-RemoteTableName] \u003cString\u003e] [-RemoteTableProvisioned] [[-ShardingColumnName] \u003cString\u003e] [[-TextFileGroup] \u003cString\u003e] [-TrackColumnsUpdatedEnabled] [[-HistoryRetentionPeriod] \u003cInt32\u003e] [[-HistoryRetentionPeriodUnit] {Day | Week | Month | Year | Undefined | Infinite}] [[-DwTableDistribution] {Undefined | None | Hash | Replicate | RoundRobin}] [[-RejectedRowLocation] \u003cString\u003e] [-OnlineHeapOperation] [[-LowPriorityMaxDuration] \u003cInt32\u003e] [-DataConsistencyCheck] [[-LowPriorityAbortAfterWait] \r\n{None | Blockers | Self}] [[-MaximumDegreeOfParallelism] \u003cInt32\u003e] [-IsNode] [-IsEdge] [-IsVarDecimalStorageFormatEnabled] [-Passthru] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.String (when -Passthru is specified)\nReturns the T-SQL CREATE TABLE script as a string for review or version control before deployment.\nMicrosoft.SqlServer.Management.Smo.Table (default)\nReturns one Table object for each table successfully created. The table object includes all configured columns, constraints, indexes, and table 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- Database: Database containing the table\r\n- Schema: Schema containing the table\r\n- Name: Name of the table\r\n- Rows: Number of rows in the table (0 for newly created tables)\r\n- Created: DateTime when the table was created\r\n- LastModified: DateTime when the table was last modified\nAdditional properties available (from SMO Table object):\r\n- FileGroup: Filegroup where the table data is stored\r\n- AnsiNullsStatus: Boolean indicating if ANSI_NULLS is enabled\r\n- QuotedIdentifierStatus: Boolean indicating if QUOTED_IDENTIFIER is enabled\r\n- ChangeTrackingEnabled: Boolean indicating if change tracking is enabled\r\n- IsMemoryOptimized: Boolean indicating if table is memory-optimized\r\n- IsSystemVersioned: Boolean indicating if table is system-versioned temporal table\r\n- IsFileTable: Boolean indicating if table is a FileTable\r\n- IsExternal: Boolean indicating if table is an external table\r\n- TrackColumnsUpdatedEnabled: Boolean indicating if column-level change tracking is enabled", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$col = @{\n\u003e\u003e Name = \u0027test\u0027\r\n\u003e\u003e Type = \u0027varchar\u0027\r\n\u003e\u003e MaxLength = 20\r\n\u003e\u003e Nullable = $true\r\n\u003e\u003e }\r\nPS C:\\\u003e New-DbaDbTable -SqlInstance sql2017 -Database tempdb -Name testtable -ColumnMap $col\nCreates a new table on sql2017 in tempdb with the name testtable and one column\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$cols = @( )\n\u003e\u003e $cols += @{\r\n\u003e\u003e Name = \u0027Id\u0027\r\n\u003e\u003e Type = \u0027varchar\u0027\r\n\u003e\u003e MaxLength = 36\r\n\u003e\u003e DefaultExpression = \u0027NEWID()\u0027\r\n\u003e\u003e }\r\n\u003e\u003e $cols += @{\r\n\u003e\u003e Name = \u0027Since\u0027\r\n\u003e\u003e Type = \u0027datetime2\u0027\r\n\u003e\u003e DefaultString = \u00272021-12-31\u0027\r\n\u003e\u003e }\r\nPS C:\\\u003e New-DbaDbTable -SqlInstance sql2017 -Database tempdb -Name testtable -ColumnMap $cols\nCreates a new table on sql2017 in tempdb with the name testtable and two columns.\r\nUses \"DefaultExpression\" to interpret the value \"NEWID()\" as an expression regardless of the data type of the column.\r\nUses \"DefaultString\" to interpret the value \"2021-12-31\" as a string regardless of the data type of the column.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e# Create collection\n\u003e\u003e $cols = @()\n\u003e\u003e # Add columns to collection\r\n\u003e\u003e $cols += @{\r\n\u003e\u003e Name = \u0027testId\u0027\r\n\u003e\u003e Type = \u0027int\u0027\r\n\u003e\u003e Identity = $true\r\n\u003e\u003e }\r\n\u003e\u003e $cols += @{\r\n\u003e\u003e Name = \u0027test\u0027\r\n\u003e\u003e Type = \u0027varchar\u0027\r\n\u003e\u003e MaxLength = 20\r\n\u003e\u003e Nullable = $true\r\n\u003e\u003e }\r\n\u003e\u003e $cols += @{\r\n\u003e\u003e Name = \u0027test2\u0027\r\n\u003e\u003e Type = \u0027int\u0027\r\n\u003e\u003e Nullable = $false\r\n\u003e\u003e }\r\n\u003e\u003e $cols += @{\r\n\u003e\u003e Name = \u0027test3\u0027\r\n\u003e\u003e Type = \u0027decimal\u0027\r\n\u003e\u003e MaxLength = 9\r\n\u003e\u003e Nullable = $true\r\n\u003e\u003e }\r\n\u003e\u003e $cols += @{\r\n\u003e\u003e Name = \u0027test4\u0027\r\n\u003e\u003e Type = \u0027decimal\u0027\r\n\u003e\u003e Precision = 8\r\n\u003e\u003e Scale = 2\r\n\u003e\u003e Nullable = $false\r\n\u003e\u003e }\r\n\u003e\u003e $cols += @{\r\n\u003e\u003e Name = \u0027test5\u0027\r\n\u003e\u003e Type = \u0027Nvarchar\u0027\r\n\u003e\u003e MaxLength = 50\r\n\u003e\u003e Nullable = $false\r\n\u003e\u003e Default = \u0027Hello\u0027\r\n\u003e\u003e DefaultName = \u0027DF_Name_test5\u0027\r\n\u003e\u003e }\r\n\u003e\u003e $cols += @{\r\n\u003e\u003e Name = \u0027test6\u0027\r\n\u003e\u003e Type = \u0027int\u0027\r\n\u003e\u003e Nullable = $false\r\n\u003e\u003e Default = \u00270\u0027\r\n\u003e\u003e }\r\n\u003e\u003e $cols += @{\r\n\u003e\u003e Name = \u0027test7\u0027\r\n\u003e\u003e Type = \u0027smallint\u0027\r\n\u003e\u003e Nullable = $false\r\n\u003e\u003e Default = 100\r\n\u003e\u003e }\r\n\u003e\u003e $cols += @{\r\n\u003e\u003e Name = \u0027test8\u0027\r\n\u003e\u003e Type = \u0027Nchar\u0027\r\n\u003e\u003e MaxLength = 3\r\n\u003e\u003e Nullable = $false\r\n\u003e\u003e Default = \u0027ABC\u0027\r\n\u003e\u003e }\r\n\u003e\u003e $cols += @{\r\n\u003e\u003e Name = \u0027test9\u0027\r\n\u003e\u003e Type = \u0027char\u0027\r\n\u003e\u003e MaxLength = 4\r\n\u003e\u003e Nullable = $false\r\n\u003e\u003e Default = \u0027XPTO\u0027\r\n\u003e\u003e }\r\n\u003e\u003e $cols += @{\r\n\u003e\u003e Name = \u0027test10\u0027\r\n\u003e\u003e Type = \u0027datetime\u0027\r\n\u003e\u003e Nullable = $false\r\n\u003e\u003e Default = \u0027GETDATE()\u0027\r\n\u003e\u003e }\nPS C:\\\u003e New-DbaDbTable -SqlInstance sql2017 -Database tempdb -Name testtable -ColumnMap $cols\nCreates a new table on sql2017 in tempdb with the name testtable and ten columns.", "Description": "Creates new tables in SQL Server databases with specified columns, data types, constraints, and properties. You can define table structure using simple PowerShell hashtables for columns or pass in pre-built SMO column objects for advanced scenarios. The function handles all common column properties including data types, nullability, default values, identity columns, and decimal precision/scale. It also supports advanced table features like memory optimization, temporal tables, file tables, and external tables. If the specified schema doesn\u0027t exist, it will be created automatically.", "Links": "https://dbatools.io/New-DbaDbTable", "Synopsis": "Creates database tables with columns and constraints using PowerShell hashtables or SMO objects", "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).\n Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\n For MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Database", "Specifies the database where the new table will be created. Accepts multiple database names to create the same table across several databases.\r\nUse this when you need to deploy identical table structures to multiple databases in your environment.", "", false, "false", "", "" ], [ "Name", "Specifies the name for the new table. Must be a valid SQL Server identifier.\r\nUse standard naming conventions like avoiding spaces and reserved keywords for better maintainability.", "Table", false, "false", "", "" ], [ "Schema", "Specifies the schema where the table will be created. Defaults to \u0027dbo\u0027 if not specified.\r\nUse this to organize tables by functional area or security requirements. The schema will be created automatically if it doesn\u0027t exist.", "", false, "false", "dbo", "" ], [ "ColumnMap", "Defines table columns using PowerShell hashtables with properties like Name, Type, MaxLength, Nullable, Default, Identity, etc.\r\nThis is the primary method for specifying column structure when you need simple, declarative table creation. See examples for supported hashtable properties.", "", false, "false", "", "" ], [ "ColumnObject", "Accepts pre-built SMO Column objects for advanced scenarios requiring complex column configurations.\r\nUse this when you need features not supported by ColumnMap hashtables, such as computed columns or advanced constraints.", "", false, "false", "", "" ], [ "AnsiNullsStatus", "Controls ANSI_NULLS setting for the table, affecting how null comparisons are handled in queries.\r\nEnable this to ensure ANSI-compliant null handling behavior, which is recommended for modern applications.", "", false, "false", "False", "" ], [ "ChangeTrackingEnabled", "Enables SQL Server Change Tracking on the table to monitor data modifications.\r\nUse this when you need to track which rows have been inserted, updated, or deleted for synchronization scenarios.", "", false, "false", "False", "" ], [ "DataSourceName", "Specifies the external data source name for external tables in SQL Server 2016+ or Azure SQL.\r\nRequired when creating external tables that reference data in Hadoop, Azure Blob Storage, or other external systems.", "", false, "false", "", "" ], [ "Durability", "Sets the durability level for memory-optimized tables (SCHEMA_AND_DATA or SCHEMA_ONLY).\r\nUse SCHEMA_ONLY for temporary data that doesn\u0027t need to persist across server restarts, or SCHEMA_AND_DATA for permanent memory-optimized tables.", "", false, "false", "", "" ], [ "ExternalTableDistribution", "Specifies the distribution method for external tables in Azure SQL Data Warehouse or Parallel Data Warehouse.\r\nChoose between HASH, ROUND_ROBIN, or REPLICATE based on your query patterns and data size requirements.", "", false, "false", "", "" ], [ "FileFormatName", "Specifies the external file format name for external tables that read from files.\r\nRequired when creating external tables that reference structured files like CSV, Parquet, or ORC in external storage systems.", "", false, "false", "", "" ], [ "FileGroup", "Specifies the filegroup where the table data will be stored. Defaults to the database\u0027s default filegroup.\r\nUse this to control storage placement for performance optimization or to separate tables across different storage devices.", "", false, "false", "", "" ], [ "FileStreamFileGroup", "Specifies the FILESTREAM filegroup for tables that store large binary data as files.\r\nRequired when creating tables with FILESTREAM columns for storing documents, images, or other large binary objects.", "", false, "false", "", "" ], [ "FileStreamPartitionScheme", "Specifies the partition scheme for FILESTREAM data in partitioned tables.\r\nUse this when you need to partition FILESTREAM data across multiple filegroups for performance or maintenance benefits.", "", false, "false", "", "" ], [ "FileTableDirectoryName", "Sets the directory name for FileTable functionality, allowing Windows file system access to table data.\r\nSpecify a meaningful name that will appear as a folder in the Windows file system when accessing the table through the file share.", "", false, "false", "", "" ], [ "FileTableNameColumnCollation", "Specifies the collation for the name column in FileTable to control file name sorting and comparison.\r\nUse a case-insensitive collation for Windows-compatible file name handling in FileTable scenarios.", "", false, "false", "", "" ], [ "FileTableNamespaceEnabled", "Enables the FileTable namespace, allowing file system access through Windows APIs.\r\nSet to true when you want applications to access table data through standard file operations like copy, move, and delete.", "", false, "false", "False", "" ], [ "HistoryTableName", "Specifies the name of the history table for system-versioned temporal tables.\r\nRequired when creating temporal tables that automatically track all data changes for point-in-time queries and auditing.", "", false, "false", "", "" ], [ "HistoryTableSchema", "Specifies the schema for the history table in system-versioned temporal tables.\r\nUse this to organize history tables in a separate schema for better security and maintenance separation from current data.", "", false, "false", "", "" ], [ "IsExternal", "Creates an external table that references data stored outside SQL Server.\r\nUse this for querying data in Azure Blob Storage, Hadoop, or other external systems without importing the data into SQL Server.", "", false, "false", "False", "" ], [ "IsFileTable", "Creates a FileTable that combines relational data with Windows file system access.\r\nEnable this when you need applications to store and manage documents through both T-SQL and standard Windows file operations.", "", false, "false", "False", "" ], [ "IsMemoryOptimized", "Creates an In-Memory OLTP table stored entirely in memory for high-performance scenarios.\r\nUse this for tables requiring extremely high transaction throughput with low latency, typically in OLTP workloads.", "", false, "false", "False", "" ], [ "IsSystemVersioned", "Creates a temporal table that automatically tracks all data changes with system-generated timestamps.\r\nEnable this for auditing requirements or when you need to query historical versions of data at any point in time.", "", false, "false", "False", "" ], [ "Location", "Specifies the location path for external tables pointing to files or directories.\r\nRequired for external tables to define where the actual data files are stored in the external system.", "", false, "false", "", "" ], [ "LockEscalation", "Controls when SQL Server escalates row or page locks to table locks (TABLE, AUTO, or DISABLE).\r\nSet to DISABLE for high-concurrency scenarios where table-level locks would cause blocking, or AUTO for default behavior.", "", false, "false", "", "" ], [ "Owner", "Specifies the table owner, typically a database user or role with appropriate permissions.\r\nUse this to set explicit ownership for security or administrative purposes, though schema-contained objects are generally preferred.", "", false, "false", "", "" ], [ "PartitionScheme", "Specifies the partition scheme for horizontally partitioning large tables across multiple filegroups.\r\nUse this for very large tables to improve query performance and enable parallel maintenance operations on partition boundaries.", "", false, "false", "", "" ], [ "QuotedIdentifierStatus", "Controls QUOTED_IDENTIFIER setting for the table, affecting how double quotes are interpreted in queries.\r\nEnable this to use double quotes for identifiers containing spaces or reserved words, following ANSI SQL standards.", "", false, "false", "False", "" ], [ "RejectSampleValue", "Sets the sample size for reject value calculations in external tables with error handling.\r\nSpecify the number of rows to sample when determining if reject thresholds have been exceeded during external data access.", "", false, "false", "0", "" ], [ "RejectType", "Defines how reject values are calculated for external tables (VALUE or PERCENTAGE).\r\nUse VALUE for absolute row count limits or PERCENTAGE for proportional error thresholds when accessing external data sources.", "", false, "false", "", "" ], [ "RejectValue", "Sets the maximum number or percentage of rejected rows allowed when querying external tables.\r\nConfigure this to control query behavior when encountering data quality issues in external data sources.", "", false, "false", "0", "" ], [ "RemoteDataArchiveDataMigrationState", "Controls the data migration state for Stretch Database tables (INBOUND, OUTBOUND, or PAUSED).\r\nUse this to manage how historical data is migrated between on-premises SQL Server and Azure SQL Database.", "", false, "false", "", "" ], [ "RemoteDataArchiveEnabled", "Enables Stretch Database functionality to automatically migrate cold data to Azure SQL Database.\r\nUse this for tables with historical data that can be moved to lower-cost cloud storage while remaining queryable.", "", false, "false", "False", "" ], [ "RemoteDataArchiveFilterPredicate", "Defines the filter function determining which rows are eligible for Stretch Database migration.\r\nSpecify a function that returns 1 for rows to migrate, typically based on date criteria for archiving old data.", "", false, "false", "", "" ], [ "RemoteObjectName", "Specifies the name of the remote table or object for Stretch Database or external table scenarios.\r\nUse this when the remote table name differs from the local table name in federated or hybrid configurations.", "", false, "false", "", "" ], [ "RemoteSchemaName", "Specifies the schema name in the remote database for Stretch Database tables.\r\nDefine this when the remote Azure SQL Database uses a different schema structure than your local database.", "", false, "false", "", "" ], [ "RemoteTableName", "Sets the table name in the remote Azure SQL Database for Stretch Database functionality.\r\nSpecify this when you want the archived data to use a different table name in the cloud storage location.", "", false, "false", "", "" ], [ "RemoteTableProvisioned", "Indicates whether the remote table for Stretch Database has already been created in Azure SQL Database.\r\nSet to true if the remote table structure already exists, preventing automatic provisioning during setup.", "", false, "false", "False", "" ], [ "ShardingColumnName", "Specifies the column used for sharding data distribution in Azure SQL Database elastic pools.\r\nDefine the column that determines how rows are distributed across multiple database shards for horizontal scaling.", "", false, "false", "", "" ], [ "TextFileGroup", "Specifies the filegroup for storing text, ntext, and image columns in SQL Server versions before 2016.\r\nUse this for legacy applications requiring separate storage for large text data, though newer data types are recommended.", "", false, "false", "", "" ], [ "TrackColumnsUpdatedEnabled", "Enables column-level change tracking to identify which specific columns were modified.\r\nUse this when you need granular change information beyond just knowing that a row was updated, useful for selective synchronization.", "", false, "false", "False", "" ], [ "HistoryRetentionPeriod", "Sets the retention period for temporal table history data before automatic cleanup.\r\nSpecify the number of time units (days, months, years) to retain historical data for compliance and storage management.", "", false, "false", "0", "" ], [ "HistoryRetentionPeriodUnit", "Defines the time unit for history retention period (DAYS, WEEKS, MONTHS, or YEARS).\r\nUse this with HistoryRetentionPeriod to control how long temporal table history is preserved before automatic deletion.", "", false, "false", "", "" ], [ "DwTableDistribution", "Specifies the distribution strategy for data warehouse tables (HASH, ROUND_ROBIN, or REPLICATE).\r\nChoose HASH for large fact tables, ROUND_ROBIN for staging tables, or REPLICATE for small dimension tables in analytical workloads.", "", false, "false", "", "" ], [ "RejectedRowLocation", "Specifies where to store rows that exceed reject thresholds when querying external tables.\r\nDefine a location for storing problematic rows for later analysis and data quality troubleshooting.", "", false, "false", "", "" ], [ "OnlineHeapOperation", "Enables online operations for heap tables during index creation or rebuilding.\r\nUse this to minimize blocking and maintain table availability during maintenance operations on tables without clustered indexes.", "", false, "false", "False", "" ], [ "LowPriorityMaxDuration", "Sets the maximum time in minutes for low-priority lock waits during online operations.\r\nSpecify how long online operations should wait for locks before taking alternative action to balance performance and availability.", "", false, "false", "0", "" ], [ "DataConsistencyCheck", "Enables data consistency validation during online index operations.\r\nUse this to ensure data integrity is maintained during concurrent modifications to tables undergoing maintenance operations.", "", false, "false", "False", "" ], [ "LowPriorityAbortAfterWait", "Defines the action to take when low-priority operations exceed their maximum wait duration.\r\nChoose how to handle lock conflicts: continue waiting, abort the operation, or kill blocking transactions.", "", false, "false", "", "" ], [ "MaximumDegreeOfParallelism", "Limits the number of processors used during table operations like index creation.\r\nSet this to control resource usage and prevent single operations from consuming all available CPU cores.", "", false, "false", "0", "" ], [ "IsNode", "Creates a node table for SQL Server 2017+ Graph Database functionality.\r\nEnable this when building graph databases where the table will store entities and their properties for relationship modeling.", "", false, "false", "False", "" ], [ "IsEdge", "Creates an edge table for SQL Server 2017+ Graph Database functionality to store relationships.\r\nEnable this when building graph databases where the table will store connections between node tables.", "", false, "false", "False", "" ], [ "IsVarDecimalStorageFormatEnabled", "Enables variable-length decimal storage format to reduce storage space for decimal and numeric columns.\r\nUse this for tables with many decimal columns containing leading zeros or small values to optimize storage efficiency.", "", false, "false", "False", "" ], [ "Passthru", "Returns the T-SQL script for table creation instead of executing it immediately.\r\nUse this to review, modify, or save table creation scripts before deployment, or to generate scripts for version control.", "", false, "false", "False", "" ], [ "InputObject", "Accepts database objects piped from Get-DbaDatabase for creating tables across multiple databases.\r\nUse this in pipeline scenarios where you want to apply table creation to a filtered set of 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", "" ], [ "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", "Transfer", "Object" ], "CommandName": "New-DbaDbTransfer", "Name": "New-DbaDbTransfer", "Author": "Kirill Kravtsov (@nvarscar)", "Syntax": "New-DbaDbTransfer [[-SqlInstance] \u003cDbaInstanceParameter\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-DestinationSqlInstance] \u003cDbaInstanceParameter\u003e] [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString\u003e] [[-DestinationDatabase] \u003cString\u003e] [[-BatchSize] \u003cInt32\u003e] [[-BulkCopyTimeOut] \u003cInt32\u003e] [[-ScriptingOption] \u003cScriptingOptions\u003e] [[-InputObject] \u003cNamedSmoObject[]\u003e] [-CopyAllObjects] [[-CopyAll] \u003cString[]\u003e] [-SchemaOnly] [-DataOnly] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Transfer\nReturns a single configured SMO Transfer object that defines what database objects to copy and how to copy them to a destination SQL Server instance.\r\nThe returned object is not executed - you must call .TransferData() on it or pipe it to Invoke-DbaDbTransfer to perform the actual transfer operation.\nDefault properties configured based on parameters:\r\n- BatchSize: Number of rows to transfer in each batch (rows)\r\n- BulkCopyTimeOut: Timeout in seconds for bulk copy operations\r\n- CopyAllObjects: Boolean indicating if all transferable objects are included\r\n- CopyAll[ObjectType]: Individual boolean properties for each object type (CopyAllTables, CopyAllViews, CopyAllStoredProcedures, etc.)\r\n- Options: Scripting options controlling how objects are scripted (from -ScriptingOption parameter)\r\n- ObjectList: Collection of specific objects to transfer (populated from InputObject pipeline parameter)\r\n- DestinationServer: Target SQL Server instance name\r\n- DestinationDatabase: Target database name on destination instance\r\n- DestinationServerConnection: ServerConnection object configured for destination with SSL/TLS settings from source\r\n- DestinationLoginSecure: Boolean indicating if destination uses integrated security (True) or SQL authentication (False)\r\n- DestinationLogin: Username for SQL Server authentication on destination (only set if not using integrated security)\r\n- DestinationPassword: Password for SQL Server authentication on destination (only set if not using integrated security)\r\n- CopyData: Boolean indicating if table data will be copied (False when -SchemaOnly specified)\r\n- CopySchema: Boolean indicating if database object schema will be copied (False when -DataOnly specified)\nWhen -SchemaOnly is specified: CopyData property is set to False (schema only, no data)\r\nWhen -DataOnly is specified: CopySchema property is set to False (data only, assumes objects exist on destination)\nThe Transfer object maintains all SMO Transfer properties and can be further customized by modifying returned object properties before calling TransferData().", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaDbTransfer -SqlInstance sql1 -Destination sql2 -Database mydb -CopyAll Tables\nCreates a transfer object that, when invoked, would copy all tables from database sql1.mydb to sql2.mydb\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbTable -SqlInstance sql1 -Database MyDb -Table a, b, c | New-DbaDbTransfer -SqlInstance sql1 -Destination sql2 -Database mydb\nCreates a transfer object to copy specific tables from database sql1.mydb to sql2.mydb", "Description": "Returns a configured SMO Transfer object that defines what database objects to copy and how to copy them between SQL Server instances.\nThis function prepares the transfer configuration but does not execute the actual copy operation - you must call .TransferData() on the returned object or pipe it to Invoke-DbaDbTransfer to perform the transfer.\nUseful for database migrations, environment refreshes, or selective object deployment where you need to copy specific tables, views, stored procedures, users, or other database objects.\nSupports copying schema only, data only, or both, with configurable batch sizes and timeout values for large data transfers.", "Links": "https://dbatools.io/New-DbaDbTransfer", "Synopsis": "Creates a configured SMO Transfer object for copying database objects between SQL Server instances", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "Source SQL Server instance name.", "", 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", "", "" ], [ "DestinationSqlInstance", "Specifies the target SQL Server instance where database objects will be transferred. The function configures the SMO Transfer object to connect to this destination.\r\nYou must have appropriate permissions to create the specified objects on the target server.", "", false, "false", "", "" ], [ "DestinationSqlCredential", "Credentials for connecting to the destination SQL Server instance. Accepts PowerShell credential objects created with Get-Credential.\r\nOnly SQL Server authentication is supported for the destination connection. When not specified, uses Windows Authentication.", "", false, "false", "", "" ], [ "Database", "Specifies the source database containing the objects to transfer. This database must exist on the source SQL Server instance.\r\nUse this to define which database serves as the source for the transfer operation.", "", false, "false", "", "" ], [ "DestinationDatabase", "Specifies the target database where objects will be transferred. The database should already exist on the destination instance.\r\nWhen not specified, uses the same database name as the source database.", "", false, "false", "$Database", "" ], [ "BatchSize", "Sets the number of rows to transfer in each batch during data copy operations. Controls memory usage and transaction log growth on the destination.\r\nLarger batch sizes improve performance but use more memory. Smaller batches reduce memory pressure but may slow transfer speed. Default is 50,000 rows.", "", false, "false", "50000", "" ], [ "BulkCopyTimeOut", "Sets the timeout in seconds for each bulk copy operation before it times out and fails. Prevents long-running transfers from hanging indefinitely.\r\nIncrease this value when transferring large tables or working with slower network connections. Default is 5000 seconds.", "", false, "false", "5000", "" ], [ "ScriptingOption", "Provides custom scripting options that control how database objects are scripted during the transfer. Must be created using New-DbaScriptingOption.\r\nUse this to control object scripting behavior such as including permissions, check constraints, triggers, or indexes in the transfer.", "", false, "false", "", "" ], [ "InputObject", "Accepts specific database objects (tables, views, stored procedures, etc.) to transfer via pipeline input from other dbatools commands.\r\nUse this to transfer only selected objects instead of entire object types. Objects must be SMO objects from the source database.", "", false, "true (ByValue)", "", "" ], [ "CopyAllObjects", "Includes all transferable database objects in the transfer operation, regardless of object type. This is the broadest transfer scope available.\r\nUse this for complete database migrations or when you need to transfer everything except system objects and data.", "", false, "false", "False", "" ], [ "CopyAll", "Specifies which types of database objects to include in the transfer operation. You can specify multiple object types to transfer specific categories.\r\nCommon values include Tables, Views, StoredProcedures, UserDefinedFunctions, Users, and Roles for typical database migrations. Use this for selective transfers instead of copying all objects.\r\nAllowed values: FullTextCatalogs, FullTextStopLists, SearchPropertyLists, Tables, Views, StoredProcedures, UserDefinedFunctions, UserDefinedDataTypes, UserDefinedTableTypes, PlanGuides, Rules, \r\nDefaults, Users, Roles, PartitionSchemes, PartitionFunctions, XmlSchemaCollections, SqlAssemblies, UserDefinedAggregates, UserDefinedTypes, Schemas, Synonyms, Sequences, DatabaseTriggers, \r\nDatabaseScopedCredentials, ExternalFileFormats, ExternalDataSources, Logins, ExternalLibraries", "", false, "false", "", "FullTextCatalogs,FullTextStopLists,SearchPropertyLists,Tables,Views,StoredProcedures,UserDefinedFunctions,UserDefinedDataTypes,UserDefinedTableTypes,PlanGuides,Rules,Defaults,Users,Roles,PartitionSchemes,PartitionFunctions,XmlSchemaCollections,SqlAssemblies,UserDefinedAggregates,UserDefinedTypes,Schemas,Synonyms,Sequences,DatabaseTriggers,DatabaseScopedCredentials,ExternalFileFormats,ExternalDataSources,Logins,ExternalLibraries" ], [ "SchemaOnly", "Transfers only the structure and definitions of database objects without copying any table data. Creates empty tables with all constraints, indexes, and triggers.\r\nUse this for setting up database structure in development environments or when data will be loaded separately.", "", false, "false", "False", "" ], [ "DataOnly", "Transfers only table data without creating or modifying database object structures. Assumes that tables and other objects already exist on the destination.\r\nUse this for data refresh scenarios where the database schema is already in place and you only need to update the data.", "", 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": [ "Database", "User" ], "CommandName": "New-DbaDbUser", "Name": "New-DbaDbUser", "Author": "Frank Henninger (@osiris687) | Andreas Jordan (@JordanOrdix), ordix.de", "Syntax": "New-DbaDbUser [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cString[]\u003e] [-ExcludeDatabase \u003cString[]\u003e] [-IncludeSystem] -User \u003cString\u003e -ExternalProvider [-DefaultSchema \u003cString\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nNew-DbaDbUser [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cString[]\u003e] [-ExcludeDatabase \u003cString[]\u003e] [-IncludeSystem] -User \u003cString\u003e -SecurePassword \u003cSecureString\u003e [-DefaultSchema \u003cString\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nNew-DbaDbUser [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cString[]\u003e] [-ExcludeDatabase \u003cString[]\u003e] [-IncludeSystem] -User \u003cString\u003e [-DefaultSchema \u003cString\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nNew-DbaDbUser [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cString[]\u003e] [-ExcludeDatabase \u003cString[]\u003e] [-IncludeSystem] [-User \u003cString\u003e] -Login \u003cString\u003e [-DefaultSchema \u003cString\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.User\nReturns one User object for each user created, with one object per database when creating users in 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- Database: The database name where the user was created\r\n- Name: The name of the created database user\r\n- LoginType: Type of login this user is based on (WindowsLogin, SqlLogin, Certificate, AsymmetricKey, etc.)\r\n- Login: The login name the user is mapped to (null for contained users or external provider users)\r\n- AuthenticationType: Authentication type used (SqlLogin for SQL authenticated, WindowsLogin, Certificate, AsymmetricKey, ExternalUser for AAD, None for NoLogin users)\r\n- DefaultSchema: The default schema for this user (configured via -DefaultSchema parameter, defaults to \u0027dbo\u0027)\nAdditional properties available from SMO User object (via Select-Object *):\r\n- ID: Object ID of the user\r\n- Owner: Principal that owns this user\r\n- State: Current object state (Existing, Creating, Pending, Dropping)\r\n- Urn: Unified Resource Name for the object\r\n- Properties: Collection of object properties\nConditional properties based on user type:\r\n- When created with -Login parameter: User has a login property set to the mapped login\r\n- When created with -SecurePassword parameter: User is a contained database user with no login mapping\r\n- When created with -ExternalProvider switch: User is an Azure AD external provider user with AuthenticationType = ExternalUser\nOutput quantity: One object per user per database. When creating the same user in multiple databases (via -Database parameter accepting multiple values), one object is returned per database with the \r\nsame user name but different Database property values.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaDbUser -SqlInstance sqlserver2014 -Database DB1 -Login user1\nCreates a new sql user named user1 for the login user1 in the database DB1.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaDbUser -SqlInstance sqlserver2014 -Database DB1 -User user1\nCreates a new sql user named user1 without login in the database DB1.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eNew-DbaDbUser -SqlInstance sqlserver2014 -Database DB1 -User user1 -Login login1\nCreates a new sql user named user1 for the login login1 in the database DB1.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eNew-DbaDbUser -SqlInstance sqlserver2014 -Database DB1 -User user1 -Login Login1 -DefaultSchema schema1\nCreates a new sql user named user1 for the login login1 in the database DB1 and specifies the default schema to be schema1.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eNew-DbaDbUser -SqlInstance sqlserver2014 -Database DB1 -User \"claudio@********.onmicrosoft.com\" -ExternalProvider\nCreates a new sql user named \u0027claudio@********.onmicrosoft.com\u0027 mapped to Azure Active Directory (AAD) in the database DB1.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eNew-DbaDbUser -SqlInstance sqlserver2014 -Database DB1 -Username user1 -Password (ConvertTo-SecureString -String \"DBATools\" -AsPlainText -Force)\nCreates a new contained sql user named user1 in the database DB1 with the password specified.", "Description": "Creates database users across one or more databases, supporting multiple authentication types including traditional SQL login mapping, contained users with passwords, and Azure Active Directory external provider authentication. This command handles the common DBA task of provisioning database access without requiring manual T-SQL scripts for each database. You can create users mapped to existing SQL logins, standalone contained users for partially contained databases, or Azure AD users for cloud environments. The function automatically validates that specified logins and schemas exist before attempting user creation.", "Links": "https://dbatools.io/New-DbaDbUser", "Synopsis": "Creates database users with support for SQL logins, contained users, and Azure AD authentication.", "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 create the user in. Accepts multiple database names separated by commas.\r\nIf not specified, the user will be created in all user databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific databases from user creation when processing all databases on an instance.\r\nUse this to skip databases where you don\u0027t want the user created, such as read-only or archived databases.", "", false, "false", "", "" ], [ "IncludeSystem", "Creates the user in system databases (master, model, msdb, tempdb) in addition to user databases.\r\nTypically used when creating maintenance or administrative users that need access to system databases.", "", false, "false", "False", "" ], [ "User", "Sets the name of the database user to be created. Required for contained users, external provider users, and users without logins.\r\nIf not specified when using -Login, the user name will match the login name.", "Username", true, "false", "", "" ], [ "Login", "Maps the database user to an existing SQL Server login for authentication.\r\nThe login must already exist on the instance before creating the user.", "", true, "false", "", "" ], [ "SecurePassword", "If we need to pass a password to the command, we always use the type securestring and name the parameter SecurePassword. Here we only use the alias for backwords compatibility.", "Password", true, "false", "", "" ], [ "ExternalProvider", "Creates a user for Azure Active Directory authentication in Azure SQL databases or SQL Server with AAD integration.\r\nThe User parameter should contain the full AAD principal name (user@domain.com or groupname).", "", true, "false", "False", "" ], [ "DefaultSchema", "Sets the default schema that will be used when the user creates objects without specifying a schema.\r\nDefaults to \u0027dbo\u0027 if not specified. The schema must already exist in the target database.", "", false, "false", "dbo", "" ], [ "Force", "Drops and recreates the user if it already exists in the database.\r\nUse this when you need to reset a user\u0027s properties or when automation scripts need to ensure a clean user state.", "", 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": [ "Community", "GlennBerry", "Notebooks", "AzureDataStudio" ], "CommandName": "New-DbaDiagnosticAdsNotebook", "Name": "New-DbaDiagnosticAdsNotebook", "Author": "Gianluca Sartori (@spaghettidba)", "Syntax": "New-DbaDiagnosticAdsNotebook [[-SqlInstance] \u003cDbaInstanceParameter\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-TargetVersion] \u003cString\u003e] [-Path] \u003cString\u003e [-IncludeDatabaseSpecific] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.IO.FileInfo\nReturns the file information object for the created Jupyter Notebook (.ipynb) file. The file contains Glenn Berry\u0027s SQL Server diagnostic queries formatted as executable cells in a Jupyter Notebook \r\nthat can be opened and run in Azure Data Studio.\nProperties:\r\n- FullName: The complete file path where the notebook was created\r\n- Name: The filename of the notebook (.ipynb file)\r\n- DirectoryName: The directory path where the notebook is located\r\n- Length: The file size in bytes\r\n- CreationTime: DateTime when the notebook file was created\r\n- LastWriteTime: DateTime when the notebook file was last modified", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaDiagnosticAdsNotebook -SqlInstance localhost -Path c:\\temp\\myNotebook.ipynb\nCreates a new Jupyter Notebook named \"myNotebook\" based on the version of diagnostic queries found at localhost\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaDiagnosticAdsNotebook -TargetVersion 2016SP2 -Path c:\\temp\\myNotebook.ipynb\nCreates a new Jupyter Notebook named \"myNotebook\" based on the version \"2016SP2\" of diagnostic queries\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eNew-DbaDiagnosticAdsNotebook -TargetVersion 2017 -Path c:\\temp\\myNotebook.ipynb -IncludeDatabaseSpecific\nCreates a new Jupyter Notebook named \"myNotebook\" based on the version \"2017\" of diagnostic queries, including database-specific queries", "Description": "Converts Glenn Berry\u0027s well-known SQL Server diagnostic queries into a Jupyter Notebook (.ipynb) file that can be opened and executed in Azure Data Studio. The function automatically detects your SQL Server version or accepts a target version parameter, then creates a notebook with version-specific diagnostic queries formatted as executable cells. Each query includes descriptive markdown explaining what it measures and why it\u0027s useful for performance troubleshooting and health monitoring.", "Links": "https://dbatools.io/New-DbaDiagnosticAdsNotebook", "Synopsis": "Generates a Jupyter Notebook containing Glenn Berry\u0027s SQL Server diagnostic queries for Azure Data Studio", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. Defaults to the default instance on localhost.", "", 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", "", "" ], [ "TargetVersion", "Specifies the SQL Server version to generate diagnostic queries for when not connecting to a live instance. Use this when creating notebooks for offline analysis or different environments than your \r\ncurrent connection.\r\nMust be one of \"2005\", \"2008\", \"2008R2\", \"2012\", \"2014\", \"2016\", \"2016SP2\", \"2017\", \"2019\", \"2022\", \"AzureSQLDatabase\". Cannot be used together with SqlInstance parameter.", "", false, "false", "", "2005,2008,2008R2,2012,2014,2016,2016SP2,2017,2019,2022,AzureSQLDatabase" ], [ "Path", "Specifies the full file path where the Jupyter Notebook (.ipynb file) will be created. The directory must exist and you must have write permissions to the location.\r\nThe generated notebook can be opened in Azure Data Studio or any Jupyter-compatible environment for executing Glenn Berry\u0027s diagnostic queries.", "", true, "false", "", "" ], [ "IncludeDatabaseSpecific", "Includes database-level diagnostic queries in addition to the default instance-level queries. These queries examine database-specific performance metrics, index usage, and database settings.\r\nUse this when you need detailed analysis of individual databases rather than just server-wide diagnostics. Defaults to $false.", "", 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": [ "Storage", "Path", "Directory", "Folder" ], "CommandName": "New-DbaDirectory", "Name": "New-DbaDirectory", "Author": "Stuart Moore", "Syntax": "New-DbaDirectory [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-Path] \u003cString\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance specified in -SqlInstance, providing the directory creation status for each instance.\nProperties:\r\n- Server: The SQL Server instance name that was targeted for directory creation\r\n- Path: The full directory path that was created on the SQL Server machine\r\n- Created: Boolean ($true or $false) indicating whether the directory was successfully created\nThe function only returns output if the path does not already exist and the ShouldProcess operation is confirmed (when -WhatIf is not specified or user confirms the action).", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaDirectory -SqlInstance sqlcluster -Path L:\\MSAS12.MSSQLSERVER\\OLAP\nIf the SQL Server instance sqlcluster can create the path L:\\MSAS12.MSSQLSERVER\\OLAP it will do and return $true, if not it will return $false.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$credential = Get-Credential\nPS C:\\\u003e New-DbaDirectory -SqlInstance sqlcluster -SqlCredential $credential -Path L:\\MSAS12.MSSQLSERVER\\OLAP\nIf the SQL Server instance sqlcluster can create the path L:\\MSAS12.MSSQLSERVER\\OLAP it will do and return $true, if not it will return $false. Uses a SqlCredential to connect", "Description": "Creates directories on local or remote SQL Server machines by executing the xp_create_subdir extended stored procedure. This is particularly useful when you need to create backup directories, log shipping paths, or database file locations where the SQL Server service account needs to have access. The function checks if the path already exists before attempting creation and returns the success status for each operation.", "Links": "https://dbatools.io/New-DbaDirectory", "Synopsis": "Creates directories on SQL Server machines using the SQL Server service account", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The SQL Server you want to run the test on.", "", true, "false", "", "" ], [ "Path", "Specifies the full directory path to create on the SQL Server machine using the SQL Server service account.\r\nUse this when you need to create backup directories, database file paths, or log shipping folders where SQL Server needs access.\r\nThe function will check if the path already exists and skip creation if it does.", "", 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", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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": "Endpoint", "CommandName": "New-DbaEndpoint", "Name": "New-DbaEndpoint", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "New-DbaEndpoint [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Name] \u003cString\u003e] [[-Type] \u003cString\u003e] [[-Protocol] \u003cString\u003e] [[-Role] \u003cString\u003e] [[-EndpointEncryption] \u003cString\u003e] [[-EncryptionAlgorithm] \u003cString\u003e] [[-AuthenticationOrder] \u003cString\u003e] [[-Certificate] \u003cString\u003e] [[-IPAddress] \u003cIPAddress\u003e] [[-Port] \u003cInt32\u003e] [[-SslPort] \u003cInt32\u003e] [[-Owner] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.EndPoint\nReturns one EndPoint object for each endpoint successfully created. The endpoint object represents the newly created SQL Server endpoint configured with the specified type, protocol, and \r\ncommunication settings.\nDefault display properties (via Select-DefaultView from Get-DbaEndpoint):\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 endpoint (e.g., hadr_endpoint for DatabaseMirroring)\r\n- Type: The endpoint type (DatabaseMirroring, ServiceBroker, Soap, TSql)\r\n- Protocol: The communication protocol (Tcp, NamedPipes, Http, Via, SharedMemory)\r\n- Owner: The SQL Server login that owns the endpoint\r\n- IsAdminOnly: Boolean indicating if the endpoint is restricted to administrators only\nAdditional properties available (from SMO EndPoint object):\r\n- EndpointType: The type of endpoint (same as Type)\r\n- ProtocolType: The protocol type enumeration value\r\n- Parent: Reference to the parent Server object\r\n- State: The current state of the endpoint object (Existing, Creating, Pending, etc.)\r\n- Urn: The Uniform Resource Name for the endpoint\r\n- Protocol: The Protocol object containing TCP, HTTP, Named Pipes configuration details\r\n- Payload: The Payload object containing endpoint-specific configuration (DatabaseMirroring, ServiceBroker, Soap, TSql)\nAll properties from the base SMO EndPoint object are accessible using Select-Object * even though only default properties are displayed without that cmdlet.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaEndpoint -SqlInstance localhost\\sql2017 -Type DatabaseMirroring\nCreates a database mirroring endpoint on localhost\\sql2017 which using the default port\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaEndpoint -SqlInstance localhost\\sql2017 -Type DatabaseMirroring -Port 5055\nCreates a database mirroring endpoint on localhost\\sql2017 which uses alternative port 5055\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eNew-DbaEndpoint -SqlInstance localhost\\sql2017 -Type DatabaseMirroring -IPAddress 192.168.0.15 -Port 5055\nCreates a database mirroring endpoint on localhost\\sql2017 which binds only on ipaddress 192.168.0.15 and port 5055", "Description": "Creates SQL Server endpoints that enable communication between instances for high availability features like availability groups and database mirroring. Database mirroring endpoints are the most common type, required for setting up availability groups and database mirroring partnerships. The function also supports Service Broker endpoints for message queuing, SOAP endpoints for web services, and T-SQL endpoints for remote connections. Automatically generates TCP ports if not specified and handles encryption settings to ensure secure communication between SQL Server instances.", "Links": "https://dbatools.io/New-DbaEndpoint", "Synopsis": "Creates SQL Server endpoints for database mirroring, Service Broker, SOAP, or T-SQL communication.", "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", "", "" ], [ "Name", "Specifies the name for the new endpoint. Defaults to hadr_endpoint for DatabaseMirroring endpoints.\r\nRequired when creating ServiceBroker, Soap, or TSql endpoints as these need unique names for identification.", "Endpoint", false, "false", "", "" ], [ "Type", "Defines the endpoint type to create. DatabaseMirroring endpoints enable availability groups and database mirroring.\r\nServiceBroker enables message queuing, Soap creates web service endpoints, and TSql allows remote connections. Defaults to DatabaseMirroring.", "", false, "false", "DatabaseMirroring", "DatabaseMirroring,ServiceBroker,Soap,TSql" ], [ "Protocol", "Sets the communication protocol for the endpoint. TCP is standard for database mirroring and availability groups.\r\nUse Http for SOAP endpoints, NamedPipes for local connections, or SharedMemory for same-machine communication. Defaults to Tcp.", "", false, "false", "Tcp", "Tcp,NamedPipes,Http,Via,SharedMemory" ], [ "Role", "Determines the database mirroring role this endpoint can serve. All allows the instance to act as principal, mirror, or witness.\r\nPartner restricts to principal/mirror roles only, Witness allows witness-only, None disables mirroring roles. Defaults to All.", "", false, "false", "All", "All,None,Partner,Witness" ], [ "EndpointEncryption", "Controls whether encryption is enforced for endpoint connections. Required forces all connections to use encryption.\r\nSupported allows both encrypted and unencrypted connections, Disabled prevents encryption. Defaults to Required for security.", "", false, "false", "Required", "Disabled,Required,Supported" ], [ "EncryptionAlgorithm", "Sets the encryption algorithm used to secure endpoint communications. AES provides the strongest security.\r\nRC4 options are available for backward compatibility but are less secure. Use None only when encryption is disabled. Defaults to Aes.", "", false, "false", "Aes", "Aes,AesRC4,None,RC4,RC4Aes" ], [ "AuthenticationOrder", "Defines the authentication methods and their priority order for endpoint connections. Negotiate automatically chooses the best available method.\r\nUse certificate options when requiring certificate-based authentication, or specific methods like Kerberos for domain environments. Defaults to Negotiate.", "", false, "false", "", "Certificate,CertificateKerberos,CertificateNegotiate,CertificateNtlm,Kerberos,KerberosCertificate,Negotiate,NegotiateCertificate,Ntlm,NtlmCertificate" ], [ "Certificate", "Name of a database certificate to use for endpoint authentication instead of Windows authentication.\r\nThe certificate must already exist in the master database and provides certificate-based authentication for enhanced security.", "", false, "false", "", "" ], [ "IPAddress", "Sets which IP address the endpoint listens on for incoming connections. Use 0.0.0.0 to listen on all available interfaces.\r\nSpecify a particular IP address to restrict connections to that interface only, useful for multi-homed servers. Defaults to 0.0.0.0 (all interfaces).", "", false, "false", "0.0.0.0", "" ], [ "Port", "Specifies the TCP port number for the endpoint to listen on. Auto-generates a port starting from 5022 if not specified.\r\nUse this when you need a specific port for firewall rules or standardization across instances.", "", false, "false", "0", "" ], [ "SslPort", "Sets the SSL port number for HTTPS endpoints when using HTTP protocol. Only applicable for Soap endpoints using HTTPS.\r\nRequired when creating secure web service endpoints that need encrypted communication over HTTP.", "", false, "false", "0", "" ], [ "Owner", "Sets the SQL Server login that owns the endpoint. The owner has full control permissions on the endpoint.\r\nDefaults to the sa account if available, otherwise uses the current connection\u0027s login for ownership.", "", 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": [ "Network", "Connection", "Firewall" ], "CommandName": "New-DbaFirewallRule", "Name": "New-DbaFirewallRule", "Author": "Andreas Jordan (@JordanOrdix), ordix.de", "Syntax": "New-DbaFirewallRule [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-Credential] \u003cPSCredential\u003e] [[-Type] \u003cString[]\u003e] [[-RuleType] \u003cString\u003e] [[-Configuration] \u003cHashtable\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per firewall rule created, providing comprehensive details about the rule configuration and creation status.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The name of the computer where the firewall rule was created\r\n- InstanceName: The SQL Server instance name; $null for Browser rules\r\n- SqlInstance: The full SQL Server instance name (computer\\instance); $null for Browser rules\r\n- DisplayName: The display name of the firewall rule (e.g., \u0027SQL Server default instance\u0027, \u0027SQL Server Browser\u0027)\r\n- Type: The type of firewall rule created (Engine, Browser, DAC, DatabaseMirroring)\r\n- Successful: Boolean indicating if the rule creation was successful\r\n- Status: Human-readable status message describing the outcome (e.g., \u0027The rule was successfully created.\u0027, \u0027The desired rule already exists. Use -Force to remove and recreate the rule.\u0027)\r\n- Protocol: The protocol type of the rule (TCP, UDP, or Any)\r\n- LocalPort: The TCP/UDP port number for port-based rules; $null for Program-based rules\r\n- Program: The executable program path for Program-based rules; $null for Port-based rules\nAdditional properties available (using Select-Object *):\r\n- Name: The internal name of the firewall rule (same as DisplayName)\r\n- RuleConfig: Complete hashtable containing all New-NetFirewallRule parameters used to create the rule\r\n- Details: PSCustomObject containing remote command execution details with properties:\r\n - Successful: Boolean indicating overall success status\r\n - CimInstance: The CIM instance object returned by New-NetFirewallRule\r\n - Warning: Warning messages from rule creation (if any)\r\n - Error: Error messages from rule creation (if any)\r\n - Exception: Exception details if an error occurred (if any)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaFirewallRule -SqlInstance SRV1, SRV1\\TEST\nAutomatically configures the needed firewall rules for both the default instance and the instance named TEST on SRV1.\r\nBy default, creates program-based rules targeting the SQL Server executables, allowing the instances to work regardless of port configuration changes.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaFirewallRule -SqlInstance SRV1, SRV1\\TEST -RuleType Port\nCreates port-based firewall rules instead of the default program-based rules.\r\nThis creates traditional TCP/UDP port rules for the instances.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eNew-DbaFirewallRule -SqlInstance SRV1, SRV1\\TEST -Configuration @{ Profile = \u0027Domain\u0027 }\nAutomatically configures the needed firewall rules for both the default instance and the instance named TEST on SRV1,\r\nbut configures the firewall rule for the domain profile only.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eNew-DbaFirewallRule -SqlInstance SRV1\\TEST -Type Engine -Force -Confirm:$false\nCreates or recreates the firewall rule for the instance TEST on SRV1. Does not prompt for confirmation.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eNew-DbaFirewallRule -SqlInstance SQL01 -Type DatabaseMirroring\nCreates the firewall rule for database mirroring or Availability Groups on the default instance on SQL01 using the default port 5022.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eNew-DbaFirewallRule -SqlInstance SQL02 -Type DatabaseMirroring -Configuration @{ LocalPort = \u00275023\u0027 }\nCreates the firewall rule for database mirroring or Availability Groups on the default instance on SQL02 using the custom port 5023.", "Description": "Creates inbound Windows firewall rules for SQL Server instances, Browser service, and Dedicated Admin Connection (DAC) to allow network connectivity.\nThis automates the tedious post-installation task of configuring firewall access for SQL Server, eliminating the need to manually determine ports and create rules through Windows Firewall GUI or netsh commands.\n\nBy default, the function creates program-based firewall rules that target SQL Server executables (sqlservr.exe, sqlbrowser.exe).\nThis approach allows instances to work regardless of port configuration changes - named instances on different ports or default instances on non-standard ports are automatically allowed without needing to update firewall rules.\nAlternatively, you can use -RuleType Port to create traditional port-based firewall rules.\n\nThis is a wrapper around New-NetFirewallRule executed remotely on the target computer via Invoke-Command2.\nBoth DisplayName and Name are set to the same value to ensure unique rule identification and prevent duplicates.\nAll rules use the \"SQL Server\" group for easy management with Get-DbaFirewallRule.\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.\n\nWith -RuleType Program (default), the firewall rule for the instance itself will have the following configuration (parameters for New-NetFirewallRule):\n\n DisplayName = \u0027SQL Server default instance\u0027 or \u0027SQL Server instance \u003cInstanceName\u003e\u0027\n Name = \u0027SQL Server default instance\u0027 or \u0027SQL Server instance \u003cInstanceName\u003e\u0027\n Group = \u0027SQL Server\u0027\n Enabled = \u0027True\u0027\n Direction = \u0027Inbound\u0027\n Protocol = \u0027TCP\u0027\n Program = \u0027\u003cPath ending with MSSQL\\Binn\\sqlservr.exe\u003e\u0027\n\nWith -RuleType Port, the firewall rule for the instance itself will have the following configuration (parameters for New-NetFirewallRule):\n\n DisplayName = \u0027SQL Server default instance\u0027 or \u0027SQL Server instance \u003cInstanceName\u003e\u0027\n Name = \u0027SQL Server default instance\u0027 or \u0027SQL Server instance \u003cInstanceName\u003e\u0027\n Group = \u0027SQL Server\u0027\n Enabled = \u0027True\u0027\n Direction = \u0027Inbound\u0027\n Protocol = \u0027TCP\u0027\n LocalPort = \u0027\u003cPort\u003e\u0027\n\nWith -RuleType Program (default), the firewall rule for the SQL Server Browser will have the following configuration (parameters for New-NetFirewallRule):\n\n DisplayName = \u0027SQL Server Browser\u0027\n Name = \u0027SQL Server Browser\u0027\n Group = \u0027SQL Server\u0027\n Enabled = \u0027True\u0027\n Direction = \u0027Inbound\u0027\n Protocol = \u0027Any\u0027\n Program = \u0027\u003cPath ending with sqlbrowser.exe\u003e\u0027\n\nWith -RuleType Port, the firewall rule for the SQL Server Browser will have the following configuration (parameters for New-NetFirewallRule):\n\n DisplayName = \u0027SQL Server Browser\u0027\n Name = \u0027SQL Server Browser\u0027\n Group = \u0027SQL Server\u0027\n Enabled = \u0027True\u0027\n Direction = \u0027Inbound\u0027\n Protocol = \u0027UDP\u0027\n LocalPort = \u00271434\u0027\n\nThe firewall rule for the dedicated admin connection (DAC) will have the following configuration (parameters for New-NetFirewallRule):\n\n DisplayName = \u0027SQL Server default instance (DAC)\u0027 or \u0027SQL Server instance \u003cInstanceName\u003e (DAC)\u0027\n Name = \u0027SQL Server default instance (DAC)\u0027 or \u0027SQL Server instance \u003cInstanceName\u003e (DAC)\u0027\n Group = \u0027SQL Server\u0027\n Enabled = \u0027True\u0027\n Direction = \u0027Inbound\u0027\n Protocol = \u0027TCP\u0027\n LocalPort = \u0027\u003cPort\u003e\u0027 (typically 1434 for a default instance, but will be fetched from ERRORLOG)\n\nThe firewall rule for the DAC will only be created if the DAC is configured for listening remotely.\nUse `Set-DbaSpConfigure -SqlInstance SRV1 -Name RemoteDacConnectionsEnabled -Value 1` to enable remote DAC before running this command.\n\nThe firewall rule for database mirroring or Availability Groups will have the following configuration (parameters for New-NetFirewallRule):\n\n DisplayName = \u0027SQL Server default instance (DatabaseMirroring)\u0027 or \u0027SQL Server instance \u003cInstanceName\u003e (DatabaseMirroring)\u0027\n Name = \u0027SQL Server default instance (DatabaseMirroring)\u0027 or \u0027SQL Server instance \u003cInstanceName\u003e (DatabaseMirroring)\u0027\n Group = \u0027SQL Server\u0027\n Enabled = \u0027True\u0027\n Direction = \u0027Inbound\u0027\n Protocol = \u0027TCP\u0027\n LocalPort = \u00275022\u0027 (can be overwritten by using the parameter Configuration)", "Links": "https://dbatools.io/New-DbaFirewallRule", "Synopsis": "Creates Windows firewall rules for SQL Server instances to allow network connectivity", "Availability": "Windows, Linux, macOS", "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 firewall rule types to create for SQL Server network access.\r\nUse this when you need to create specific rules instead of the automatic detection behavior.\r\nValid values are Engine (SQL Server instance), Browser (SQL Server Browser service), DAC (Dedicated Admin Connection) and DatabaseMirroring (database mirroring or Availability Groups). When omitted, \r\nthe function automatically creates Engine rules plus Browser rules for non-default ports and DAC rules when remote DAC is enabled.", "", false, "false", "", "Engine,Browser,DAC,DatabaseMirroring" ], [ "RuleType", "Specifies how firewall rules identify SQL Server traffic - either by targeting the executable program or by targeting specific TCP/UDP ports.\r\nValid values are Program (targets sqlservr.exe and sqlbrowser.exe executables) and Port (targets TCP/UDP port numbers).\r\nDefaults to Program, which allows instances to work regardless of port configuration changes (named instances on different ports, default instances on non-standard ports).\r\nUse Port when you need traditional port-based rules or when Program-based rules cannot be created.\r\nNote: DAC and DatabaseMirroring rules are always port-based regardless of this setting.", "", false, "false", "Program", "Program,Port" ], [ "Configuration", "Provides custom settings to override the default firewall rule configuration when calling New-NetFirewallRule.\r\nUse this when you need to restrict rules to specific network profiles (Domain, Private, Public) or modify other advanced firewall settings.\r\nCommon examples include @{Profile = \u0027Domain\u0027} to limit rules to domain networks only, or @{RemoteAddress = \u0027192.168.1.0/24\u0027} to restrict source IPs. The Name, DisplayName, and Group parameters are \r\nreserved and will be ignored if specified.", "", false, "false", "", "" ], [ "Force", "Forces recreation of firewall rules that already exist by deleting and recreating them.\r\nUse this when you need to update existing rules with new settings or when troubleshooting connectivity issues.\r\nWithout this switch, the function will warn you about existing rules and skip their 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", "" ], [ "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": [ "LinkedServer", "Server" ], "CommandName": "New-DbaLinkedServer", "Name": "New-DbaLinkedServer", "Author": "Adam Lancaster, github.com/lancasteradam", "Syntax": "New-DbaLinkedServer [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-LinkedServer] \u003cString\u003e] [[-ServerProduct] \u003cString\u003e] [[-Provider] \u003cString\u003e] [[-DataSource] \u003cString\u003e] [[-Location] \u003cString\u003e] [[-ProviderString] \u003cString\u003e] [[-Catalog] \u003cString\u003e] [[-SecurityContext] \u003cString\u003e] [[-SecurityContextRemoteUser] \u003cString\u003e] [[-SecurityContextRemoteUserPassword] \u003cSecureString\u003e] [[-InputObject] \u003cServer[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.LinkedServer\nReturns one LinkedServer object for each linked server successfully created on the target 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- Name: Name of the linked server\r\n- DataSource: Network name or connection string for the remote data source\r\n- ProviderName: OLE DB provider used to connect to the remote data source\r\n- ProductName: Product name of the remote data source\r\n- LinkedServerLogins: Number of login mappings configured for this linked server\nAdditional properties available (from SMO LinkedServer object):\r\n- Catalog: Default database or catalog name on the remote data source\r\n- Location: Physical location information for the data source\r\n- ProviderString: Additional connection properties passed to the OLE DB provider\r\n- RpcEnabled: Boolean indicating if remote procedure calls are enabled\r\n- RpcOut: Boolean indicating if outgoing RPC calls are allowed\r\n- ConnectTimeout: Connection timeout in seconds\r\n- QueryTimeout: Query timeout in seconds\r\n- IsPublisher: Boolean indicating if the linked server is a replication publisher\r\n- IsSubscriber: Boolean indicating if the linked server is a replication subscriber\r\n- IsDistributor: Boolean indicating if the linked server is a replication distributor", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaLinkedServer -SqlInstance sql01 -LinkedServer linkedServer1 -ServerProduct mssql -Provider MSOLEDBSQL -DataSource sql02\nCreates a new linked server named linkedServer1 on the sql01 instance. The link uses the Microsoft OLE DB Driver for SQL Server and is connected to the sql02 instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eConnect-DbaInstance -SqlInstance sql01 | New-DbaLinkedServer -LinkedServer linkedServer1 -ServerProduct mssql -Provider MSOLEDBSQL -DataSource sql02\nCreates a new linked server named linkedServer1 on the sql01 instance. The link uses the Microsoft OLE DB Driver for SQL Server and is connected to the sql02 instance. The sql01 instance is passed in \r\nvia pipeline.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eNew-DbaLinkedServer -SqlInstance sql01 -LinkedServer linkedServer1 -ServerProduct mssql -Provider MSOLEDBSQL -DataSource sql02 -SecurityContext CurrentSecurityContext\nCreates a new linked server named linkedServer1 on the sql01 instance. The link uses the Microsoft OLE DB Driver for SQL Server and is connected to the sql02 instance. Connections with logins that \r\nare not explicitly mapped to the remote server will use the current login\u0027s security context.", "Description": "Creates a new linked server on a SQL Server instance, allowing you to query remote databases and heterogeneous data sources as if they were local tables. This replaces the need to manually configure linked servers through SSMS or T-SQL scripts, while providing consistent security context management for unmapped logins. The function uses SMO to create the linked server definition and automatically configures the default security mapping based on your specified security context.", "Links": "https://dbatools.io/New-DbaLinkedServer", "Synopsis": "Creates a new linked server connection to remote SQL Server instances or heterogeneous data sources.", "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 for the new linked server object in SQL Server. This name must be unique on the SQL Server instance.\r\nUse a descriptive name that identifies the remote data source or its purpose to help other DBAs understand the connection.", "", false, "false", "", "" ], [ "ServerProduct", "Specifies the product name of the remote data source as it appears in sys.servers.product column.\r\nCommon values include \u0027SQL Server\u0027 for SQL Server instances, \u0027Oracle\u0027 for Oracle databases, or custom names for other OLE DB data sources.\r\nThis is primarily used for documentation and identification purposes in system views.", "", false, "false", "", "" ], [ "Provider", "Specifies the OLE DB provider used to connect to the remote data source.\r\nFor SQL Server, use \u0027MSOLEDBSQL\u0027 or \u0027MSOLEDBSQL19\u0027 (recommended) - SQL Server Native Client (SQLNCLI) is deprecated and removed from SQL Server 2022 and SSMS 19.\r\nOther common providers include \u0027OraOLEDB.Oracle\u0027 for Oracle or \u0027Microsoft.ACE.OLEDB.12.0\u0027 for Access databases.\r\nThe provider must be installed and registered on the SQL Server instance.", "", false, "false", "", "" ], [ "DataSource", "Specifies the network name or connection string for the remote data source.\r\nFor SQL Server instances, this is typically the server name or server\\instance format.\r\nFor other data sources, this could be a TNS name for Oracle or a file path for file-based sources.", "", false, "false", "", "" ], [ "Location", "Specifies the physical location information for the data source, typically used for documentation purposes.\r\nThis parameter is rarely required for most linked server configurations and is primarily used with specific OLE DB providers.\r\nLeave empty unless specifically required by your data source provider.", "", false, "false", "", "" ], [ "ProviderString", "Specifies additional connection properties passed directly to the OLE DB provider.\r\nUse this for provider-specific settings like connection pooling, timeouts, or authentication options that cannot be set through other parameters.\r\nThe format and available options depend on the specific OLE DB provider being used.", "", false, "false", "", "" ], [ "Catalog", "Specifies the default database or catalog name to use when connecting to the remote data source.\r\nFor SQL Server linked servers, this sets the default database context for queries that don\u0027t specify a database name.\r\nThis is equivalent to the \u0027Initial Catalog\u0027 connection property in connection strings.", "", false, "false", "", "" ], [ "SecurityContext", "Specifies the security context option found on the SSMS Security tab of the linked server. This is a separate configuration from the mapping of a local login to a remote login. It specifies the \r\nconnection behavior for a login that is not explicitly mapped. \u0027NoConnection\u0027 means that a connection will not be made. \u0027WithoutSecurityContext\u0027 means the connection will be made without using a \r\nsecurity context. \u0027CurrentSecurityContext\u0027 means the connection will be made using the login\u0027s current security context. \u0027SpecifiedSecurityContext\u0027 means the specified username and password will be \r\nused. The default value is \u0027WithoutSecurityContext\u0027. For more details see the Microsoft documentation for sp_addlinkedsrvlogin and also review the SSMS Security tab of the linked server.", "", false, "false", "WithoutSecurityContext", "NoConnection,WithoutSecurityContext,CurrentSecurityContext,SpecifiedSecurityContext" ], [ "SecurityContextRemoteUser", "Specifies the remote login name. This param is used when SecurityContext is set to SpecifiedSecurityContext. To map a local login to a remote login use New-DbaLinkedServerLogin.", "", false, "false", "", "" ], [ "SecurityContextRemoteUserPassword", "Specifies the remote login password. This param is used when SecurityContext is set to SpecifiedSecurityContext. To map a local login to a remote login use New-DbaLinkedServerLogin. NOTE: passwords \r\nare sent to the SQL Server instance in plain text. Check with your security administrator before using this parameter.", "", false, "false", "", "" ], [ "InputObject", "Accepts SQL Server SMO objects from the pipeline, typically from Connect-DbaInstance.\r\nThis allows you to create linked servers on multiple instances by piping server connections to this function.\r\nUse this when you need to create the same linked server configuration across multiple 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": [ "LinkedServer", "Server" ], "CommandName": "New-DbaLinkedServerLogin", "Name": "New-DbaLinkedServerLogin", "Author": "Adam Lancaster, github.com/lancasteradam", "Syntax": "New-DbaLinkedServerLogin [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-LinkedServer] \u003cString[]\u003e] [[-LocalLogin] \u003cString\u003e] [[-RemoteUser] \u003cString\u003e] [[-RemoteUserPassword] \u003cSecureString\u003e] [-Impersonate] [[-InputObject] \u003cLinkedServer[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.LinkedServerLogin\nReturns one LinkedServerLogin object for each newly created linked server login mapping.\r\nThe returned object represents the login mapping that was created, retrieved from Get-DbaLinkedServerLogin after creation.\nProperties include:\r\n- Name: The local SQL Server login name that was mapped\r\n- RemoteUser: The remote login name on the linked server (if credential mapping was used)\r\n- Impersonate: Boolean indicating whether impersonation is enabled (pass-through authentication)\r\n- Parent: Reference to the parent LinkedServer object\r\n- DateLastModified: Timestamp of when the login mapping was last modified\r\n- State: SMO object state (Existing, Creating, Pending, etc.)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaLinkedServerLogin -SqlInstance sql01 -LinkedServer linkedServer1 -LocalLogin localUser1 -RemoteUser remoteUser1 -RemoteUserPassword \u003cpassword\u003e\nCreates a new linked server login and maps the local login testuser1 to the remote login testuser2. This linked server login is created on the sql01 instance for the linkedServer1 linked server.\nNOTE: passwords are sent to the SQL Server instance in plain text. Check with your security administrator before using the command with the RemoteUserPassword parameter. View the documentation for \r\nsp_addlinkedsrvlogin for more details.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaLinkedServerLogin -SqlInstance sql01 -LinkedServer linkedServer1 -Impersonate\nCreates a mapping for all local logins on sql01 to connect using their own credentials to the linked server linkedServer1.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaLinkedServer -SqlInstance sql01 -LinkedServer linkedServer1 | New-DbaLinkedServerLogin -LinkedServer linkedServer1 -LocalLogin testuser1 -RemoteUser testuser2 -RemoteUserPassword \r\n\u003cpassword\u003e\nCreates a new linked server login and maps the local login testuser1 to the remote login testuser2. This linked server login is created on the sql01 instance for the linkedServer1 linked server. The \r\nlinkedServer1 instance is passed in via pipeline.\nNOTE: passwords are sent to the SQL Server instance in plain text. Check with your security administrator before using the command with the RemoteUserPassword parameter. View the documentation for \r\nsp_addlinkedsrvlogin for more details.", "Description": "Creates linked server login mappings that define how local SQL Server logins authenticate to remote servers during distributed queries. You can either map specific local logins to remote credentials or configure impersonation where local logins use their own credentials. This eliminates the need to hardcode passwords in applications that query across linked servers and provides centralized authentication management for cross-server operations.", "Links": "https://dbatools.io/New-DbaLinkedServerLogin", "Synopsis": "Creates authentication mappings between local and remote logins for linked server connections.", "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 of the linked server where the login mapping will be created. Required when using SqlInstance parameter.\r\nUse this to target specific linked servers when you have multiple configured on the same SQL instance.", "", false, "false", "", "" ], [ "LocalLogin", "Specifies the local SQL Server login that needs access to the linked server. Required in all scenarios.\r\nThis is the login name that exists on your local SQL instance and will be mapped to credentials on the remote server.", "", false, "false", "", "" ], [ "RemoteUser", "Specifies the login name to use on the remote server for authentication. Use with RemoteUserPassword to create explicit credential mapping.\r\nWhen omitted with Impersonate disabled, the mapping will fail unless the same login exists on both servers.", "", false, "false", "", "" ], [ "RemoteUserPassword", "Provides the password for the RemoteUser as a secure string. Required when mapping to a different remote login.\r\nWARNING: Passwords are transmitted to SQL Server in plain text - consult your security team before using in production environments.", "", false, "false", "", "" ], [ "Impersonate", "Enables pass-through authentication where local login credentials are used to authenticate to the remote server.\r\nUse this for trusted domain environments where the same login exists on both servers, eliminating the need to store remote passwords.", "", false, "false", "False", "" ], [ "InputObject", "Accepts linked server objects from Get-DbaLinkedServer pipeline input.\r\nUse this to efficiently configure login mappings across multiple linked servers retrieved from Get-DbaLinkedServer.", "", 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": "Login", "CommandName": "New-DbaLogin", "Name": "New-DbaLogin", "Author": "Kirill Kravtsov (@nvarscar)", "Syntax": "New-DbaLogin [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [[-Login] \u003cString[]\u003e] [-InputObject \u003cObject[]\u003e] [-LoginRenameHashtable \u003cHashtable\u003e] [[-SecurePassword] \u003cSecureString\u003e] [-MapToCredential \u003cString\u003e] [-Sid \u003cObject\u003e] [-DefaultDatabase \u003cString\u003e] [-Language \u003cString\u003e] [-PasswordExpirationEnabled] [-PasswordPolicyEnforced] [-PasswordMustChange] [-Disabled] [-DenyWindowsLogin] [-NewSid] [-ExternalProvider] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nNew-DbaLogin [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Login \u003cString[]\u003e] [-InputObject \u003cObject[]\u003e] [-LoginRenameHashtable \u003cHashtable\u003e] [-MapToAsymmetricKey \u003cString\u003e] [-MapToCredential \u003cString\u003e] [-Sid \u003cObject\u003e] [-Disabled] [-DenyWindowsLogin] [-NewSid] [-ExternalProvider] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nNew-DbaLogin [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Login \u003cString[]\u003e] [-InputObject \u003cObject[]\u003e] [-LoginRenameHashtable \u003cHashtable\u003e] [-MapToCertificate \u003cString\u003e] [-MapToCredential \u003cString\u003e] [-Sid \u003cObject\u003e] [-Disabled] [-DenyWindowsLogin] [-NewSid] [-ExternalProvider] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nNew-DbaLogin [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Login \u003cString[]\u003e] [-InputObject \u003cObject[]\u003e] [-LoginRenameHashtable \u003cHashtable\u003e] [-HashedPassword \u003cString\u003e] [-MapToCredential \u003cString\u003e] [-Sid \u003cObject\u003e] [-DefaultDatabase \u003cString\u003e] [-Language \u003cString\u003e] [-PasswordExpirationEnabled] [-PasswordPolicyEnforced] [-Disabled] [-DenyWindowsLogin] [-NewSid] [-ExternalProvider] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Login\nReturns one Login object for each login successfully created on the specified SQL Server instance(s). The Login object contains all configuration and security properties for the newly created login.\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, WindowsGroup, Certificate, AsymmetricKey, or ExternalUser)\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\nAdditional properties always available (from SMO Login object):\r\n- SidString: Hexadecimal string representation of the login\u0027s Security Identifier (SID)\r\n- Sid: Binary Security Identifier of the login\r\n- DefaultDatabase: The default database for the login when connecting\r\n- Language: The default language for the login\u0027s SQL Server session\r\n- LoginMode: The authentication mode for the login\r\n- PasswordExpirationEnabled: Boolean indicating if password expiration policy is enforced\r\n- PasswordPolicyEnforced: Boolean indicating if Windows password complexity requirements are enforced\r\n- DenyWindowsLogin: Boolean indicating if Windows Authentication is denied for this login\r\n- IsSystemObject: Boolean indicating if the login is a system object\r\n- IsExpired: Boolean indicating if the SQL Server login password has expired (SQL Server 2008+)\nAll properties from the base SMO Login object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaLogin -SqlInstance Server1,Server2 -Login Newlogin\nYou will be prompted to securely enter the password for a login [Newlogin]. The login would be created on servers Server1 and Server2 with default parameters.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$securePassword = Read-Host \"Input password\" -AsSecureString\nPS C:\\\u003e New-DbaLogin -SqlInstance Server1\\sql1 -Login Newlogin -SecurePassword $securePassword -PasswordPolicyEnforced -PasswordExpirationEnabled\nCreates a login on Server1\\sql1 with a predefined password. The login will have password and expiration policies enforced onto it.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaLogin -SqlInstance sql1 -Login Oldlogin | New-DbaLogin -SqlInstance sql1 -LoginRenameHashtable @{Oldlogin = \u0027Newlogin\u0027} -Force -NewSid -Disabled:$false\nCopies a login [Oldlogin] to the same instance sql1 with the same parameters (including password). New login will have a new sid, a new name [Newlogin] and will not be disabled. Existing login \r\n[Newlogin] will be removed prior to creation.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaLogin -SqlInstance sql1 -Login Login1,Login2 | New-DbaLogin -SqlInstance sql2 -PasswordPolicyEnforced -PasswordExpirationEnabled -DefaultDatabase tempdb -Disabled\nCopies logins [Login1] and [Login2] from instance sql1 to instance sql2, but enforces password and expiration policies for the new logins. New logins will also have a default database set to [tempdb] \r\nand will be created in a disabled state.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eNew-DbaLogin -SqlInstance sql1 -Login domain\\user\nCreates a new Windows Authentication backed login on sql1. The login will be part of the public server role.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eNew-DbaLogin -SqlInstance sql1 -Login domain\\user1, domain\\user2 -DenyWindowsLogin\nCreates two new Windows Authentication backed login on sql1. The logins would be denied from logging in.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eNew-DbaLogin -SqlInstance sql1 -Login \"claudio@********.onmicrosoft.com\" -ExternalProvider\nCreates a new login named \u0027claudio@********.onmicrosoft.com\u0027 mapped to Azure Active Directory (AAD).", "Description": "Creates new SQL Server logins supporting Windows Authentication, SQL Authentication, certificate-mapped, asymmetric key-mapped, and Azure AD authentication. Handles password policies, expiration settings, SID preservation for migration scenarios, and credential mapping. Can copy existing logins between instances while preserving or modifying security settings, making it essential for user provisioning, migration projects, and security standardization across environments.", "Links": "https://dbatools.io/New-DbaLogin", "Synopsis": "Creates SQL Server logins for authentication with configurable security policies and mapping options", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server(s)", "", 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", "", "" ], [ "Login", "Specifies the name or names of the logins to create. Accepts arrays for bulk login creation.\r\nUse domain\\username format for Windows Authentication logins, or simple names for SQL Server logins.", "Name,LoginName", false, "false", "", "" ], [ "InputObject", "Accepts login objects piped from Get-DbaLogin for copying existing logins to new instances.\r\nPreserves login properties including passwords, SIDs, and security settings from the source login.", "", false, "true (ByValue)", "", "" ], [ "LoginRenameHashtable", "Maps original login names to new names when piping login objects between instances.\r\nUse format @{\u0027OldLoginName\u0027 = \u0027NewLoginName\u0027} to rename logins during the copy process.", "Rename", false, "false", "", "" ], [ "SecurePassword", "Sets the password for SQL Server Authentication logins as a secure string object.\r\nRequired for new SQL logins unless using HashedPassword or copying from existing login objects.", "Password", false, "false", "", "" ], [ "HashedPassword", "Provides a pre-hashed password string for SQL Server logins, allowing password preservation during migrations.\r\nUse this when copying logins between instances while maintaining the original password hash.", "Hash,PasswordHash", false, "false", "", "" ], [ "MapToCertificate", "Associates the login with a specific certificate for certificate-based authentication.\r\nSpecify the certificate name that exists in the master database for secure key-based login access.", "", false, "false", "", "" ], [ "MapToAsymmetricKey", "Links the login to an asymmetric key for public key authentication scenarios.\r\nProvide the asymmetric key name from master database to enable cryptographic login authentication.", "", false, "false", "", "" ], [ "MapToCredential", "Connects the login to a server credential for accessing external resources or delegation scenarios.\r\nSpecify the credential name to associate with the login for extended authentication capabilities.", "", false, "false", "", "" ], [ "Sid", "Forces a specific Security Identifier (SID) for the login instead of generating a new one.\r\nEssential for login migrations to preserve user-database mappings and avoid orphaned users.", "", false, "false", "", "" ], [ "DefaultDatabase", "Sets the initial database context when the login connects to SQL Server.\r\nDefaults to master if not specified; useful for directing users to their primary working database.", "DefaultDB", false, "false", "", "" ], [ "Language", "Configures the default language for the login\u0027s SQL Server session messages and formatting.\r\nAffects date formats, error messages, and other locale-specific behaviors for the login.", "", false, "false", "", "" ], [ "PasswordExpirationEnabled", "Enforces Windows password expiration policy for SQL Server logins when combined with password policy enforcement.\r\nRequires PasswordPolicyEnforced to be enabled; helps maintain consistent password aging across systems.", "Expiration,CheckExpiration", false, "false", "False", "" ], [ "PasswordPolicyEnforced", "Applies Windows password complexity requirements to SQL Server logins including length and character variety.\r\nRecommended for security compliance; works with domain password policies when available.", "Policy,CheckPolicy", false, "false", "False", "" ], [ "PasswordMustChange", "Forces the user to set a new password on their first login attempt after account creation.\r\nAutomatically enables password policy and expiration enforcement as prerequisites for this security feature.", "MustChange", false, "false", "False", "" ], [ "Disabled", "Creates the login in a disabled state, preventing authentication until manually enabled.\r\nUseful for preparing accounts before users need access or temporarily suspending login capabilities.", "Disable", false, "false", "False", "" ], [ "DenyWindowsLogin", "Blocks Windows Authentication login access while preserving the login definition for future use.\r\nCreates the login but prevents actual authentication; often used for security policy enforcement.", "", false, "false", "False", "" ], [ "NewSid", "Generates fresh SIDs when copying logins to the same instance or when SID conflicts exist.\r\nPrevents SID collision errors during login duplication and ensures unique security identifiers.", "", false, "false", "False", "" ], [ "ExternalProvider", "Configures the login for Azure Active Directory authentication in Azure SQL Database or Managed Instance.\r\nUse with Azure AD user principal names or service principal names for cloud-integrated authentication.", "", false, "false", "False", "" ], [ "Force", "Removes any existing login with the same name before creating the new one.\r\nAllows overwriting existing logins without manual cleanup; use carefully to avoid unintended access 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": [ "repl", "Replication", "Script" ], "CommandName": "New-DbaReplCreationScriptOptions", "Name": "New-DbaReplCreationScriptOptions", "Author": "Jess Pomfret (@jpomfret), jesspomfret.com", "Syntax": "New-DbaReplCreationScriptOptions [[-Options] \u003cString[]\u003e] [-NoDefaults] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Replication.CreationScriptOptions\nReturns a CreationScriptOptions enum instance that encapsulates the selected replication schema options.\r\nThis object can be passed to Add-DbaReplArticle\u0027s CreationScriptOptions parameter to control which schema elements are replicated to subscribers.\nThe object represents a combination of zero or more schema option flags, including:\r\n- PrimaryObject: The table structure\r\n- CustomProcedures: Custom stored procedures\r\n- Identity: Identity column properties\r\n- KeepTimestamp: Timestamp columns\r\n- ClusteredIndexes: Clustered indexes\r\n- NonClusteredIndexes: Non-clustered indexes\r\n- DriPrimaryKey: Primary key constraints\r\n- DriForeignKeys: Foreign key constraints\r\n- DriUniqueKeys: Unique key constraints\r\n- CheckConstraints: Check constraints\r\n- Collation: Column-level collation\r\n- MarkReplicatedCheckConstraintsAsNotForReplication: Check constraints marked as not for replication\r\n- MarkReplicatedForeignKeyConstraintsAsNotForReplication: Foreign key constraints marked as not for replication\r\n- Schema: Database schema association\r\n- And 27+ additional replication schema options\nSee https://learn.microsoft.com/en-us/dotnet/api/microsoft.sqlserver.replication.creationscriptoptions for the complete list of available options.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\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 PublicationName = \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.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$cso = New-DbaReplCreationScriptOptions -Options ClusteredIndexes, Identity -NoDefaults\nPS C:\\\u003e $article = @{\r\n\u003e\u003e SqlInstance = \u0027mssql1\u0027\r\n\u003e\u003e Database = \u0027pubs\u0027\r\n\u003e\u003e PublicationName = \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 ClusteredIndexes and Identity options set, excludes default options.", "Description": "Creates a Microsoft.SqlServer.Replication.CreationScriptOptions object that controls which database objects and properties are included when replicating tables through SQL Server replication. This determines what gets scripted at the subscriber when articles are added to publications - things like indexes, constraints, triggers, and identity columns.\n\nBy default, includes the same options that SQL Server Management Studio uses when adding articles: primary objects, custom procedures, identity properties, timestamps, clustered indexes, primary keys, collation, unique keys, and constraint replication settings. Use -NoDefaults to start with a blank slate and specify only the options you want.\n\nThis object is typically used with Add-DbaReplArticle to precisely control what database schema elements are replicated to subscribers, avoiding common issues like missing indexes or constraints that can impact subscriber performance.\n\nSee https://learn.microsoft.com/en-us/dotnet/api/microsoft.sqlserver.replication.creationscriptoptions for more information", "Links": "https://dbatools.io/New-DbaReplCreationScriptOptions", "Synopsis": "Creates replication article creation script options for controlling which database objects are replicated", "Availability": "Windows, Linux, macOS", "Params": [ [ "Options", "Specifies which database object properties to include when creating replicated tables at subscribers. Controls what gets scripted beyond the basic table structure.\r\nUse this to add specific elements like NonClusteredIndexes, Statistics, CheckConstraints, or ForeignKeys that aren\u0027t included in the default set.\r\nCommon values include Statistics for performance, NonClusteredIndexes for query optimization, or Triggers for business logic replication.", "", false, "false", "", "" ], [ "NoDefaults", "Excludes the standard replication options that SQL Server Management Studio applies automatically when adding articles.\r\nUse this when you need precise control over which schema elements are replicated and want to avoid the default behavior.\r\nWithout this switch, includes PrimaryObject, CustomProcedures, Identity, KeepTimestamp, ClusteredIndexes, DriPrimaryKey, Collation, DriUniqueKeys, and constraint replication settings.", "", false, "false", "False", "" ] ] }, { "Tags": [ "repl", "Replication" ], "CommandName": "New-DbaReplPublication", "Name": "New-DbaReplPublication", "Author": "Jess Pomfret (@jpomfret), jesspomfret.com", "Syntax": "New-DbaReplPublication [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Database] \u003cString\u003e [-Name] \u003cString\u003e [-Type] \u003cString\u003e [[-LogReaderAgentCredential] \u003cPSCredential\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Replication.TransPublication or Microsoft.SqlServer.Replication.MergePublication\nReturns one publication object for each newly created publication. The returned object type depends on the publication type specified:\r\n- TransPublication for Transactional or Snapshot publications\r\n- MergePublication for Merge publications\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance where the publication was created\r\n- InstanceName: The SQL Server instance name\r\n- SQLInstance: The full SQL Server instance object\r\n- DatabaseName: The name of the database containing the publication\r\n- Name: The name of the publication\r\n- Type: The publication type (Transactional, Snapshot, or Merge)\r\n- Articles: Collection of articles defined in the publication\r\n- Subscriptions: Collection of subscriptions to this publication\nAdditional properties available from SMO publication objects:\r\n- Status: Current status of the publication (normal, inactive, etc.)\r\n- HasSubscriptions: Boolean indicating if the publication has active subscriptions\r\n- CreationDate: DateTime when the publication was created\r\n- SnapshotAgentExists: Boolean indicating if a Snapshot Agent job exists\r\n- LogReaderAgentExists: Boolean indicating if a Log Reader Agent job exists (transactional/snapshot only)\nAccess all properties using Select-Object * to view complete publication configuration details from the SMO object.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaReplPublication -SqlInstance mssql1 -Database Northwind -Name PubFromPosh -Type Transactional\nCreates a transactional publication called PubFromPosh for the Northwind database on mssql1\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaReplPublication -SqlInstance mssql1 -Database pubs -Name snapPub -Type Snapshot\nCreates a snapshot publication called snapPub for the pubs database on mssql1\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eNew-DbaReplPublication -SqlInstance mssql1 -Database pubs -Name mergePub -Type Merge\nCreates a merge publication called mergePub for the pubs database on mssql1", "Description": "Creates a new replication publication on a SQL Server instance that\u0027s already configured as a publisher. This function enables publishing on the specified database, creates necessary replication agents (Log Reader for transactional/snapshot, Snapshot Agent for all types), and establishes the publication object that defines what data will be replicated to subscribers.\n\nUse this command when setting up the publisher side of SQL Server replication to distribute data across multiple servers. The publication acts as a container for the articles (tables, views, stored procedures) you want to replicate. After creating the publication, you\u0027ll typically add articles using Add-DbaReplArticle and create subscriptions on target servers.\n\nhttps://learn.microsoft.com/en-us/sql/relational-databases/replication/publish/create-a-publication?view=sql-server-ver16", "Links": "https://dbatools.io/New-DbaReplPublication", "Synopsis": "Creates a SQL Server replication publication for transactional, snapshot, or merge replication", "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 the database where the publication will be created and which contains the objects to be replicated.\r\nThis database must already exist on the publisher instance and will be enabled for the specified replication type.", "", true, "false", "", "" ], [ "Name", "Sets the unique name for the publication within the database.\r\nUse a descriptive name that identifies the purpose or content of the publication, as this name will be referenced when creating subscriptions and managing replication.", "", true, "false", "", "" ], [ "Type", "Determines the replication method used for distributing data to subscribers.\r\nTransactional provides near real-time synchronization for frequently changing data, Snapshot creates point-in-time copies for less volatile data, and Merge allows bidirectional changes with conflict \r\nresolution.\r\nChoose based on your data synchronization requirements and network constraints.", "", true, "false", "", "Snapshot,Transactional,Merge" ], [ "LogReaderAgentCredential", "Specifies the Windows account credentials for the Log Reader Agent, which is required for Transactional and Snapshot replication types.\r\nThis agent reads the transaction log to identify changes for replication. Only needed when not running as sysadmin, as sysadmin members default to using the SQL Server Agent service account.\r\nUse a domain account with appropriate permissions to the publisher database and distributor.", "", 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": "New-DbaReplSubscription", "Name": "New-DbaReplSubscription", "Author": "Jess Pomfret (@jpomfret), jesspomfret.com", "Syntax": "New-DbaReplSubscription [-SqlInstance] \u003cDbaInstanceParameter\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString\u003e] [-SubscriberSqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SubscriberSqlCredential] \u003cPSCredential\u003e] [[-SubscriptionDatabase] \u003cString\u003e] [-PublicationName] \u003cString\u003e [[-SubscriptionSqlCredential] \u003cPSCredential\u003e] [-Type] \u003cString\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "None\nThis function creates replication subscriptions but does not return output objects. The function performs the following operations:\r\n- Validates or creates the subscription database on the subscriber instance\r\n- Creates necessary database schemas on the subscriber if needed\r\n- Configures Push or Pull subscription based on the -Type parameter\r\n- Initializes the subscription and creates synchronization agent jobs\nTo verify the subscription was created successfully, use Get-DbaReplSubscription with the same parameters:\r\nPS C:\\\u003e Get-DbaReplSubscription -SqlInstance $SqlInstance -Database $Database -PublicationName $PublicationName\nThis will return subscription objects showing:\r\n- ComputerName: The publisher server name\r\n- InstanceName: The publisher instance name\r\n- SqlInstance: The publisher instance in domain\\instance format\r\n- DatabaseName: The publishing database name\r\n- PublicationName: The publication name\r\n- Name: The subscription name\r\n- SubscriberName: The subscriber instance name\r\n- SubscriptionDBName: The subscription database name on subscriber\r\n- SubscriptionType: Push or Pull indicating subscription type", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaReplSubscription -SqlInstance sql2017 -Database pubs -SubscriberSqlInstance sql2019 -SubscriptionDatabase pubs -PublicationName testPub -Type Push\nCreates a push subscription from sql2017 to sql2019 for the pubs database.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaReplSubscription -SqlInstance sql2017 -Database pubs -SubscriberSqlInstance sql2019 -SubscriptionDatabase pubs -PublicationName testPub -Type Pull\nCreates a pull subscription from sql2017 to sql2019 for the pubs database.", "Description": "Creates push or pull subscriptions for SQL Server replication, connecting a subscriber instance to an existing publication on a publisher. This function handles the setup of transactional, snapshot, and merge replication subscriptions, automatically creating the subscription database and required schemas if they don\u0027t exist. Use this when you need to establish data replication for disaster recovery, reporting databases, or distributing data across multiple SQL Server instances without manually configuring subscription properties through SQL Server Management Studio.", "Links": "https://dbatools.io/New-DbaReplSubscription", "Synopsis": "Creates SQL Server replication subscriptions to distribute data from publisher to subscriber instances.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target publishing SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target publishing 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 source database on the publisher instance that contains the publication data to be replicated.\r\nThis database must already contain the publication you\u0027re subscribing to.", "", false, "false", "", "" ], [ "SubscriberSqlInstance", "The target SQL Server instance that will receive the replicated data from the publisher.\r\nCan specify multiple instances to create subscriptions on several subscribers simultaneously.", "", true, "false", "", "" ], [ "SubscriberSqlCredential", "Login credentials for connecting to the subscriber SQL Server instance. Accepts PowerShell credentials (Get-Credential).\r\nUse this when the subscriber requires different authentication than the publisher connection.\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "SubscriptionDatabase", "The destination database name on the subscriber instance where replicated data will be stored.\r\nIf this database doesn\u0027t exist, it will be automatically created with default settings.", "", false, "false", "", "" ], [ "PublicationName", "The name of the existing publication on the publisher database that you want to subscribe to.\r\nThis publication must already exist and be configured for the type of subscription you\u0027re creating.", "", true, "false", "", "" ], [ "SubscriptionSqlCredential", "SQL Server credentials used by the replication agents to connect to the subscriber database during synchronization.\r\nThese credentials are stored in the subscription properties and used by the Distribution or Merge Agent.", "", false, "false", "", "" ], [ "Type", "Specifies whether to create a Push or Pull subscription for data synchronization.\r\nPush subscriptions are managed by the publisher and typically used for high-frequency replication, while Pull subscriptions are managed by the subscriber.", "", true, "false", "", "Push,Pull" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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": [ "ResourcePool", "ResourceGovernor" ], "CommandName": "New-DbaRgResourcePool", "Name": "New-DbaRgResourcePool", "Author": "John McCall (@lowlydba), lowlydba.com", "Syntax": "New-DbaRgResourcePool -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-ResourcePool \u003cString[]\u003e] [-Type \u003cString\u003e] [-MaximumCpuPercentage \u003cInt32\u003e] [-MaximumMemoryPercentage \u003cInt32\u003e] [-SkipReconfigure] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nNew-DbaRgResourcePool -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-ResourcePool \u003cString[]\u003e] [-Type \u003cString\u003e] [-MinimumCpuPercentage \u003cInt32\u003e] [-MaximumCpuPercentage \u003cInt32\u003e] [-CapCpuPercentage \u003cInt32\u003e] [-MinimumMemoryPercentage \u003cInt32\u003e] [-MaximumMemoryPercentage \u003cInt32\u003e] [-MinimumIOPSPerVolume \u003cInt32\u003e] [-MaximumIOPSPerVolume \u003cInt32\u003e] [-SkipReconfigure] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nNew-DbaRgResourcePool -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-ResourcePool \u003cString[]\u003e] [-Type \u003cString\u003e] [-MaximumCpuPercentage \u003cInt32\u003e] [-MaximumMemoryPercentage \u003cInt32\u003e] [-MaximumProcesses \u003cInt32\u003e] [-SkipReconfigure] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.ResourcePool (for Internal pools)\r\nMicrosoft.SqlServer.Management.Smo.ExternalResourcePool (for External pools)\nReturns one resource pool object per pool created 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: The unique identifier for the resource pool\r\n- Name: The name of the resource pool\r\n- CapCpuPercentage: Absolute maximum CPU percentage limit (1-100)\r\n- IsSystemObject: Boolean indicating if the pool is a system-defined pool\r\n- MaximumCpuPercentage: Maximum CPU percentage during contention (1-100)\r\n- MaximumIopsPerVolume: Maximum IOPS per disk volume (0 = unlimited)\r\n- MaximumMemoryPercentage: Maximum memory percentage (1-100)\r\n- MinimumCpuPercentage: Guaranteed minimum CPU percentage (0-100)\r\n- MinimumIopsPerVolume: Guaranteed minimum IOPS per disk volume (0 = unlimited)\r\n- MinimumMemoryPercentage: Guaranteed minimum memory percentage (0-100)\r\n- WorkloadGroups: Collection of workload groups associated with this pool\nAll properties from the base SMO ResourcePool or ExternalResourcePool objects are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaRgResourcePool -SqlInstance sql2016 -ResourcePool \"poolAdmin\"\nCreates a new resource pool named \"poolAdmin\" for the instance sql2016.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaRgResourcePool -SqlInstance sql2012\\dev1 -ResourcePool \"poolDeveloper\" -SkipReconfigure\nCreates a new resource pool named \"poolDeveloper\" for the instance dev1 on sq2012.\r\nReconfiguration is skipped and the Resource Governor will not be able to use the new resource pool\r\nuntil it is reconfigured.", "Description": "Creates a new Resource Governor resource pool that defines specific limits for CPU, memory, and I/O resources on a SQL Server instance.\nResource pools let you isolate different workloads by setting minimum and maximum thresholds for system resources, preventing one application from consuming all server resources.\nSupports both Internal pools (for SQL Server workloads) and External pools (for external processes like R Services).\nThe Resource Governor is automatically reconfigured after pool creation unless you specify otherwise.", "Links": "https://dbatools.io/New-DbaRgResourcePool", "Synopsis": "Creates a Resource Governor resource pool to control CPU, memory, and I/O allocation for SQL Server workloads.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue, ByPropertyName)", "", "" ], [ "SqlCredential", "Credential object used to connect to the Windows server as a different user", "", false, "false", "", "" ], [ "ResourcePool", "Specifies the name of the resource pool to create. Pool names must be unique within the Resource Governor configuration.\r\nUse descriptive names that indicate the workload type, like \u0027ReportingPool\u0027 or \u0027BatchProcessingPool\u0027 for easier management.", "", false, "false", "", "" ], [ "Type", "Specifies whether to create an Internal pool for SQL Server workloads or External pool for external processes like R Services.\r\nInternal pools control database workloads, while External pools manage machine learning and external script execution resources.", "", false, "false", "Internal", "Internal,External" ], [ "MinimumCpuPercentage", "Sets the guaranteed minimum CPU percentage reserved for this pool during CPU contention. Ranges from 0-100, defaults to 0.\r\nUse this to ensure critical workloads always get their required CPU resources, even when the server is under heavy load.", "", false, "false", "0", "" ], [ "MaximumCpuPercentage", "Sets the maximum CPU percentage this pool can consume during CPU contention. Ranges from 1-100, defaults to 100.\r\nUse this to prevent runaway queries or resource-intensive workloads from monopolizing server CPU resources.", "", false, "false", "100", "" ], [ "CapCpuPercentage", "Creates an absolute hard limit on CPU usage that cannot be exceeded, regardless of available CPU capacity. Ranges from 1-100, defaults to 100.\r\nUnlike MaximumCpuPercentage, this enforces the limit even when CPU resources are idle. Requires SQL Server 2012 or later.", "", false, "false", "100", "" ], [ "MinimumMemoryPercentage", "Reserves a minimum percentage of server memory exclusively for this pool that cannot be shared with other pools. Ranges from 0-100, defaults to 0.\r\nUse this to guarantee memory allocation for critical workloads that require consistent memory availability.", "", false, "false", "0", "" ], [ "MaximumMemoryPercentage", "Sets the maximum percentage of total server memory this pool can consume. Ranges from 1-100, defaults to 100.\r\nUse this to prevent memory-intensive operations from consuming all available server memory and affecting other workloads.", "", false, "false", "100", "" ], [ "MinimumIOPSPerVolume", "Reserves a minimum number of IOPS per disk volume exclusively for this pool. Defaults to 0 (unlimited).\r\nUse this to guarantee disk I/O performance for workloads that require consistent data access speeds, such as OLTP systems.", "", false, "false", "0", "" ], [ "MaximumIOPSPerVolume", "Limits the maximum IOPS per disk volume that this pool can consume. Defaults to 0 (unlimited).\r\nUse this to prevent I/O-intensive workloads like batch processing or reporting from saturating disk subsystems.", "", false, "false", "0", "" ], [ "MaximumProcesses", "Sets the maximum number of external processes allowed to run concurrently in this External pool. Specify 0 for unlimited.\r\nUse this to control how many R or Python scripts can execute simultaneously, preventing external processes from overwhelming the server.", "", false, "false", "0", "" ], [ "SkipReconfigure", "Skips the automatic Resource Governor reconfiguration that makes the new pool active immediately after creation.\r\nUse this when creating multiple pools in succession to avoid repeated reconfigurations, then manually reconfigure once at the end.", "", false, "false", "False", "" ], [ "Force", "Automatically drops and recreates the resource pool if it already exists with the same name.\r\nUse this when you need to update an existing pool\u0027s configuration or ensure a clean pool 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", "" ], [ "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": [ "WorkloadGroup", "ResourceGovernor" ], "CommandName": "New-DbaRgWorkloadGroup", "Name": "New-DbaRgWorkloadGroup", "Author": "John McCall (@lowlydba), lowlydba.com", "Syntax": "New-DbaRgWorkloadGroup [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-WorkloadGroup] \u003cString[]\u003e] [[-ResourcePool] \u003cString\u003e] [[-ResourcePoolType] \u003cString\u003e] [[-Importance] \u003cString\u003e] [[-RequestMaximumMemoryGrantPercentage] \u003cInt32\u003e] [[-RequestMaximumCpuTimeInSeconds] \u003cInt32\u003e] [[-RequestMemoryGrantTimeoutInSeconds] \u003cInt32\u003e] [[-MaximumDegreeOfParallelism] \u003cInt32\u003e] [[-GroupMaximumRequests] \u003cInt32\u003e] [-SkipReconfigure] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.WorkloadGroup\nReturns one workload group object per workload group created within the specified resource pool(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: The unique identifier for the workload group\r\n- Name: The name of the workload group\r\n- ExternalResourcePoolName: Name of the external resource pool (for External pools only)\r\n- GroupMaximumRequests: Maximum number of concurrent requests allowed in this group (0 = unlimited)\r\n- Importance: Relative priority when competing for CPU resources (LOW, MEDIUM, or HIGH)\r\n- IsSystemObject: Boolean indicating if the workload group is a system-defined group\r\n- MaximumDegreeOfParallelism: Maximum number of processors for parallel execution (0 = server default)\r\n- RequestMaximumCpuTimeInSeconds: Maximum CPU time in seconds per request (0 = unlimited)\r\n- RequestMaximumMemoryGrantPercentage: Maximum memory grant percentage from the pool (1-100)\r\n- RequestMemoryGrantTimeoutInSeconds: Maximum wait time in seconds for memory grants (0 = unlimited)\nAll properties from the base SMO WorkloadGroup object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaRgWorkloadGroup -SqlInstance sql2016 -WorkloadGroup \"groupAdmin\" -ResourcePool \"poolAdmin\"\nCreates a workload group \"groupAdmin\" in the resource pool named \"poolAdmin\" for the instance sql2016.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaRgWorkloadGroup -SqlInstance sql2016 -WorkloadGroup \"groupAdmin\" -Force\nIf \"groupAdmin\" exists, it is dropped and re-created in the default resource pool for the instance sql2016.", "Description": "Creates a Resource Governor workload group within a specified resource pool, allowing you to define specific resource limits and priorities for different types of SQL Server workloads. Workload groups act as containers that classify incoming requests and apply resource policies like CPU time limits, memory grant percentages, and maximum degree of parallelism.\n\nThis is essential for DBAs managing multi-tenant environments, mixed workloads, or systems where you need to prevent resource-intensive queries from impacting critical applications. You can create separate workload groups for reporting queries, ETL processes, application traffic, or administrative tasks, each with tailored resource constraints.\n\nThe function supports both internal and external resource pools, handles existing workload group conflicts with optional force recreation, and automatically reconfigures Resource Governor to apply the changes immediately.", "Links": "https://dbatools.io/New-DbaRgWorkloadGroup", "Synopsis": "Creates a Resource Governor workload group within a specified resource pool to control SQL Server resource allocation.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", false, "true (ByValue, ByPropertyName)", "", "" ], [ "SqlCredential", "Credential object used to connect to the Windows server as a different user", "", false, "true (ByPropertyName)", "", "" ], [ "WorkloadGroup", "Specifies the name of the workload group to create within the resource pool. Use descriptive names that reflect the workload type, like \u0027ReportingQueries\u0027, \u0027ETLProcesses\u0027, or \u0027AdminTasks\u0027.\r\nEach workload group acts as a container for classifying requests and applying specific resource limits and priorities.", "", false, "false", "", "" ], [ "ResourcePool", "Specifies which resource pool will contain the new workload group. Defaults to \u0027default\u0027 if not specified.\r\nUse this to organize workload groups within custom resource pools that have specific CPU and memory allocations.", "", false, "false", "default", "" ], [ "ResourcePoolType", "Determines whether to create the workload group in an Internal or External resource pool. Defaults to Internal.\r\nUse External for R/Python workloads or machine learning services; use Internal for standard SQL Server workloads like queries and stored procedures.", "", false, "false", "Internal", "Internal,External" ], [ "Importance", "Sets the relative priority for requests in this workload group when competing for CPU resources. Defaults to MEDIUM.\r\nUse HIGH for critical application queries, MEDIUM for normal operations, and LOW for background tasks like maintenance or reporting.", "", false, "false", "MEDIUM", "LOW,MEDIUM,HIGH" ], [ "RequestMaximumMemoryGrantPercentage", "Limits how much memory any single query in this workload group can consume from the resource pool. Defaults to 25%.\r\nLower this for concurrent workloads to prevent memory hogging, or increase it for data warehouse queries that need large memory grants for sorting and hashing.", "", false, "false", "25", "" ], [ "RequestMaximumCpuTimeInSeconds", "Sets the maximum CPU time in seconds that any single request can consume before being terminated. Default of 0 means unlimited.\r\nUse this to prevent runaway queries from consuming excessive CPU, typically setting values between 300-3600 seconds depending on your workload requirements.", "", false, "false", "0", "" ], [ "RequestMemoryGrantTimeoutInSeconds", "Defines how long a query will wait for memory grants before timing out. Default of 0 means unlimited wait time.\r\nSet this to prevent queries from waiting indefinitely during memory pressure, typically using values like 60-300 seconds for interactive workloads.", "", false, "false", "0", "" ], [ "MaximumDegreeOfParallelism", "Controls the maximum number of processors that queries in this workload group can use for parallel execution. Default of 0 uses the server\u0027s MAXDOP setting.\r\nLower values prevent queries from consuming too many CPU cores, while higher values can improve performance for analytical workloads on servers with many cores.", "", false, "false", "0", "" ], [ "GroupMaximumRequests", "Limits the total number of concurrent requests that can execute simultaneously within this workload group. Default of 0 means unlimited.\r\nUse this to control concurrency for resource-intensive workloads, preventing too many expensive queries from running at once and overwhelming the system.", "", false, "false", "0", "" ], [ "SkipReconfigure", "Prevents automatic reconfiguration of Resource Governor after creating the workload group. Changes won\u0027t take effect until you manually run ALTER RESOURCE GOVERNOR RECONFIGURE.\r\nUse this when creating multiple workload groups in a batch to avoid repeated reconfigurations, but remember to reconfigure manually afterward.", "", false, "false", "False", "" ], [ "Force", "Drops and recreates the workload group if it already exists, applying new configuration settings.\r\nUse this when you need to modify an existing workload group\u0027s properties, as Resource Governor workload groups cannot be altered once 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": [ "General", "Script", "Object" ], "CommandName": "New-DbaScriptingOption", "Name": "New-DbaScriptingOption", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "New-DbaScriptingOption [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.ScriptingOptions\nReturns a single ScriptingOptions object that can be used to customize script generation behavior. This object contains dozens of boolean and string properties that control what gets included when \r\nscripting SQL Server objects (indexes, triggers, permissions, dependencies, batch separators, etc.). Use this object with Export-DbaScript and other scripting commands to control the generated T-SQL \r\noutput.\nCommon properties include:\r\n- ScriptDrops: Include DROP statements (Boolean)\r\n- WithDependencies: Include dependent objects (Boolean)\r\n- AgentAlertJob: Include SQL Agent Alert and Job information (Boolean)\r\n- AgentNotify: Include SQL Agent notification (Boolean)\r\n- Indexes: Include indexes (Boolean)\r\n- Triggers: Include triggers (Boolean)\r\n- Permissions: Include permissions (Boolean)\r\n- TargetServerVersion: Target SQL Server version for compatibility\nSee Microsoft.SqlServer.Management.Smo.ScriptingOptions documentation for complete property list.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$options = New-DbaScriptingOption\nPS C:\\\u003e $options.ScriptDrops = $false\r\nPS C:\\\u003e $options.WithDependencies = $false\r\nPS C:\\\u003e $options.AgentAlertJob = $true\r\nPS C:\\\u003e $options.AgentNotify = $true\r\nPS C:\\\u003e Get-DbaAgentJob -SqlInstance sql2016 | Export-DbaScript -ScriptingOptionObject $options\nExports Agent Jobs with the Scripting Options ScriptDrops/WithDependencies set to $false and AgentAlertJob/AgentNotify set to true", "Description": "Creates a Microsoft.SqlServer.Management.Smo.ScriptingOptions object that controls how SQL Server objects get scripted into T-SQL CREATE statements. This object lets you customize what gets included when using Export-DbaScript and other dbatools scripting commands - things like whether to include indexes, triggers, permissions, dependencies, or batch separators. Perfect for creating deployment scripts where you need specific control over what gets scripted and how it\u0027s formatted.\n\nSee https://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.scriptingoptions.aspx for more information", "Links": "https://dbatools.io/New-DbaScriptingOption", "Synopsis": "Creates a customizable SMO ScriptingOptions object for controlling T-SQL script generation", "Availability": "Windows, Linux, macOS", "Params": [ ] }, { "Tags": "Role", "CommandName": "New-DbaServerRole", "Name": "New-DbaServerRole", "Author": "Claudio Silva (@ClaudioESSilva), claudioessilva.eu", "Syntax": "New-DbaServerRole [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-ServerRole] \u003cString[]\u003e] [[-Owner] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.ServerRole\nReturns one ServerRole object for each newly created server-level role. The returned object is obtained from Get-DbaServerRole after successful role creation.\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- Role: The name of the server role\r\n- Login: Array of logins/users that are members of this role\r\n- Owner: The login that owns the server role\r\n- IsFixedRole: Boolean indicating if this is a built-in fixed role (always $false for newly created roles)\r\n- DateCreated: DateTime when the role was created\r\n- DateModified: DateTime when the role was last modified\nAdditional properties available (from SMO ServerRole object):\r\n- ServerRole: Duplicate of Role property name\r\n- Parent: Reference to parent SQL Server object\r\n- State: SMO object state (Existing, Creating, Pending, etc.)\r\n- Urn: The unified resource name of the role object\r\n- Properties: Collection of property objects for the role\r\n- PermissionSet: Permissions assigned to the role\nAll properties from the base SMO ServerRole object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaServerRole -SqlInstance sql2017a -ServerRole \u0027dbExecuter\u0027 -Owner sa\nWill create a new server role named dbExecuter and grant ownership to the login sa on sql2017a instance.", "Description": "Creates new server-level roles on one or more SQL Server instances, allowing you to implement custom security frameworks without manually using SSMS or T-SQL. Server roles provide a way to group server-level permissions and assign them to logins, making it easier to manage security across your environment. The function checks for existing roles before creation and optionally allows you to specify a role owner other than the default dbo.", "Links": "https://dbatools.io/New-DbaServerRole", "Synopsis": "Creates custom server-level roles on SQL Server instances for role-based access control.", "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", "", "" ], [ "ServerRole", "Specifies the name of the custom server-level role to create. Accepts multiple role names to create several roles in one operation.\r\nUse this when implementing role-based security models or when you need custom permission groups beyond the built-in server roles like sysadmin or dbcreator.", "", false, "false", "", "" ], [ "Owner", "Sets the login that will own the newly created server role. Defaults to \u0027dbo\u0027 if not specified.\r\nSpecify a different owner when you need the role managed by a specific login for security or organizational requirements.", "", 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": "New-DbaServiceMasterKey", "Name": "New-DbaServiceMasterKey", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "New-DbaServiceMasterKey [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [[-SecurePassword] \u003cSecureString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.MasterKey\nReturns one MasterKey object for each instance where the service master key was created in the master 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: Always \"master\" for service master keys\r\n- CreateDate: DateTime when the service master key was created\r\n- DateLastModified: DateTime when the service master key was last modified\r\n- IsEncryptedByServer: Boolean indicating if the master key is encrypted by the server\nAdditional properties available (from SMO MasterKey object):\r\n- Urn: The Uniform Resource Name of the master key\r\n- State: Current state of the object (Existing, Creating, etc.)\r\n- Parent: Reference to parent database object", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaServiceMasterKey -SqlInstance Server1\nYou will be prompted to securely enter your Service Key password, then a master key will be created in the master database on server1 if it does not exist.", "Description": "Creates a service master key in the master database, which sits at the top of SQL Server\u0027s encryption hierarchy. The service master key automatically encrypts and protects database master keys, certificates, and other encryption objects across all databases on the instance. This is typically the first step when implementing any encryption strategy on a SQL Server instance, as it eliminates the need to manually manage individual database master key passwords.", "Links": "https://dbatools.io/New-DbaServiceMasterKey", "Synopsis": "Creates a service master key in the master database for instance-level encryption hierarchy", "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", "Provides an alternative way to specify the service master key password using a PSCredential object.\r\nThe password from the credential will be used to encrypt the service master key, offering a convenient method when you already have credentials stored.", "", false, "false", "", "" ], [ "SecurePassword", "Specifies the password used to encrypt the service master key. Must be a SecureString object for security.\r\nUse this when you need to set a specific password for the service master key instead of being prompted interactively.", "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", "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": [ "Utility", "Query" ], "CommandName": "New-DbaSqlParameter", "Name": "New-DbaSqlParameter", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "New-DbaSqlParameter [[-CompareInfo] \u003cString\u003e] [[-DbType] \u003cString\u003e] [[-Direction] \u003cString\u003e] [-ForceColumnEncryption] [-IsNullable] [[-LocaleId] \u003cInt32\u003e] [[-Offset] \u003cString\u003e] [[-ParameterName] \u003cString\u003e] [[-Precision] \u003cString\u003e] [[-Scale] \u003cString\u003e] [[-Size] \u003cInt32\u003e] [[-SourceColumn] \u003cString\u003e] [-SourceColumnNullMapping] [[-SourceVersion] \u003cString\u003e] [[-SqlDbType] \u003cString\u003e] [[-SqlValue] \u003cObject\u003e] [[-TypeName] \u003cString\u003e] [[-UdtTypeName] \u003cString\u003e] [[-Value] \u003cObject\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.Data.SqlClient.SqlParameter\nReturns a single SqlParameter object configured with the specified properties. The returned parameter object is ready to be used with Invoke-DbaQuery or other data access operations that accept \r\nparameterized queries.\nProperties available on the returned object include:\r\n- CompareInfo: String comparison rules for the parameter\r\n- DbType: .NET data type from System.Data.DbType enumeration\r\n- Direction: Parameter direction (Input, Output, InputOutput, or ReturnValue)\r\n- ForceColumnEncryption: Boolean indicating Always Encrypted enforcement\r\n- IsNullable: Boolean indicating if parameter accepts null values\r\n- LocaleId: Integer locale identifier (LCID) for formatting\r\n- Offset: Starting position within parameter value for binary/text data\r\n- ParameterName: The name of the parameter (including \u0027@\u0027 prefix)\r\n- Precision: Total number of digits for numeric types\r\n- Scale: Number of decimal places for numeric types\r\n- Size: Maximum length for variable-length data types (use -1 for MAX)\r\n- SourceColumn: Column name mapping for DataTable operations\r\n- SourceColumnNullMapping: Boolean for DataAdapter null mapping\r\n- SourceVersion: Data version selection (Original, Current, Proposed, Default)\r\n- SqlDbType: SQL Server-specific data type\r\n- SqlValue: Parameter value using SQL Server-specific types\r\n- TypeName: User-defined table type name for table-valued parameters\r\n- UdtTypeName: User-defined data type (UDT) or CLR type name\r\n- Value: The actual parameter value passed to SQL", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaSqlParameter -ParameterName json_result -SqlDbType NVarChar -Size -1 -Direction Output\nCreates a SqlParameter object that can be used with Invoke-DbaQuery\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$output = New-DbaSqlParameter -ParameterName json_result -SqlDbType NVarChar -Size -1 -Direction Output\nPS C:\\\u003e Invoke-DbaQuery -SqlInstance localhost -Database master -CommandType StoredProcedure -Query my_proc -SqlParameter $output\r\nPS C:\\\u003e $output.Value\nCreates an output parameter and uses it to invoke a stored procedure.", "Description": "Creates a Microsoft.Data.SqlClient.SqlParameter object with specified properties like data type, direction, size, and value. This is essential for executing parameterized queries and stored procedures safely through Invoke-DbaQuery, preventing SQL injection while providing precise control over parameter behavior. Supports all SqlParameter properties including output parameters, table-valued parameters, and column encryption for secure data handling.", "Links": "https://dbatools.io/New-DbaSqlParameter", "Synopsis": "Creates a SqlParameter object for use with parameterized queries and stored procedures.", "Availability": "Windows, Linux, macOS", "Params": [ [ "CompareInfo", "Defines how string comparisons are performed when this parameter is used in SQL operations. Controls case sensitivity, accent sensitivity, and other collation behaviors.\r\nUse this when you need specific string comparison rules that differ from the database\u0027s default collation settings.", "", false, "false", "", "None,IgnoreCase,IgnoreNonSpace,IgnoreKanaType,IgnoreWidth,BinarySort2,BinarySort" ], [ "DbType", "Specifies the .NET data type for the parameter using System.Data.DbType enumeration. This is an alternative to SqlDbType for cross-database compatibility.\r\nUse SqlDbType instead for SQL Server-specific operations, as it provides better type mapping and performance.", "", false, "false", "", "AnsiString,Binary,Byte,Boolean,Currency,Date,DateTime,Decimal,Double,Guid,Int16,Int32,Int64,Object,SByte,Single,String,Time,UInt16,UInt32,UInt64,VarNumeric,AnsiStringFixedLength,StringFixedLength,Xml,DateTime2,DateTimeOffset" ], [ "Direction", "Specifies whether the parameter passes data into the query (Input), returns data from a stored procedure (Output), or both (InputOutput).\r\nRequired when creating output parameters for stored procedures that return values through parameters rather than result sets.", "", false, "false", "", "Input,Output,InputOutput,ReturnValue" ], [ "ForceColumnEncryption", "Enforces encryption of a parameter when using Always Encrypted.\nIf SQL Server informs the driver that the parameter does not need to be encrypted, the query using the parameter will fail.\nThis property provides additional protection against security attacks that involve a compromised SQL Server providing incorrect encryption metadata to the client, which may lead to data disclosure.", "", false, "false", "False", "" ], [ "IsNullable", "Indicates whether the parameter can accept null values, but does not enforce null validation during query execution.\r\nThis is primarily used for metadata purposes and DataAdapter operations, not for runtime null checking.", "", false, "false", "False", "" ], [ "LocaleId", "Specifies the locale identifier (LCID) that determines regional formatting conventions for the parameter value.\r\nUse this when working with locale-specific data formatting, particularly for date, time, and numeric values that need specific regional representation.", "", false, "false", "0", "" ], [ "Offset", "Specifies the starting position within the parameter value when working with binary or text data types.\r\nUseful when you need to read or write data starting from a specific byte position rather than the beginning of the value.", "", false, "false", "", "" ], [ "ParameterName", "Specifies the name of the parameter as it appears in the SQL query or stored procedure, including the \u0027@\u0027 prefix.\r\nMust match exactly with parameter names defined in your SQL statements for proper parameter binding.", "Name", false, "false", "", "" ], [ "Precision", "Defines the total number of digits for numeric data types like decimal or numeric columns.\r\nRequired when working with precise financial calculations or when the target column has specific precision requirements.", "", false, "false", "", "" ], [ "Scale", "Specifies the number of decimal places for numeric data types, working together with Precision.\r\nEssential for financial data and calculations where exact decimal representation is required to prevent rounding errors.", "", false, "false", "", "" ], [ "Size", "Defines the maximum length for variable-length data types like varchar, nvarchar, or varbinary columns.\r\nUse -1 for MAX data types (varchar(max), nvarchar(max)) to handle large text or binary data without size restrictions.", "", false, "false", "0", "" ], [ "SourceColumn", "Maps the parameter to a specific column name in a DataTable or DataSet for bulk operations.\r\nUsed primarily with DataAdapter operations when you need to map parameter values to specific columns during data updates.", "", false, "false", "", "" ], [ "SourceColumnNullMapping", "Indicates whether the source column allows null values, helping SqlCommandBuilder generate correct UPDATE statements.\r\nImportant for DataAdapter scenarios where the framework needs to understand column nullability for proper SQL generation.", "", false, "false", "False", "" ], [ "SourceVersion", "Specifies which version of data to use from a DataRow when the parameter value comes from a DataSet.\r\nUse \u0027Current\u0027 for modified data, \u0027Original\u0027 for unchanged data, or \u0027Proposed\u0027 for uncommitted changes during DataAdapter operations.", "", false, "false", "", "Original,Current,Proposed,Default" ], [ "SqlDbType", "Specifies the SQL Server data type for the parameter, ensuring proper type mapping and optimal performance.\r\nPrefer this over DbType for SQL Server operations as it provides exact type matching with SQL Server\u0027s native data types.", "", false, "false", "", "BigInt,Binary,Bit,Char,DateTime,Decimal,Float,Image,Int,Money,NChar,NText,NVarChar,Real,UniqueIdentifier,SmallDateTime,SmallInt,SmallMoney,Text,Timestamp,TinyInt,VarBinary,VarChar,Variant,Xml,Udt,Structured,Date,Time,DateTime2,DateTimeOffset" ], [ "SqlValue", "Sets the parameter value using SQL Server-specific data types (like SqlString, SqlInt32) instead of standard .NET types.\r\nUse this when you need to handle SQL null values explicitly or work with SQL Server-specific type behaviors that differ from .NET types.", "", false, "false", "", "" ], [ "TypeName", "Specifies the user-defined table type name when passing DataTable objects as table-valued parameters to stored procedures.\r\nThe type name must match a table type defined in the database schema and is essential for bulk data operations.", "", false, "false", "", "" ], [ "UdtTypeName", "Specifies the name of a user-defined data type (UDT) or CLR type when working with custom SQL Server data types.\r\nRequired when passing complex objects or custom data structures that extend beyond standard SQL Server data types.", "", false, "false", "", "" ], [ "Value", "Specifies the actual data value to pass to the SQL parameter, automatically handling type conversion from .NET to SQL types.\r\nThe most commonly used parameter property for passing data into queries and stored procedures safely.", "", 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": [ "SSIS", "SSISDB", "Catalog" ], "CommandName": "New-DbaSsisCatalog", "Name": "New-DbaSsisCatalog", "Author": "Stephen Bennett, https://sqlnotesfromtheunderground.wordpress.com/", "Syntax": "New-DbaSsisCatalog [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [[-SecurePassword] \u003cSecureString\u003e] [[-SsisCatalog] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SSIS Catalog successfully created, containing connection context and creation 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 (computer\\instance format)\r\n- SsisCatalog: The name of the SSIS Catalog database that was created\r\n- Created: Boolean indicating the catalog was successfully created (always $true when object is returned)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$SecurePassword = Read-Host -AsSecureString -Prompt \"Enter password\"\nPS C:\\\u003e New-DbaSsisCatalog -SqlInstance DEV01 -SecurePassword $SecurePassword\nCreates the SSIS Catalog on server DEV01 with the specified password.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eNew-DbaSsisCatalog -SqlInstance sql2016 -Credential usernamedoesntmatter\nCreates the SSIS Catalog on server DEV01 with the specified password in the credential prompt. As the example username suggets the username does not matter.\r\nThis is simply an easier way to get a secure password.", "Description": "Creates the SSIS Catalog database (SSISDB) which is required before you can deploy, manage, or execute SSIS packages on the server. Installing SQL Server with SSIS doesn\u0027t automatically create this catalog - it\u0027s a separate post-installation step that requires CLR integration and a secure password for the master key. This function handles the entire setup process, including prerequisite validation, so you don\u0027t have to manually run SQL scripts or navigate through SQL Server Management Studio wizards.", "Links": "https://dbatools.io/New-DbaSsisCatalog", "Synopsis": "Creates and enables the SSIS Catalog (SSISDB) database on SQL Server 2012+ instances", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "SQL Server you wish to run the function on.", "", 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", "Provides an alternative way to supply the master password using a PSCredential object instead of SecurePassword. The username portion is ignored - only the password from the credential is used.\r\nThis approach simplifies password input by allowing you to use Get-Credential, which presents a secure password prompt dialog.", "", false, "false", "", "" ], [ "SecurePassword", "Specifies the master password that encrypts the SSIS catalog database master key. This password is required to access and decrypt sensitive data like connection strings and package parameters stored \r\nin SSISDB.\r\nUse Read-Host -AsSecureString or ConvertTo-SecureString to create this value securely without exposing the password in plain text.", "Password", false, "false", "", "" ], [ "SsisCatalog", "Specifies the name for the SSIS catalog database that will be created. Defaults to \u0027SSISDB\u0027 which is the Microsoft standard name.\r\nOnly change this if your organization has specific naming requirements, as most SSIS tooling and documentation assumes the standard SSISDB name.", "", false, "false", "SSISDB", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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": [ "Module", "Support" ], "CommandName": "New-DbatoolsSupportPackage", "Name": "New-DbatoolsSupportPackage", "Author": "Friedrich Weinmann (@FredWeinmann)", "Syntax": "New-DbatoolsSupportPackage [[-Path] \u003cString\u003e] [[-Variables] \u003cString[]\u003e] [-PassThru] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.IO.FileInfo\nReturns a FileInfo object representing the created diagnostic support package ZIP file.\nProperties:\r\n- FullName: The complete file path to the ZIP archive (e.g., C:\\Users\\username\\Desktop\\dbatools_support_pack_2024_12_29-14_30_45.zip)\r\n- Name: The filename of the ZIP archive (e.g., dbatools_support_pack_2024_12_29-14_30_45.zip)\r\n- DirectoryName: The directory path containing the ZIP file\r\n- Directory: The parent directory object\r\n- Length: The size of the ZIP file in bytes\r\n- Exists: Boolean indicating the file exists ($true upon successful creation)\r\n- CreationTime: DateTime when the file was created\r\n- LastWriteTime: DateTime when the file was last modified\r\n- LastAccessTime: DateTime when the file was last accessed\nThe ZIP archive contains comprehensive diagnostic data for troubleshooting:\r\n- Operating system and hardware information\r\n- PowerShell and .NET framework versions\r\n- Loaded modules, snapins (on Windows PowerShell), and assemblies\r\n- Complete console buffer (all visible commands and output)\r\n- PowerShell command history from the current session\r\n- dbatools message and error logs\r\n- Any additional variables specified via -Variables parameter\nNote: No output is returned if -WhatIf is specified or if an error occurs during package creation. Use -PassThru to programmatically access the FileInfo object even if it would normally only be \r\ndisplayed.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbatoolsSupportPackage\nCreates a large support pack in order to help us troubleshoot stuff.", "Description": "This function creates an extensive diagnostic package specifically designed to help the dbatools team troubleshoot module-related issues, bugs, or unexpected behavior. When you encounter problems with dbatools commands or need to submit a bug report, this package provides all the environmental and runtime information needed for effective debugging.\n\nThe resulting compressed file contains comprehensive system and PowerShell environment details that are essential for reproducing and diagnosing issues. This saves you from manually collecting multiple pieces of information and ensures nothing important gets missed when reporting problems.\n\nThe package includes:\n- Operating system and hardware information (CPU, RAM, OS version)\n- PowerShell and .NET framework versions and loaded modules\n- Your PowerShell command history from the current session\n- dbatools internal message and error logs\n- Complete console buffer contents (everything currently visible in your PowerShell window)\n- Loaded assemblies and their versions\n- Any additional variables you specify\n\nThe output file is automatically created on your desktop (or home directory if desktop doesn\u0027t exist) as a timestamped ZIP archive. Always start a fresh PowerShell session and reproduce the minimal steps to trigger your issue before running this command - this keeps the diagnostic data focused and avoids including unrelated information or sensitive data from your session history.", "Links": "https://dbatools.io/New-DbatoolsSupportPackage", "Synopsis": "Creates a comprehensive diagnostic package for troubleshooting dbatools module issues and bugs.", "Availability": "Windows, Linux, macOS", "Params": [ [ "Path", "Specifies the directory where the support package ZIP file will be created. Defaults to your desktop, or home directory if desktop doesn\u0027t exist.\r\nUse this when you need the diagnostic file saved to a specific location for easier access or compliance requirements.", "", false, "false", "\"$($env:USERPROFILE)\\Desktop\"", "" ], [ "Variables", "Specifies additional PowerShell variables to include in the diagnostic package by name. Only captures variables that exist in your current session.\r\nUse this when specific variables contain connection strings, configuration settings, or data relevant to reproducing your issue.", "", false, "false", "", "" ], [ "PassThru", "Returns the FileInfo object for the created ZIP file instead of just displaying its location.\r\nUse this when you need to programmatically work with the support package file, such as uploading it automatically or getting its size.", "", 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": "New-DbaXESession", "Name": "New-DbaXESession", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "New-DbaXESession [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Name] \u003cString\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "None\nThis command creates the Extended Events session on the server but does not return any output objects to the pipeline. The session object is created on the SQL Server instance but is not returned to \r\nthe caller. To work with the created session, you can use Get-DbaXESession to retrieve it after creation, or the session can be further configured and created in a single operation using other \r\nExtended Events cmdlets.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$session = New-DbaXESession -SqlInstance sql2017 -Name XeSession_Test\nPS C:\\\u003e $event = $session.AddEvent(\"sqlserver.file_written\")\r\nPS C:\\\u003e $event.AddAction(\"package0.callstack\")\r\nPS C:\\\u003e $session.Create()\nReturns a new XE Session object from sql2017 then adds an event, an action then creates it.", "Description": "Creates a new Extended Events session object that can be programmatically configured with events, actions, and targets before deployment to SQL Server. This function provides the foundation for building XE sessions through code rather than using predefined templates. The returned session object requires additional configuration using AddEvent(), AddAction(), and AddTarget() methods before calling Create() to deploy it to the server. For most scenarios, Import-DbaXESessionTemplate provides a simpler approach using predefined session configurations, but this function offers complete control when building custom monitoring solutions from scratch.", "Links": "https://dbatools.io/New-DbaXESession", "Synopsis": "Creates a new Extended Events session object for programmatic configuration and deployment.", "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.", "", 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", "", "" ], [ "Name", "Specifies the name for the new Extended Events session. Session names must be unique within the SQL Server instance and follow SQL Server identifier naming rules.\r\nChoose descriptive names that indicate the monitoring purpose, such as \"Query_Performance_Monitor\" or \"Security_Audit_Session\".", "", 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", "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": [ "Deployment", "Dacpac", "Bacpac" ], "CommandName": "Publish-DbaDacPackage", "Name": "Publish-DbaDacPackage", "Author": "Richie lee (@richiebzzzt)", "Syntax": "Publish-DbaDacPackage [-SqlInstance \u003cDbaInstanceParameter[]\u003e] [-SqlCredential \u003cPSCredential\u003e] -Path \u003cString\u003e -Database \u003cString[]\u003e [-ConnectionString \u003cString[]\u003e] [-GenerateDeploymentReport] [-ScriptOnly] [-Type \u003cString\u003e] [-OutputPath \u003cString\u003e] [-IncludeSqlCmdVars] [-DacOption \u003cObject\u003e] [-EnableException] [-DacFxPath \u003cString\u003e] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nPublish-DbaDacPackage [-SqlInstance \u003cDbaInstanceParameter[]\u003e] [-SqlCredential \u003cPSCredential\u003e] -Path \u003cString\u003e [-PublishXml \u003cString\u003e] -Database \u003cString[]\u003e [-ConnectionString \u003cString[]\u003e] [-GenerateDeploymentReport] [-ScriptOnly] [-Type \u003cString\u003e] [-OutputPath \u003cString\u003e] [-IncludeSqlCmdVars] [-EnableException] [-DacFxPath \u003cString\u003e] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database deployed, with properties varying based on the deployment type and options specified.\nProperties when deploying DACPAC (Type = \u0027Dacpac\u0027):\r\nDefault properties (always included):\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 in computer\\instance format (string)\r\n- Database: The target database name (string)\r\n- Dacpac: Path to the deployed DACPAC file (string)\r\n- PublishXml: Path to the publish profile XML file used, if any (string)\r\n- Result: Deployment result messages and status output (string)\r\n- DeployOptions: The deployment options object used for the deployment, excluding SqlCommandVariableValues (object)\r\n- SqlCmdVariableValues: Array of SqlCmd variable names that were applied (string[])\nAdditional properties when using -ScriptOnly or -GenerateDeploymentReport:\r\n- DatabaseScriptPath: Full path to the generated database deployment script file (string)\r\n- MasterDbScriptPath: Full path to the generated master database script file, if generated (string)\r\n- DeploymentReport: Full path to the XML deployment report file (string)\nProperties when deploying BACPAC (Type = \u0027Bacpac\u0027):\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 in computer\\instance format (string)\r\n- Database: The target database name (string)\r\n- Bacpac: Path to the deployed BACPAC file (string)\r\n- Result: Deployment result messages and status output (string)\r\n- DeployOptions: The deployment options object used for the import (object)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$options = New-DbaDacOption -Type Dacpac -Action Publish\nPS C:\\\u003e $options.DeployOptions.DropObjectsNotInSource = $true\r\nPS C:\\\u003e Publish-DbaDacPackage -SqlInstance sql2016 -Database DB1 -DacOption $options -Path c:\\temp\\db.dacpac\nUses DacOption object to set Deployment Options and updates DB1 database on sql2016 from the db.dacpac dacpac file, dropping objects that are missing from source.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003ePublish-DbaDacPackage -SqlInstance sql2017 -Database WideWorldImporters -Path C:\\temp\\sql2016-WideWorldImporters.dacpac -PublishXml C:\\temp\\sql2016-WideWorldImporters-publish.xml -Confirm\nUpdates WideWorldImporters on sql2017 from the sql2016-WideWorldImporters.dacpac using the sql2016-WideWorldImporters-publish.xml publish profile. Prompts for confirmation.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eNew-DbaDacProfile -SqlInstance sql2016 -Database db2 -Path C:\\temp\nPS C:\\\u003e Export-DbaDacPackage -SqlInstance sql2016 -Database db2 | Publish-DbaDacPackage -PublishXml C:\\temp\\sql2016-db2-publish.xml -Database db1, db2 -SqlInstance sql2017\nCreates a publish profile at C:\\temp\\sql2016-db2-publish.xml, exports the .dacpac to $home\\Documents\\sql2016-db2.dacpac. Does not prompt for confirmation.\r\nthen publishes it to the sql2017 server database db2\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$loc = \"C:\\Users\\bob\\source\\repos\\Microsoft.Data.Tools.Msbuild\\lib\\net46\\Microsoft.SqlServer.Dac.dll\"\nPS C:\\\u003e Publish-DbaDacPackage -SqlInstance \"local\" -Database WideWorldImporters -Path C:\\temp\\WideWorldImporters.dacpac -PublishXml C:\\temp\\WideWorldImporters.publish.xml -DacFxPath $loc -Confirm\nPublishes the dacpac using a specific dacfx library. Prompts for confirmation.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003ePublish-DbaDacPackage -SqlInstance sql2017 -Database WideWorldImporters -Path C:\\temp\\sql2016-WideWorldImporters.dacpac -PublishXml C:\\temp\\sql2016-WideWorldImporters-publish.xml -ScriptOnly\nDoes not deploy the changes, but will generate the deployment script that would be executed against WideWorldImporters.", "Description": "Deploys database schema changes from DACPAC files created by SSDT projects or Export-DbaDacPackage, automatically updating target database structure and executing embedded pre/post deployment scripts. Also imports data from BACPAC files for complete database restoration scenarios. This replaces manual schema synchronization and deployment processes, making it essential for CI/CD pipelines and environment promotions. You can generate deployment scripts without applying changes for review, or use publish profiles to control deployment behavior and variable substitution.", "Links": "https://dbatools.io/Publish-DbaDacPackage", "Synopsis": "Deploys DACPAC or BACPAC files to SQL Server databases using the DacFx framework", "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).\nOnly SQL authentication is supported. When not specified, uses Trusted Authentication.", "", false, "false", "", "" ], [ "Path", "Specifies the filesystem path to the DACPAC or BACPAC file to deploy. The function automatically detects file type based on the extension.\r\nUse this to point to your compiled database project (.dacpac) or exported database backup with data (.bacpac).", "", true, "true (ByPropertyName)", "", "" ], [ "PublishXml", "Specifies the path to a publish profile XML file that defines deployment options and SqlCmd variables. Created by SQL Server Data Tools (SSDT) or New-DbaDacProfile.\r\nUse this to control deployment behavior like dropping objects not in source, ignoring permissions, or setting variable values for different environments.", "", false, "false", "", "" ], [ "Database", "Specifies the target database name(s) to deploy the DACPAC or BACPAC to. Accepts multiple database names for deploying the same package to multiple databases.\r\nThe database will be created if it doesn\u0027t exist, or updated to match the schema if it already exists.", "", true, "true (ByPropertyName)", "", "" ], [ "ConnectionString", "Specifies the connection string to connect to the target SQL Server instance. Alternative to using SqlInstance and SqlCredential parameters.\r\nUse this when you need specific connection properties or when connecting through alternative authentication methods not supported by SqlInstance.", "", false, "false", "", "" ], [ "GenerateDeploymentReport", "Creates an XML deployment report showing what changes were made during the deployment. The report is saved to the OutputPath directory.\r\nUse this for deployment auditing, troubleshooting failed deployments, or documenting changes applied to production databases.", "", false, "false", "False", "" ], [ "ScriptOnly", "Generates the deployment script without executing it against the target database. The script is saved to the OutputPath directory for review.\r\nUse this for change approval processes, manual deployment scenarios, or to review what changes would be applied before executing them.", "", false, "false", "False", "" ], [ "Type", "Specifies whether to deploy a DACPAC (schema only) or BACPAC (schema and data) file. Defaults to DACPAC.\r\nUse DACPAC for deploying database schema changes from development to production, or BACPAC for full database restore including data.", "", false, "false", "Dacpac", "Dacpac,Bacpac" ], [ "OutputPath", "Specifies the directory where deployment scripts and reports will be saved when using ScriptOnly or GenerateDeploymentReport. Defaults to the dbatools export path configuration.\r\nUse this to organize output files in a specific location for review, version control, or automated deployment processes.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027Path.DbatoolsExport\u0027)", "" ], [ "IncludeSqlCmdVars", "Enables replacement of SqlCmd variables in the publish profile with their actual values during deployment.\r\nUse this when your deployment scripts or publish profile contain variables like $(Environment) or $(ServerName) that need to be substituted with environment-specific values.", "", false, "false", "False", "" ], [ "DacOption", "Specifies deployment options object controlling how the deployment behaves. Created using New-DbaDacOption with specific deployment settings.\r\nUse this to programmatically control deployment behavior instead of using a publish profile XML file, such as dropping objects not in source or ignoring permissions.", "Option", 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", "" ], [ "DacFxPath", "Specifies the path to a specific version of the Microsoft.SqlServer.Dac.dll library to use for deployment operations.\r\nUse this when you need a specific DacFx version for compatibility with your SQL Server version or to use features from a newer DacFx release.", "", 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": [ "XE", "Audit", "Security" ], "CommandName": "Read-DbaAuditFile", "Name": "Read-DbaAuditFile", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Read-DbaAuditFile [-Path] \u003cObject[]\u003e [-Raw] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.Object (when -Raw is specified)\nReturns the raw enumeration object containing unprocessed audit event data from Read-XEvent.\nPSCustomObject (default)\nReturns one object per audit event with the following standard properties:\r\n- name: The name of the audit event (string)\r\n- timestamp: The timestamp when the event occurred (datetime)\nAdditional properties are dynamically added based on the audit file contents and include:\r\n- Fields.*: All field names present in the audit events (properties vary based on audit configuration)\r\n- Actions.*: All action names from the audit events with the action suffix only (e.g., \u0027session_id\u0027 from \u0027server_principal_name.session_id\u0027)\nThe exact set of additional properties depends on what SQL Server Audit events and fields are present in the .sqlaudit files being read. Use Select-Object * to see all available properties for a \r\ngiven audit file.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRead-DbaAuditFile -Path C:\\temp\\logins.sqlaudit\nReturns events from C:\\temp\\logins.sqlaudit.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-ChildItem C:\\temp\\audit\\*.sqlaudit | Read-DbaAuditFile\nReturns events from all .sqlaudit files in C:\\temp\\audit.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaInstanceAudit -SqlInstance sql2014 -Audit LoginTracker | Read-DbaAuditFile\nReads remote Audit details by accessing the file over the admin UNC share.", "Description": "Reads and parses SQL Server audit files (.sqlaudit) created by SQL Server Audit functionality, converting binary audit data into readable PowerShell objects. Each audit event is returned with its timestamp, event details, fields, and actions in a structured format that\u0027s easy to filter, export, or analyze. This is essential for security investigations, compliance reporting, and monitoring database access patterns since SQL Server audit files are stored in a proprietary binary format that can\u0027t be read directly. Works with local files, UNC paths, or can be piped from Get-DbaInstanceAudit to automatically locate and read audit files from remote instances.", "Links": "https://dbatools.io/Read-DbaAuditFile", "Synopsis": "Parses SQL Server audit files (.sqlaudit) into structured event data for security analysis and compliance reporting.", "Availability": "Windows, Linux, macOS", "Params": [ [ "Path", "Specifies the path to SQL Server audit files (.sqlaudit) to read and parse. Accepts file paths, FileInfo objects from Get-ChildItem, or Audit objects from Get-DbaInstanceAudit.\r\nSupports UNC paths for reading remote files and automatically expands wildcards to process multiple related audit files. Use this when you need to analyze audit data from specific files or when \r\npiping from other dbatools audit commands.", "FullName", true, "true (ByValue)", "", "" ], [ "Raw", "Returns the unprocessed enumeration object instead of structured PowerShell objects.\r\nUse this when you need access to the raw audit data structure for custom processing or when working with audit parsing tools that expect the native format.", "", 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": "Read-DbaBackupHeader", "Name": "Read-DbaBackupHeader", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Read-DbaBackupHeader [-SqlInstance] \u003cDbaInstanceParameter\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Path] \u003cObject[]\u003e [-Simple] [-FileList] [[-StorageCredential] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.Data.DataRow (default output)\nReturns one object per backup set found in the backup file. When -Simple is not specified, returns the full DataTable with backup header metadata including:\nDefault properties:\r\n- DatabaseName: Name of the database that was backed up\r\n- BackupFinishDate: DateTime when the backup completed\r\n- RecoveryModel: Database recovery model (Simple, Full, or BulkLogged)\r\n- BackupSize: Size of the backup (dbasize object with Byte, KB, MB, GB properties)\r\n- CompressedBackupSize: Size of the compressed backup if compression was used (dbasize object)\r\n- DatabaseCreationDate: DateTime the database was created\r\n- UserName: Login that performed the backup\r\n- ServerName: SQL Server instance name where backup was created\r\n- SqlVersion: SQL Server version string (e.g., \"SQL Server 2016\", \"SQL Server 2019\")\r\n- BackupPath: Full path to the backup file\r\n- FileList: Collection of backup file details (see -FileList for details)\nAdditional properties from SMO Restore.ReadBackupHeader():\r\n- BackupType: Type of backup (Database, Differential, Log, etc.)\r\n- BackupName: Name given to the backup set\r\n- Position: Position of this backup set within the file (1 for first, 2 for second, etc.)\r\n- DatabaseVersion: Internal database version number\r\n- IsPassword: Whether the backup is password-protected (0 or 1)\r\n- IsCopyOnly: Whether this is a copy-only backup (0 or 1)\r\n- ContinuationFolk: Whether this is a continuation of a previous backup (0 or 1)\r\n- HasBulkLoggedData: Whether the backup contains bulk-logged operations (0 or 1)\r\n- IsSnapshot: Whether this is a snapshot backup (0 or 1)\r\n- IsDamaged: Whether the backup is marked as damaged (0 or 1)\r\n- StarTime: DateTime when backup started\r\n- CompatibilityLevel: Compatibility level of the database\r\n- SoftwareVendorId: Software vendor identifier\r\n- SoftwareVersionMajor: Major version of SQL Server that created backup\r\n- SoftwareVersionMinor: Minor version of SQL Server that created backup\r\n- SoftwareVersionBuild: Build number of SQL Server that created backup\r\n- MachineName: Computer name where backup was created\r\n- Flags: Backup flags and options\r\n- BindingId: Binding ID\r\n- RecoveryFork: Recovery fork identifier\r\n- Collation: Database collation\r\n- FamilyGuid: Family GUID for backup family tracking\r\n- HasBackupChecksums: Whether checksums are present (0 or 1)\r\n- IsSealedBackup: Whether backup is sealed/complete (0 or 1)\nSystem.Data.DataRow (when -Simple is specified)\nReturns one object per backup set with only essential backup metadata columns:\r\n- DatabaseName: Name of the database that was backed up\r\n- BackupFinishDate: DateTime when the backup completed\r\n- RecoveryModel: Database recovery model (Simple, Full, or BulkLogged)\r\n- BackupSize: Size of the backup (dbasize object with Byte, KB, MB, GB properties)\r\n- CompressedBackupSize: Size of the compressed backup (dbasize object)\r\n- DatabaseCreationDate: DateTime the database was created\r\n- UserName: Login that performed the backup\r\n- ServerName: SQL Server instance name\r\n- SqlVersion: SQL Server version string\r\n- BackupPath: Full path to the backup file\nSystem.Data.DataRow (when -FileList is specified)\nReturns detailed information about each data and log file contained within the backup set(s):\r\n- LogicalName: Logical name of the file as defined in the database\r\n- PhysicalName: Physical file path where the file is stored\r\n- Type: File type (D for Data, L for Log, etc.)\r\n- FileGroupName: Filegroup that contains this file\r\n- Size: Size of the file in bytes\r\n- MaxSize: Maximum size of the file in bytes\r\n- FileId: File ID number in the database\r\n- CreateLsn: Log sequence number when file was created\r\n- DropLsn: Log sequence number when file was dropped (if applicable)\r\n- UniqueId: Unique identifier for the file\r\n- ReadOnlyLsn: Log sequence number when file became read-only\r\n- ReadWriteLsn: Log sequence number when file became read-write\r\n- BackupSizeInBytes: Size of this file in the backup\r\n- SourceBlockSize: Original block size when file was created\r\n- FileGroupId: ID of the filegroup containing this file\r\n- LogGroupGuid: Identifier for log group\r\n- DifferentialBaseLsn: LSN of the differential base\r\n- DifferentialBaseGuid: GUID of the differential base\r\n- IsReadOnly: Whether the file is read-only (0 or 1)\r\n- IsPresent: Whether the file is present in this backup (0 or 1)\r\n- TdeThumbprint: Transparent Data Encryption thumbprint if applicable", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRead-DbaBackupHeader -SqlInstance sql2016 -Path S:\\backups\\mydb\\mydb.bak\nLogs into sql2016 using Windows authentication and reads the local file on sql2016, S:\\backups\\mydb\\mydb.bak.\nIf you are running this command on a workstation and connecting remotely, remember that sql2016 cannot access files on your own workstation.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRead-DbaBackupHeader -SqlInstance sql2016 -Path \\\\nas\\sql\\backups\\mydb\\mydb.bak, \\\\nas\\sql\\backups\\otherdb\\otherdb.bak\nLogs into sql2016 and reads two backup files - mydb.bak and otherdb.bak. The SQL Server service account must have rights to read this file.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRead-DbaBackupHeader -SqlInstance . -Path C:\\temp\\myfile.bak -Simple\nLogs into the local workstation (or computer) and shows simplified output about C:\\temp\\myfile.bak. The SQL Server service account must have rights to read this file.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$backupinfo = Read-DbaBackupHeader -SqlInstance . -Path C:\\temp\\myfile.bak\nPS C:\\\u003e $backupinfo.FileList\nDisplays detailed information about each of the datafiles contained in the backupset.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eRead-DbaBackupHeader -SqlInstance . -Path C:\\temp\\myfile.bak -FileList\nAlso returns detailed information about each of the datafiles contained in the backupset.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e\"C:\\temp\\myfile.bak\", \"\\backupserver\\backups\\myotherfile.bak\" | Read-DbaBackupHeader -SqlInstance sql2016 | Where-Object { $_.BackupSize.Megabyte -gt 100 }\nReads the two files and returns only backups larger than 100 MB\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eGet-ChildItem \\\\nas\\sql\\*.bak | Read-DbaBackupHeader -SqlInstance sql2016\nGets a list of all .bak files on the \\\\nas\\sql share and reads the headers using the server named \"sql2016\". This means that the server, sql2016, must have read access to the \\\\nas\\sql share.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eRead-DbaBackupHeader -SqlInstance sql2016 -Path https://dbatoolsaz.blob.core.windows.net/azbackups/restoretime/restoretime_201705131850.bak -StorageCredential AzureBackupUser\nGets the backup header information from the SQL Server backup file stored at https://dbatoolsaz.blob.core.windows.net/azbackups/restoretime/restoretime_201705131850.bak on Azure\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003eRead-DbaBackupHeader -SqlInstance sql2022 -Path s3://s3.us-west-2.amazonaws.com/mybucket/backups/mydb.bak -StorageCredential MyS3Credential\nGets the backup header information from the SQL Server backup file stored in an AWS S3 bucket. Requires SQL Server 2022 or higher and a credential configured with S3 access keys.", "Description": "Uses SQL Server\u0027s RESTORE HEADERONLY functionality to extract detailed metadata from backup files including database name, backup type, creation date, file lists, and backup size information. This lets you validate backups, plan restores, and audit backup inventory without actually performing a restore operation.\n\nThe function can process full, differential, and transaction log backups from local file systems, network shares, and Azure blob storage. It requires an online SQL Server instance to parse the backup files since it leverages SQL Server\u0027s built-in backup reading capabilities.\n\nSupports multithreaded processing for improved performance when scanning multiple backup files. The backup file paths must be accessible from the target SQL Server instance, not your local workstation.", "Links": "https://dbatools.io/Read-DbaBackupHeader", "Synopsis": "Extracts backup metadata from SQL Server backup files without restoring them", "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", "", "" ], [ "Path", "Specifies the file path to SQL Server backup files including full, differential, and transaction log backups. Supports local paths, UNC network shares, and Azure blob storage URLs.\r\nThe backup files must be accessible from the target SQL Server instance, not your local workstation. Use this to read backup metadata without performing an actual restore.", "", true, "true (ByValue)", "", "" ], [ "Simple", "Returns a simplified output with only essential columns: DatabaseName, BackupFinishDate, RecoveryModel, BackupSize, CompressedBackupSize, DatabaseCreationDate, UserName, ServerName, SqlVersion, and \r\nBackupPath.\r\nUse this when you need a quick overview of backup files without the full 50+ columns of detailed metadata.", "", false, "false", "False", "" ], [ "FileList", "Returns detailed information about each data and log file contained within the backup set, including logical names, physical paths, file sizes, and file types.\r\nUse this when planning restores to different locations or when you need to understand the file structure before performing a restore operation.", "", false, "false", "False", "" ], [ "StorageCredential", "Specifies the name of a SQL Server credential object that contains the authentication information for accessing Azure blob storage or S3-compatible object storage.\r\nRequired when reading backup files stored in Azure blob storage or S3. The credential must already exist on the target SQL Server instance.\r\nFor Azure: The credential must contain valid Azure storage account keys or SAS tokens.\r\nFor S3: The credential must use Identity = \u0027S3 Access Key\u0027 and Secret = \u0027AccessKeyID:SecretKeyID\u0027. Requires SQL Server 2022 or higher.", "AzureCredential,S3Credential", 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": "Trace", "CommandName": "Read-DbaTraceFile", "Name": "Read-DbaTraceFile", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Read-DbaTraceFile [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Path] \u003cString[]\u003e] [[-Database] \u003cString[]\u003e] [[-Login] \u003cString[]\u003e] [[-Spid] \u003cInt32[]\u003e] [[-EventClass] \u003cString[]\u003e] [[-ObjectType] \u003cString[]\u003e] [[-ErrorId] \u003cInt32[]\u003e] [[-EventSequence] \u003cInt32[]\u003e] [[-TextData] \u003cString[]\u003e] [[-ApplicationName] \u003cString[]\u003e] [[-ObjectName] \u003cString[]\u003e] [[-Where] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.Data.DataRow\nReturns one object per trace event from the SQL Server trace file, with the following properties added by the command:\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 properties come from fn_trace_gettable function, including:\r\n- TextData: SQL statement or command text associated with the event\r\n- BinaryData: Binary data captured for the event\r\n- DatabaseID: Numeric identifier of the database\r\n- DatabaseName: Name of the database affected by the event\r\n- LoginName: SQL Server login that performed the event\r\n- SPID: Session Process ID of the connection\r\n- StartTime: DateTime when the event started\r\n- EndTime: DateTime when the event ended\r\n- Duration: Duration of the event in milliseconds\r\n- Reads: Number of logical disk reads\r\n- Writes: Number of logical disk writes\r\n- CPU: CPU time consumed in milliseconds\r\n- EventClass: Event class number (e.g., 10 for SQL:StmtCompleted, 14 for Login)\r\n- EventSequence: Sequential number of the event\r\n- ApplicationName: Name of the client application\r\n- HostName: Name of the client computer\r\n- ObjectName: Name of the database object being accessed\r\n- ObjectType: Type of object being accessed\r\n- Error: SQL Server error number if an error occurred\r\n- Severity: Severity level of the error\r\n- Success: Whether the operation succeeded (0 or 1)\r\n- NestLevel: Nesting level of the stored procedure\r\n- LineNumber: Line number within the batch or procedure\r\n- TransactionID: Transaction identifier\r\n- NTUserName: Windows domain and user name\r\n- NTDomainName: Windows domain name\r\n- ColumnPermissions: Column-level permissions being checked\r\n- Permissions: Object permissions being checked\r\n- State: Object state\r\n- Mode: Lock mode (if applicable)\r\n- Handle: Handle reference\r\n- OwnerName: Name of the object owner\r\n- RoleName: Database role name\r\n- TargetUserName: Target user for impersonation operations\r\n- DBUserName: Database user name\r\n- LoginSid: SQL Server login SID\r\n- TargetLoginName: Target login for security operations\r\n- TargetLoginSid: Target login SID\r\n- LinkedServerName: Name of linked server being accessed\r\n- ProviderName: OLE DB provider name\r\n- MethodName: OLE DB method name\r\n- RowCounts: Number of rows affected\r\n- RequestID: Batch request ID\r\n- XactSequence: Transaction sequence number\r\n- BigintData1: First 64-bit integer data\r\n- BigintData2: Second 64-bit integer data\r\n- GUID: Globally unique identifier\r\n- IntegerData: Integer data value\r\n- IntegerData2: Second integer data value\r\n- ObjectID: Object ID number\r\n- ObjectID2: Second object ID number\r\n- EventSubClass: Event subclass number\r\n- IndexID: Index ID\r\n- ClientProcessID: Process ID of the client application\r\n- ServerName: Name of the SQL Server instance\r\n- Type: Type identifier\r\n- OwnerID: Owner object ID\r\n- ParentName: Parent object name\r\n- IsSystem: Whether the object is a system object (0 or 1)\r\n- Offset: Offset value for the event\r\n- SourceDatabaseID: Source database ID\r\n- SqlHandle: SQL handle reference\r\n- SessionLoginName: Session login name\r\n- PlanHandle: Query plan handle\r\n- GroupID: Group ID for the event\nAll properties are accessible using Select-Object * or standard pipeline operations.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRead-DbaTraceFile -SqlInstance sql2016 -Database master, tempdb -Path C:\\traces\\big.trc\nReads the tracefile C:\\traces\\big.trc, stored on the sql2016 sql server. Filters only results that have master or tempdb as the DatabaseName.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRead-DbaTraceFile -SqlInstance sql2016 -Database master, tempdb -Path C:\\traces\\big.trc -TextData \u0027EXEC SP_PROCOPTION\u0027\nReads the tracefile C:\\traces\\big.trc, stored on the sql2016 sql server.\r\nFilters only results that have master or tempdb as the DatabaseName and that have \u0027EXEC SP_PROCOPTION\u0027 somewhere in the text.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRead-DbaTraceFile -SqlInstance sql2016 -Path C:\\traces\\big.trc -Where \"LinkedServerName = \u0027myls\u0027 and StartTime \u003e \u00275/30/2017 4:27:52 PM\u0027\"\nReads the tracefile C:\\traces\\big.trc, stored on the sql2016 sql server.\r\nFilters only results where LinkServerName = myls and StartTime is greater than \u00275/30/2017 4:27:52 PM\u0027.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaTrace -SqlInstance sql2014 | Read-DbaTraceFile\nReads every trace file on sql2014", "Description": "Reads SQL Server trace files (.trc) using the fn_trace_gettable function and returns events as PowerShell objects for analysis. This function is essential for DBAs who need to investigate security incidents, audit database access, troubleshoot performance issues, or extract compliance data from trace files.\n\nThe function can read both active trace files and archived trace files, including SQL Server\u0027s default trace that automatically captures configuration changes, login failures, and other critical events. You can filter results by database, login, application, event type, or use custom WHERE clauses to pinpoint specific activities.\n\nCommon use cases include analyzing failed login attempts for security breaches, identifying slow-running queries affecting performance, tracking schema changes for change management, and extracting audit trails for compliance reporting.", "Links": "https://dbatools.io/Read-DbaTraceFile", "Synopsis": "Parses SQL Server trace files and extracts events for security auditing and performance analysis", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", 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)", "", "" ], [ "Path", "Specifies the full path to the trace file (.trc) on the SQL Server instance.\r\nWhen omitted, reads from the default system trace that automatically captures configuration changes and security events.\r\nUse this when analyzing specific trace files created by custom traces or archived default traces.", "", false, "true (ByPropertyName)", "", "" ], [ "Database", "Filters trace events to show only those affecting specific databases by name.\r\nUse this to focus analysis on particular databases when investigating issues or tracking changes.\r\nAccepts multiple database names and supports wildcards for pattern matching.", "", false, "false", "", "" ], [ "Login", "Filters trace events to show only those performed by specific SQL Server logins.\r\nEssential for security investigations to track activities by suspected user accounts or service accounts.\r\nAccepts multiple login names for comprehensive user activity analysis.", "", false, "false", "", "" ], [ "Spid", "Filters trace events to show only those from specific Session Process IDs (SPIDs).\r\nUseful for tracking all activities within particular database sessions or troubleshooting specific connection issues.\r\nAccepts multiple SPID values to monitor several concurrent sessions.", "", false, "false", "", "" ], [ "EventClass", "Filters trace events by event class numbers to focus on specific types of database activities.\r\nCommon values include login events (14), logout events (15), SQL statements (10-12), and security audit events (102-111).\r\nUse this to narrow analysis to particular event types like failed logins or DDL changes.", "", false, "false", "", "" ], [ "ObjectType", "Filters trace events by the type of database object being accessed or modified.\r\nCommon values include tables, views, stored procedures, functions, and triggers.\r\nUse this when investigating changes to specific types of database objects during schema modifications.", "", false, "false", "", "" ], [ "ErrorId", "Filters trace events to show only those with specific SQL Server error numbers.\r\nCommon values include login failures (18456), permission denied (229), and deadlock victims (1205).\r\nUse this to focus on particular error conditions when troubleshooting recurring issues or security events.", "", false, "false", "", "" ], [ "EventSequence", "Filters trace events by their sequence number within the trace file.\r\nUse this to retrieve specific events when you know their exact sequence numbers from previous analysis.\r\nHelpful for pinpointing events that occurred at precise moments during an incident.", "", false, "false", "", "" ], [ "TextData", "Filters trace events by searching within the SQL statements or command text using pattern matching.\r\nUse this to find specific queries, stored procedure calls, or SQL commands that contain particular keywords.\r\nSupports partial text matching, making it ideal for finding all queries containing specific table names or SQL constructs.", "", false, "false", "", "" ], [ "ApplicationName", "Filters trace events by the application name that initiated the database connection.\r\nUse this to isolate activities from specific applications like SQL Server Management Studio, custom applications, or services.\r\nSupports pattern matching to group similar application names or versions together.", "", false, "false", "", "" ], [ "ObjectName", "Filters trace events by the name of the database object being accessed or modified.\r\nUse this to track all operations against specific tables, views, procedures, or other database objects.\r\nSupports pattern matching to find objects with similar naming conventions or prefixes.", "", false, "false", "", "" ], [ "Where", "Specifies a custom SQL WHERE clause for complex filtering beyond the standard parameters.\r\nUse this for advanced queries combining multiple conditions, date ranges, or custom logic that other parameters cannot achieve.\r\nDo not include the word \"WHERE\" - it is added automatically. Here are the available columns:\nTextData\r\nBinaryData\r\nDatabaseID\r\nTransactionID\r\nLineNumber\r\nNTUserName\r\nNTDomainName\r\nHostName\r\nClientProcessID\r\nApplicationName\r\nLoginName\r\nSPID\r\nDuration\r\nStartTime\r\nEndTime\r\nReads\r\nWrites\r\nCPU\r\nPermissions\r\nSeverity\r\nEventSubClass\r\nObjectID\r\nSuccess\r\nIndexID\r\nIntegerData\r\nServerName\r\nEventClass\r\nObjectType\r\nNestLevel\r\nState\r\nError\r\nMode\r\nHandle\r\nObjectName\r\nDatabaseName\r\nFileName\r\nOwnerName\r\nRoleName\r\nTargetUserName\r\nDBUserName\r\nLoginSid\r\nTargetLoginName\r\nTargetLoginSid\r\nColumnPermissions\r\nLinkedServerName\r\nProviderName\r\nMethodName\r\nRowCounts\r\nRequestID\r\nXactSequence\r\nEventSequence\r\nBigintData1\r\nBigintData2\r\nGUID\r\nIntegerData2\r\nObjectID2\r\nType\r\nOwnerID\r\nParentName\r\nIsSystem\r\nOffset\r\nSourceDatabaseID\r\nSqlHandle\r\nSessionLoginName\r\nPlanHandle\r\nGroupID", "", 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": [ "Log", "LogFile", "Utility" ], "CommandName": "Read-DbaTransactionLog", "Name": "Read-DbaTransactionLog", "Author": "Stuart Moore (@napalmgram), stuart-moore.com", "Syntax": "Read-DbaTransactionLog [-SqlInstance] \u003cDbaInstanceParameter\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Database] \u003cObject\u003e [-IgnoreLimit] [[-RowLimit] \u003cInt32\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject[]\nReturns zero or more objects representing transaction log records from the fn_dblog function. Each object represents one transaction log record with all columns from fn_dblog as individual properties.\nCommon properties include:\r\n- RecoveryUnitId: Identifier of the recovery unit\r\n- LSN: Log Sequence Number identifying the position in the transaction log\r\n- LOP: The log operation type (e.g., INSERT, DELETE, UPDATE, ALLOCATE, DEALLOCATE, etc.)\r\n- Transaction ID: The transaction identifier\r\n- BeginTime: When the operation began\r\n- AllocUnitName: Name of the allocation unit affected\r\n- RowIdentifier: Identifies the specific row affected\r\n- DBFragId: Database fragmentation identifier\r\n- XactId: Extended transaction ID\r\n- XactOp: Extended transaction operation\r\n- Context: Operation context flags\r\n- AllocUnitId: Identifier of the allocation unit\r\n- ObjectId: Object ID of the table or index\r\n- IndexId: Index ID if applicable\r\n- PrevPageLSN: LSN of the previous page in the log chain\r\n- PageId: Page ID affected by the operation\nThe exact set of columns depends on SQL Server version and the specific operations recorded in the transaction log. Use Select-Object * to see all available properties.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$Log = Read-DbaTransactionLog -SqlInstance sql2016 -Database MyDatabase\nWill read the contents of the transaction log of MyDatabase on SQL Server Instance sql2016 into the local PowerShell object $Log\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$Log = Read-DbaTransactionLog -SqlInstance sql2016 -Database MyDatabase -IgnoreLimit\nWill read the contents of the transaction log of MyDatabase on SQL Server Instance sql2016 into the local PowerShell object $Log, ignoring the recommendation of not returning more that 0.5GB of log", "Description": "Uses SQL Server\u0027s built-in fn_dblog function to extract raw transaction log records from a live database, returning detailed information about every transaction in the format used by the SQL Server logging subsystem. This gives you access to the same low-level data that SQL Server uses internally to track database changes.\n\nThis is primarily useful for forensic analysis when you need to understand exactly what happened to your data - like tracking down who deleted records, when specific changes occurred, or analyzing transaction patterns for troubleshooting performance issues. The raw log data includes LSN numbers, transaction IDs, operation types, and other metadata that can help reconstruct the sequence of database modifications.\n\nA safety limit of 0.5GB has been implemented to prevent performance issues, since reading large transaction logs can impact both the target database and the system running this command. This limit is based on testing and can be overridden using the -IgnoreLimit switch, but be aware that processing very large logs may cause performance degradation on your SQL Server instance.", "Links": "https://dbatools.io/Read-DbaTransactionLog", "Synopsis": "Retrieves raw transaction log records from a database using fn_dblog for forensic analysis and troubleshooting", "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 database whose transaction log records you want to analyze. The database must be online and in a normal state.\r\nUse this to target the specific database where you need to investigate transaction activity or perform forensic analysis.", "", true, "false", "", "" ], [ "IgnoreLimit", "Bypasses the built-in 0.5GB safety limit that prevents performance issues when reading large transaction logs.\r\nUse this when you need to analyze databases with large active logs, but be aware it may impact SQL Server performance during execution.", "", false, "false", "False", "" ], [ "RowLimit", "Limits the number of transaction log records returned by adding a TOP clause to the fn_dblog query.\r\nUse this when you only need recent transactions or want to prevent memory issues with very large logs. Automatically enables IgnoreLimit when specified.", "", 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": [ "ExtendedEvent", "XE", "XEvent" ], "CommandName": "Read-DbaXEFile", "Name": "Read-DbaXEFile", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Read-DbaXEFile [-Path] \u003cObject[]\u003e [-Raw] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.XEvent.XELite.XEvent[] (when -Raw is specified)\nReturns the native XEvent objects from the XELite reader with full access to XEvent properties and methods for advanced programmatic processing.\nPSCustomObject[] (default)\nReturns one object per event in the trace file with dynamic properties based on the captured fields and actions. All objects include standard properties plus event-specific fields:\nStandard properties:\r\n- name: The name of the Extended Event\r\n- timestamp: The timestamp when the event was captured\nDynamic properties vary based on the Extended Events session configuration and captured actions:\r\n- All unique field names from the XEvent.Fields collection appear as individual properties\r\n- All unique action names from the XEvent.Actions collection appear as individual properties (action names are normalized to remove the leading package.action prefix)\nFor example, a deadlock trace might include properties like: database_id, duration, cpu_time, physical_reads, logical_reads, writes, priority, transaction_id, client_app_name, etc. A security audit \r\ntrace might include: client_principal_name, server_principal_name, statement, etc.\nUse Select-Object * to see all properties returned in the results.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRead-DbaXEFile -Path C:\\temp\\deadocks.xel\nReturns events from C:\\temp\\deadocks.xel.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-ChildItem C:\\temp\\xe\\*.xel | Read-DbaXEFile\nReturns events from all .xel files in C:\\temp\\xe.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaXESession -SqlInstance sql2019 -Session deadlocks | Read-DbaXEFile\nReads remote XEvents by accessing the file over the admin UNC share.", "Description": "Converts Extended Events trace files into PowerShell objects so you can analyze captured SQL Server events without needing SQL Server Management Studio. This function takes the raw XEvent data from .xel or .xem files and transforms it into structured objects with properties for each field and action in the trace.\n\nPerfect for post-incident analysis of deadlocks, performance issues, or security events that were captured by your Extended Events sessions. You can pipe the results to other PowerShell cmdlets for filtering, sorting, exporting to CSV, or building reports.\n\nWhen using pipeline input from Get-DbaXESession, the function automatically skips the file currently being written to avoid access conflicts, and can read files from remote servers via admin shares.", "Links": "https://dbatools.io/Read-DbaXEFile", "Synopsis": "Parses Extended Events trace files (.xel/.xem) into structured PowerShell objects for analysis", "Availability": "Windows, Linux, macOS", "Params": [ [ "Path", "Specifies the Extended Events file path (.xel or .xem), file objects, or XEvent session objects to read from. Supports local paths, UNC paths for remote files, and pipeline input from Get-ChildItem \r\nor Get-DbaXESession.\r\nWhen using session objects from Get-DbaXESession, automatically accesses files via admin shares and skips the current file being written to prevent access conflicts.", "FullName", true, "true (ByValue)", "", "" ], [ "Raw", "Returns the native Microsoft.SqlServer.XEvent.XELite.XEvent objects instead of structured PowerShell objects. Use this when you need direct access to the XEvent object properties and methods for \r\nadvanced programmatic processing.\r\nBy default, events are converted to PSCustomObjects with all fields and actions as individual properties for easier analysis and 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", "" ] ] }, { "Name": "Read-XEvent", "Description": null, "Synopsis": "\r\nRead-XEvent [-FileName \u003cstring\u003e] [-ConnectionString \u003cstring\u003e] [-SessionName \u003cstring\u003e] [\u003cCommonParameters\u003e]\r\n", "Outputs": "returnValue\r\n-----------\r\n@{type=}", "Alias": "", "CommandName": "Read-XEvent", "Availability": "Windows, Linux, macOS", "Links": null, "Examples": "", "Params": [ [ "ConnectionString", "", "", false, "false", null, "" ], [ "FileName", "", "FullName", false, "true (ByValue)", null, "" ], [ "SessionName", "", "", false, "false", null, "" ] ], "Syntax": "syntaxItem \r\n---------- \r\n{@{name=Read-XEvent; CommonParameters=True; WorkflowCommonParameters=False; parameter=System.Object[]}}" }, { "Tags": "Module", "CommandName": "Register-DbatoolsConfig", "Name": "Register-DbatoolsConfig", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Register-DbatoolsConfig [-Config \u003cConfig[]\u003e] [-FullName \u003cString[]\u003e] [-Scope {UserDefault | UserMandatory | SystemDefault | SystemMandatory | FileUserLocal | FileUserShared | FileSystem}] [-EnableException] [\u003cCommonParameters\u003e]\nRegister-DbatoolsConfig [-Module] \u003cString\u003e [[-Name] \u003cString\u003e] [-Scope {UserDefault | UserMandatory | SystemDefault | SystemMandatory | FileUserLocal | FileUserShared | FileSystem}] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "None\nThis function does not return output to the pipeline. Configuration settings are persisted to registry (Windows) or JSON files (cross-platform) based on the specified Scope parameter. Use \r\nGet-DbatoolsConfig to verify that settings have been registered.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbatoolsConfig message.style.* | Register-DbatoolsConfig\nRetrieves all configuration items that that start with message.style. and registers them in registry for the current user.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRegister-DbatoolsConfig -FullName \"message.consoleoutput.disable\" -Scope SystemDefault\nRetrieves the configuration item \"message.consoleoutput.disable\" and registers it in registry as the default setting for all users on this machine.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRegister-DbatoolsConfig -Module Message -Scope SystemMandatory\nRetrieves all configuration items of the module Message, then registers them in registry to enforce them for all users on the current system.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eSet-DbatoolsConfig -FullName sql.connection.trustcert -Value $true -PassThru | Register-DbatoolsConfig\nSet the \"sql.connection.trustcert\" configuration to be $true, and then use the -PassThru parameter\r\nto be able to pipe the output and register them in registry for the current user.", "Description": "Registers an existing configuration object in registry.\nThis allows simple persisting of settings across powershell consoles.\nIt also can be used to generate a registry template, which can then be used to create policies.", "Links": "https://dbatools.io/Register-DbatoolsConfig", "Synopsis": "Registers an existing configuration object in registry.", "Availability": "Windows, Linux, macOS", "Params": [ [ "Config", "Configuration object(s) to persist to registry or file system for future PowerShell sessions.\r\nAccepts pipeline input from Get-DbatoolsConfig to save specific settings like connection timeouts or SSL preferences.\r\nUse this when you have configuration objects you want to make permanent across dbatools sessions.", "", false, "true (ByValue)", "", "" ], [ "FullName", "Complete configuration setting name to register, such as \"sql.connection.trustcert\" or \"message.consoleoutput.disable\".\r\nSpecify this when you know the exact setting name and want to persist that specific configuration.\r\nUse Get-DbatoolsConfig to discover available configuration names in your environment.", "", false, "true (ByValue)", "", "" ], [ "Module", "Module name containing the configuration settings to register, such as \"Message\" or \"SqlInstance\".\r\nUse this to register all configuration settings for a particular dbatools module at once.\r\nCombine with -Name parameter to filter which settings within the module get registered.", "", true, "false", "", "" ], [ "Name", "Filters which configuration settings get registered when used with -Module parameter. Supports wildcards.\r\nUse this to register only specific settings within a module rather than all module settings.\r\nDefaults to \"*\" which includes all settings for the specified module.", "", false, "false", "*", "" ], [ "Scope", "Determines where the configuration is stored and who can access it.\r\nUserDefault applies to current user only, while SystemDefault affects all users on the machine.\r\nUse UserMandatory or SystemMandatory to enforce settings that cannot be overridden by individual users.", "", false, "false", "UserDefault", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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": "Remove-DbaAgDatabase", "Name": "Remove-DbaAgDatabase", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Remove-DbaAgDatabase [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-AvailabilityGroup] \u003cString[]\u003e] [[-InputObject] \u003cObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database successfully removed from the availability group.\nProperties:\r\n- ComputerName: The computer name of the SQL Server instance where the database was removed\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance format)\r\n- AvailabilityGroup: The name of the availability group from which the database was removed\r\n- Database: The name of the database that was removed\r\n- Status: String indicating the operation result (\"Removed\")", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaAgDatabase -SqlInstance sqlserver2012 -AvailabilityGroup ag1, ag2 -Confirm:$false\nRemoves all databases from the ag1 and ag2 availability groups on sqlserver2012. Does not prompt for confirmation.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaAgDatabase -SqlInstance sqlserver2012 -AvailabilityGroup ag1 -Database pubs -Confirm:$false\nRemoves the pubs database from the ag1 availability group on sqlserver2012. Does not prompt for confirmation.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sqlserver2012 -AvailabilityGroup availabilitygroup1 | Remove-DbaAgDatabase\nRemoves the availability groups returned from the Get-DbaAvailabilityGroup function. Prompts for confirmation.", "Description": "Removes databases from availability groups, effectively stopping replication and high availability protection for those databases. This is commonly needed when decommissioning databases, reconfiguring availability group membership during maintenance windows, or troubleshooting replication issues. The function safely removes the database from all replicas in the availability group while preserving the actual database files on each replica. You can target specific databases and availability groups, or use pipeline input from Get-DbaAgDatabase to remove multiple databases efficiently.", "Links": "https://dbatools.io/Remove-DbaAgDatabase", "Synopsis": "Removes databases from availability groups on 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", "", "" ], [ "Database", "Specifies which databases to remove from their availability groups. Accepts multiple database names as an array.\r\nRequired when using SqlInstance parameter. Use this to target specific databases rather than removing all databases from an availability group.", "", false, "false", "", "" ], [ "AvailabilityGroup", "Limits the operation to databases within specific availability groups. When specified, only databases belonging to these availability groups will be removed.\r\nUseful when you have databases with the same name across multiple availability groups and need to target specific groups.", "", false, "false", "", "" ], [ "InputObject", "Accepts availability group database objects from Get-DbaAgDatabase or database objects from Get-DbaDatabase through the pipeline.\r\nThis enables efficient batch operations and complex filtering scenarios using 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", "" ], [ "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": [ "Agent", "Alert" ], "CommandName": "Remove-DbaAgentAlert", "Name": "Remove-DbaAgentAlert", "Author": "Mikey Bronowski (@MikeyBronowski), bronowski.it", "Syntax": "Remove-DbaAgentAlert [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Alert \u003cString[]\u003e] [-ExcludeAlert \u003cString[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nRemove-DbaAgentAlert -InputObject \u003cAlert[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per alert removal attempt. Each object represents the status of removing a single SQL Agent alert from a SQL Server instance.\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 (service name)\r\n- SqlInstance: The full SQL Server instance name in the format ComputerName\\InstanceName\r\n- Name: The name of the SQL Agent alert that was removed\r\n- Status: Status message indicating the outcome of the removal (\"Dropped\" on success, or an error message on failure)\r\n- IsRemoved: Boolean indicating whether the SQL Agent alert was successfully removed ($true) or failed ($false)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaAgentAlert -SqlInstance localhost, localhost\\namedinstance\nRemoves all SQL Agent alerts on the localhost, localhost\\namedinstance instances.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaAgentAlert -SqlInstance localhost -Alert MyDatabaseAlert\nRemoves MyDatabaseAlert SQL Agent alert on the localhost.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaAgentAlert -SqlInstance SRV1 | Out-GridView -Title \u0027Select SQL Agent alert(s) to drop\u0027 -OutputMode Multiple | Remove-DbaAgentAlert\nUsing a pipeline this command gets all SQL Agent alerts on SRV1, lets the user select those to remove and then removes the selected SQL Agent alerts.", "Description": "Deletes SQL Server Agent alerts that monitor for specific errors, performance conditions, or system events.\nUseful for cleaning up obsolete alerts, removing test configurations, or managing alert policies across multiple instances.\nCan remove specific alerts by name, exclude certain alerts, or work with piped input from Get-DbaAgentAlert for selective removal.\nReturns detailed results showing which alerts were successfully removed and any errors encountered.", "Links": "https://dbatools.io/Remove-DbaAgentAlert", "Synopsis": "Removes SQL Server Agent alerts from specified instances.", "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).\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", "", "" ], [ "Alert", "Specifies the names of specific SQL Agent alerts to remove from the target instances.\r\nUse this when you need to remove particular alerts rather than all alerts on the server.\r\nAccepts an array of alert names for bulk removal operations.", "", false, "false", "", "" ], [ "ExcludeAlert", "Excludes specific SQL Agent alerts from removal when processing all alerts on an instance.\r\nUseful for bulk cleanup operations where you want to preserve certain critical alerts.\r\nOnly applies when the Alert parameter is not specified, allowing you to remove all alerts except those listed here.", "", false, "false", "", "" ], [ "InputObject", "Accepts SQL Agent alert objects from the pipeline, typically from Get-DbaAgentAlert.\r\nUse this for selective removal operations where you first query alerts with specific criteria and then remove the filtered results.\r\nEnables advanced scenarios like interactive selection using Out-GridView or complex filtering logic.", "", 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.\r\nThis is the default. Use -Confirm:$false to suppress these prompts.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Agent", "Alert", "AlertCategory" ], "CommandName": "Remove-DbaAgentAlertCategory", "Name": "Remove-DbaAgentAlertCategory", "Author": "Patrick Flynn (@sqllensman)", "Syntax": "Remove-DbaAgentAlertCategory [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Category \u003cString[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nRemove-DbaAgentAlertCategory -InputObject \u003cAlertCategory[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per alert category removal attempt. Each object represents the status of removing a single alert category from a SQL Server instance.\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 (service name)\r\n- SqlInstance: The full SQL Server instance name in the format ComputerName\\InstanceName\r\n- Name: The name of the alert category that was removed\r\n- Status: Status message indicating the outcome of the removal (\"Dropped\" on success, or an error message on failure)\r\n- IsRemoved: Boolean indicating whether the alert category was successfully removed ($true) or failed ($false)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaAgentAlertCategory -SqlInstance sql1 -Category \u0027Category 1\u0027\nRemove the alert category Category 1 from the instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaAgentAlertCategory -SqlInstance sql1 -Category Category1, Category2, Category3\nRemove multiple alert categories from the instance.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRemove-DbaAgentAlertCategory -SqlInstance sql1, sql2, sql3 -Category Category1, Category2, Category3\nRemove multiple alert categories from the multiple instances.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaAgentAlertCategory -SqlInstance SRV1 | Out-GridView -Title \u0027Select SQL Agent alert category(-ies) to drop\u0027 -OutputMode Multiple | Remove-DbaAgentAlertCategory\nUsing a pipeline this command gets all SQL Agent alert category(-ies) on SRV1, lets the user select those to remove and then removes the selected SQL Agent alert category(-ies).", "Description": "Removes custom alert categories from SQL Server Agent, useful for cleaning up unused organizational structures or standardizing alert management across environments.\nAny existing alerts that reference the removed category will automatically be reassigned to the [Uncategorized] category, so you don\u0027t need to manually update alert assignments before removal.\nThe function works with both individual category names and accepts pipeline input from Get-DbaAgentAlertCategory for bulk operations.\nReturns detailed status information showing which categories were successfully removed and any that failed with error details.", "Links": "https://dbatools.io/Remove-DbaAgentAlertCategory", "Synopsis": "Removes SQL Server Agent alert categories 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 2000 or greater.", "", 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", "", "" ], [ "Category", "Specifies the names of the alert categories to remove from SQL Server Agent. Accepts multiple category names for bulk removal.\r\nUse this to target specific custom categories you want to delete while keeping others intact.", "", false, "false", "", "" ], [ "InputObject", "Accepts alert category objects from Get-DbaAgentAlertCategory for pipeline-based operations.\r\nUse this when you need to filter or select categories interactively before removal, such as with Out-GridView.", "", 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": [ "Agent", "Job" ], "CommandName": "Remove-DbaAgentJob", "Name": "Remove-DbaAgentJob", "Author": "Sander Stad (@sqlstad, sqlstad.nl)", "Syntax": "Remove-DbaAgentJob [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Job] \u003cObject[]\u003e] [-KeepHistory] [-KeepUnusedSchedule] [[-InputObject] \u003cJob[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per job removed, 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)\r\n- Name: The job name that was removed\r\n- Status: The status of the removal operation (\"Dropped\" on success, or \"Failed. {error message}\" on failure)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaAgentJob -SqlInstance sql1 -Job Job1\nRemoves the job from the instance with the name Job1\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGetDbaAgentJob -SqlInstance sql1 -Job Job1 | Remove-DbaAgentJob -KeepHistory\nRemoves the job but keeps the history\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRemove-DbaAgentJob -SqlInstance sql1 -Job Job1 -KeepUnusedSchedule\nRemoves the job but keeps the unused schedules\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eRemove-DbaAgentJob -SqlInstance sql1, sql2, sql3 -Job Job1\nRemoves the job from multiple servers", "Description": "Removes SQL Server Agent jobs from the target instances using the sp_delete_job system stored procedure. By default, both job history and unused schedules are deleted along with the job itself. You can optionally preserve job execution history for compliance or troubleshooting purposes, and keep unused schedules that might be reused for other jobs. This function is commonly used when decommissioning applications, cleaning up test environments, or removing obsolete maintenance jobs during server consolidation projects.", "Links": "https://dbatools.io/Remove-DbaAgentJob", "Synopsis": "Removes SQL Server Agent jobs from one or more instances with options to preserve history and schedules.", "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, "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", "", "" ], [ "Job", "Specifies the name of the SQL Server Agent job to remove. Accepts one or more job names.\r\nUse this when you know the specific job names you want to delete, rather than piping job objects.", "", false, "false", "", "" ], [ "KeepHistory", "Preserves job execution history in the msdb.dbo.sysjobhistory tables when removing the job.\r\nUse this when you need to retain audit trails or troubleshooting information for compliance or analysis purposes.", "", false, "false", "False", "" ], [ "KeepUnusedSchedule", "Preserves job schedules that aren\u0027t used by other jobs when removing this job.\r\nUse this when you plan to reuse the schedule for new jobs or want to maintain schedule definitions for documentation purposes.", "", false, "false", "False", "" ], [ "InputObject", "Accepts SQL Server Agent job objects from the pipeline, typically from Get-DbaAgentJob.\r\nUse this approach when you need to filter jobs with complex criteria before removal or when processing jobs from multiple 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": [ "Agent", "Job", "JobCategory" ], "CommandName": "Remove-DbaAgentJobCategory", "Name": "Remove-DbaAgentJobCategory", "Author": "Sander Stad (@sqlstad, sqlstad.nl)", "Syntax": "Remove-DbaAgentJobCategory [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Category \u003cString[]\u003e] [-CategoryType \u003cString[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nRemove-DbaAgentJobCategory -InputObject \u003cJobCategory[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per category removed, 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)\r\n- Name: The job category name that was removed\r\n- Status: The status of the removal operation (\"Dropped\" on success, or an error message on failure)\r\n- IsRemoved: Boolean indicating whether the category was successfully removed (true) or failed (false)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaAgentJobCategory -SqlInstance sql1 -Category \u0027Category 1\u0027\nRemove the job category Category 1 from the instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaAgentJobCategory -SqlInstance sql1 -Category Category1, Category2, Category3\nRemove multiple job categories from the instance.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRemove-DbaAgentJobCategory -SqlInstance sql1, sql2, sql3 -Category Category1, Category2, Category3\nRemove multiple job categories from the multiple instances.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaAgentJobCategory -SqlInstance SRV1 | Out-GridView -Title \u0027Select SQL Agent job category(-ies) to drop\u0027 -OutputMode Multiple | Remove-DbaAgentJobCategory\nUsing a pipeline this command gets all SQL Agent job category(-ies) on SRV1, lets the user select those to remove and then removes the selected SQL Agent job category(-ies).", "Description": "Removes custom SQL Server Agent job categories that are no longer needed for job organization and management.\nThis is useful when cleaning up obsolete categories after reorganizing jobs or migrating workloads between environments.\nAny jobs currently assigned to a removed category will automatically be reassigned to the default \"[Uncategorized (Local)]\" category.\nThe function provides safety controls and detailed status reporting to ensure successful cleanup operations.", "Links": "https://dbatools.io/Remove-DbaAgentJobCategory", "Synopsis": "Removes SQL Server Agent job categories from one or more 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 2000 or greater.", "", 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", "", "" ], [ "Category", "Specifies the name of the SQL Agent job category to remove from the instance. Accepts multiple category names for batch operations.\r\nUse this when you need to clean up specific custom categories that are no longer needed for job organization.", "", false, "false", "", "" ], [ "CategoryType", "Filters categories by their type: \"LocalJob\" for single-server jobs, \"MultiServerJob\" for multi-server administration jobs, or \"None\" for uncategorized jobs.\r\nUse this to target specific category types when cleaning up job organization structures. If omitted, all category types will be processed.", "", false, "false", "", "LocalJob,MultiServerJob,None" ], [ "InputObject", "Accepts SQL Agent job category objects from the pipeline, typically from Get-DbaAgentJobCategory.\r\nUse this for interactive category selection workflows or when you need to filter categories before removal using Get-DbaAgentJobCategory\u0027s filtering options.", "", 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": [ "Agent", "Job", "JobStep" ], "CommandName": "Remove-DbaAgentJobStep", "Name": "Remove-DbaAgentJobStep", "Author": "Sander Stad (@sqlstad), sqlstad.nl", "Syntax": "Remove-DbaAgentJobStep [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Job] \u003cObject[]\u003e [-StepName] \u003cString\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "None\nThis function does not return any objects. It performs the removal operation and returns no output to the pipeline.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaAgentJobStep -SqlInstance sql1 -Job Job1 -StepName Step1\nRemove \u0027Step1\u0027 from job \u0027Job1\u0027 on sql1.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaAgentJobStep -SqlInstance sql1 -Job Job1, Job2, Job3 -StepName Step1\nRemove the job step from multiple jobs.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRemove-DbaAgentJobStep -SqlInstance sql1, sql2, sql3 -Job Job1 -StepName Step1\nRemove the job step from the job on multiple servers.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003esql1, sql2, sql3 | Remove-DbaAgentJobStep -Job Job1 -StepName Step1\nRemove the job step from the job on multiple servers using pipeline.", "Description": "Removes individual job steps from SQL Server Agent jobs by step name. This function validates that both the job and step exist before attempting removal, preventing errors when cleaning up outdated or broken job steps. Useful for job maintenance tasks like removing obsolete backup steps, failed notification steps, or deprecated processes without affecting the rest of the job workflow.", "Links": "https://dbatools.io/Remove-DbaAgentJobStep", "Synopsis": "Removes specified job steps from SQL Server Agent jobs.", "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 the SQL Agent job(s) from which to remove the step. Accepts multiple job names for bulk operations.\r\nUse this when you need to remove the same step from multiple jobs, such as cleaning up outdated notification steps across maintenance jobs.", "", true, "false", "", "" ], [ "StepName", "Specifies the exact name of the job step to remove from the specified jobs. Step names are case-sensitive and must match exactly.\r\nUse this when you need to remove specific steps like obsolete backup verification steps, deprecated notification steps, or failed job components.", "", 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", "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": [ "Agent", "Operator" ], "CommandName": "Remove-DbaAgentOperator", "Name": "Remove-DbaAgentOperator", "Author": "Tracy Boggiano (@TracyBoggiano), databasesuperhero.com", "Syntax": "Remove-DbaAgentOperator [-SqlInstance \u003cDbaInstanceParameter[]\u003e] [-SqlCredential \u003cPSCredential\u003e] [-Operator \u003cString[]\u003e] [-ExcludeOperator \u003cString[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nRemove-DbaAgentOperator [-SqlInstance \u003cDbaInstanceParameter[]\u003e] [-SqlCredential \u003cPSCredential\u003e] [-Operator \u003cString[]\u003e] [-ExcludeOperator \u003cString[]\u003e] -InputObject \u003cOperator[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per operator removal attempt 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- Name: The name of the operator that was removed\r\n- Status: Status message indicating \"Dropped\" on success or error message on failure\r\n- IsRemoved: Boolean indicating whether the operator was successfully removed (true) or removal failed (false)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaAgentOperator -SqlInstance sql01 -Operator DBA\nThis removes an operator named DBA from the instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgentOperator -SqlInstance SRV1 | Out-GridView -Title \u0027Select SQL Agent operator(s) to drop\u0027 -OutputMode Multiple | Remove-DbaAgentOperator\nUsing a pipeline this command gets all SQL Agent operator(s) on SRV1, lets the user select those to remove and then removes the selected SQL Agent alert category(-ies).", "Description": "Removes SQL Server Agent operators from specified instances, cleaning up notification contacts that are no longer needed.\n\nOperators are notification contacts used by SQL Server Agent to send alerts about job failures, system issues, or other events. This function helps you remove outdated operator accounts when employees leave, contact information changes, or you need to consolidate notification lists.\n\nThe function safely handles dependencies and provides detailed status output for each removal operation, making it suitable for both interactive cleanup and automated operator management scripts.", "Links": "https://dbatools.io/Remove-DbaAgentOperator", "Synopsis": "Removes SQL Server Agent operators from one or more 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 2000 or greater.", "", 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", "", "" ], [ "Operator", "Specifies the SQL Server Agent operator names to remove from the instance. Accepts multiple operator names for bulk removal.\r\nUse this when you need to remove specific operators by name, such as when employees leave or contact information becomes outdated.", "", false, "false", "", "" ], [ "ExcludeOperator", "Specifies operator names to skip during removal operations. Useful when removing multiple operators but want to preserve certain ones.\r\nUse this to protect critical operators from accidental deletion when performing bulk removals or scripted cleanup operations.", "", false, "false", "", "" ], [ "InputObject", "Accepts SQL Server Agent operator objects from Get-DbaAgentOperator for pipeline operations.\r\nThis parameter enables filtering operators before removal and supports interactive selection workflows using Out-GridView.", "", 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": [ "Agent", "Proxy" ], "CommandName": "Remove-DbaAgentProxy", "Name": "Remove-DbaAgentProxy", "Author": "Mikey Bronowski (@MikeyBronowski), bronowski.it", "Syntax": "Remove-DbaAgentProxy [-SqlInstance \u003cDbaInstanceParameter[]\u003e] [-SqlCredential \u003cPSCredential\u003e] [-Proxy \u003cString[]\u003e] [-ExcludeProxy \u003cString[]\u003e] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nRemove-DbaAgentProxy [-SqlInstance \u003cDbaInstanceParameter[]\u003e] [-SqlCredential \u003cPSCredential\u003e] [-Proxy \u003cString[]\u003e] [-ExcludeProxy \u003cString[]\u003e] -InputObject \u003cProxyAccount[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per proxy processed, containing removal status and details.\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 name of the SQL Agent proxy that was removed\r\n- Status: Result of the removal operation (\"Dropped\" for success, or error message for failures)\r\n- IsRemoved: Boolean indicating if the proxy was successfully removed ($true for success, $false for failures)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaAgentProxy -SqlInstance localhost, localhost\\namedinstance\nRemoves all SQL Agent proxies on the localhost, localhost\\namedinstance instances.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaAgentProxy -SqlInstance localhost -Proxy MyDatabaseProxy\nRemoves MyDatabaseProxy SQL Agent proxy on the localhost.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaAgentProxy -SqlInstance SRV1 | Out-GridView -Title \u0027Select SQL Agent proxy(s) to drop\u0027 -OutputMode Multiple | Remove-DbaAgentProxy\nUsing a pipeline this command gets all SQL Agent proxies on SRV1, lets the user select those to remove and then removes the selected SQL Agent proxies.", "Description": "Removes the SQL Agent proxy(s) that have passed through the pipeline.\nIf not used with a pipeline, Get-DbaAgentProxy will be executed with the parameters provided\nand the returned SQL Agent proxy(s) will be removed.", "Links": "https://dbatools.io/Remove-DbaAgentProxy", "Synopsis": "Removes SQL Agent agent proxy(s).", "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).\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", "", "" ], [ "Proxy", "Specifies one or more SQL Agent proxy account names to remove. Accepts wildcards for pattern matching.\r\nUse this when you need to remove specific proxy accounts instead of all proxies on the instance.\r\nCommon examples include service account proxies or job-specific proxy accounts that are no longer needed.", "", false, "false", "", "" ], [ "ExcludeProxy", "Specifies one or more SQL Agent proxy account names to exclude from removal. Accepts wildcards for pattern matching.\r\nUse this when removing multiple proxies but want to preserve certain critical proxy accounts.\r\nHelpful for bulk cleanup operations while protecting production service account proxies.", "", false, "false", "", "" ], [ "InputObject", "Accepts SQL Agent proxy objects from the pipeline, typically from Get-DbaAgentProxy.\r\nUse this parameter set when you need to filter or select specific proxies before removal.\r\nEnables advanced scenarios like interactive selection through Out-GridView or complex filtering logic.", "", 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.\r\nThis is the default. Use -Confirm:$false to suppress these prompts.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Agent", "Job", "Schedule" ], "CommandName": "Remove-DbaAgentSchedule", "Name": "Remove-DbaAgentSchedule", "Author": "Sander Stad (@sqlstad), sqlstad.nl", "Syntax": "Remove-DbaAgentSchedule [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Schedule] \u003cString[]\u003e] [[-ScheduleUid] \u003cString[]\u003e] [[-Id] \u003cInt32[]\u003e] [[-InputObject] \u003cScheduleBase[]\u003e] [-EnableException] [-Force] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per schedule processed, containing removal status and details.\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- Schedule: The name of the schedule that was removed\r\n- ScheduleId: The numeric ID of the schedule\r\n- ScheduleUid: The unique GUID identifier of the schedule\r\n- Status: Result of the removal operation (\"Dropped\" for success, or error message for failures)\r\n- IsRemoved: Boolean indicating if the schedule was successfully removed ($true for success, $false for failures)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaAgentSchedule -SqlInstance sql1 -Schedule weekly\nRemove the schedule weekly.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaAgentSchedule -SqlInstance sql1 -Schedule weekly -Force\nRemove the schedule weekly even if the schedule is being used by jobs.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRemove-DbaAgentSchedule -SqlInstance sql1 -Schedule daily, weekly\nRemove multiple schedules.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eRemove-DbaAgentSchedule -SqlInstance sql1, sql2, sql3 -Schedule daily, weekly\nRemove the schedule on multiple servers for multiple schedules.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaAgentSchedule -SqlInstance sql1 -Schedule sched1, sched2, sched3 | Remove-DbaAgentSchedule\nRemove the schedules using a pipeline.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eRemove-DbaAgentSchedule -SqlInstance sql1, sql2, sql3 -ScheduleUid \u0027bf57fa7e-7720-4936-85a0-87d279db7eb7\u0027\nRemove the schedules using the schedule uid.", "Description": "Removes SQL Server Agent schedules from the msdb database, handling both unused schedules and those currently assigned to jobs. The function first removes schedule associations from any jobs using the schedule, then drops the schedule itself to prevent orphaned references. Use this when cleaning up unused schedules during maintenance, consolidating multiple schedules, or removing schedules as part of job reorganization. By default, schedules in use by jobs are protected and require the -Force parameter to remove.", "Links": "https://dbatools.io/Remove-DbaAgentSchedule", "Synopsis": "Removes SQL Server Agent schedules from one or more 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 2000 or greater.", "", 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", "", "" ], [ "Schedule", "Specifies the name(s) of SQL Server Agent schedules to remove from the msdb database.\r\nUse this when you know the schedule name but need to be aware that multiple schedules can share the same name.\r\nWhen multiple schedules have identical names, you\u0027ll need to use -Id or -ScheduleUid to target a specific schedule.", "Schedules,Name", false, "false", "", "" ], [ "ScheduleUid", "Specifies the unique GUID identifier of specific SQL Server Agent schedules to remove.\r\nUse this when you need to target an exact schedule, especially when multiple schedules share the same name.\r\nThe ScheduleUid ensures you\u0027re removing the precise schedule without ambiguity.", "Uid", false, "false", "", "" ], [ "Id", "Specifies the numeric schedule ID(s) to remove from SQL Server Agent.\r\nUse this when you have the specific schedule ID number, typically obtained from Get-DbaAgentSchedule output.\r\nThe ID provides an alternative to name-based removal when dealing with duplicate schedule names.", "", false, "false", "", "" ], [ "InputObject", "Accepts schedule objects from the pipeline, typically from Get-DbaAgentSchedule output.\r\nUse this when you want to filter schedules first with Get-DbaAgentSchedule, then pipe the results for removal.\r\nThis approach allows for complex filtering and review before deletion.", "", 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", "" ], [ "Force", "Bypasses the protection that prevents removal of schedules currently assigned to jobs.\r\nWithout this parameter, schedules in use by jobs are protected and will not be removed.\r\nUse this when you need to clean up schedules and automatically remove their job associations first.", "", 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": "Remove-DbaAgListener", "Name": "Remove-DbaAgListener", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Remove-DbaAgListener [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Listener] \u003cString[]\u003e] [[-AvailabilityGroup] \u003cString[]\u003e] [[-InputObject] \u003cAvailabilityGroupListener[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per listener that is successfully removed from the availability group.\nProperties:\r\n- ComputerName: The computer name of the SQL Server instance hosting the listener\r\n- InstanceName: The SQL Server instance name (the named instance or MSSQLSERVER for default instance)\r\n- SqlInstance: The full SQL Server instance name in the format ComputerName\\InstanceName\r\n- AvailabilityGroup: Name of the availability group from which the listener was removed\r\n- Listener: The name of the availability group listener that was removed\r\n- Status: The status of the operation; always \"Removed\" for successful removals", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaAgListener -SqlInstance sqlserver2012 -AvailabilityGroup ag1, ag2 -Confirm:$false\nRemoves the ag1 and ag2 availability groups on sqlserver2012. Does not prompt for confirmation.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sqlserver2012 -AvailabilityGroup availabilitygroup1 | Remove-DbaAgListener\nRemoves the listeners returned from the Get-DbaAvailabilityGroup function. Prompts for confirmation.", "Description": "Removes availability group listeners from SQL Server instances, permanently deleting the virtual network name and IP address configuration that clients use to connect to availability group databases. This operation is typically performed during decommissioning, reconfiguration, or when consolidating listeners. Once removed, applications will need to connect directly to individual replicas or use a different listener. The function can target specific listeners by name or remove all listeners from specified availability groups.", "Links": "https://dbatools.io/Remove-DbaAgListener", "Synopsis": "Removes availability group listeners 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", "", "" ], [ "Listener", "Specifies the name of specific availability group listeners to remove. Required when using SqlInstance parameter.\r\nUse this when you need to remove particular listeners rather than all listeners from availability groups.", "", false, "false", "", "" ], [ "AvailabilityGroup", "Filters listener removal to only those within the specified availability groups.\r\nUse this when you want to remove listeners from particular AGs while preserving listeners from other availability groups on the same instance.", "", false, "false", "", "" ], [ "InputObject", "Accepts availability group listener objects from the pipeline, typically from Get-DbaAgListener.\r\nUse this when you need to remove listeners that have been filtered or selected through other dbatools 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", "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": "Remove-DbaAgReplica", "Name": "Remove-DbaAgReplica", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Remove-DbaAgReplica [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-AvailabilityGroup] \u003cString[]\u003e] [[-Replica] \u003cString[]\u003e] [[-InputObject] \u003cAvailabilityReplica[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per replica that is successfully removed from the availability group.\nProperties:\r\n- ComputerName: The computer name of the SQL Server instance hosting the replica\r\n- InstanceName: The SQL Server instance name (the named instance or MSSQLSERVER for default instance)\r\n- SqlInstance: The full SQL Server instance name in the format ComputerName\\InstanceName\r\n- AvailabilityGroup: Name of the availability group from which the replica was removed\r\n- Replica: The name of the replica that was removed\r\n- Status: The status of the operation; always \"Removed\" for successful removals", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaAgReplica -SqlInstance sql2017a -AvailabilityGroup SharePoint -Replica sp1\nRemoves the sp1 replica from the SharePoint ag on sql2017a. Prompts for confirmation.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaAgReplica -SqlInstance sql2017a | Select-Object *\nReturns full object properties on all availability group replicas found on sql2017a", "Description": "Removes secondary replicas from Availability Groups by calling the Drop() method on the replica object. This is commonly used when decommissioning servers, scaling down your availability group topology, or removing failed replicas that cannot be recovered. The function accepts either direct SQL instance parameters or piped input from Get-DbaAgReplica for batch operations. All removal operations require explicit confirmation due to the high-impact nature of this change.", "Links": "https://dbatools.io/Remove-DbaAgReplica", "Synopsis": "Removes secondary replicas from SQL Server Availability Groups", "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 the availability group(s) containing the replicas to remove. Accepts wildcards for pattern matching.\r\nUse this to limit the removal operation to specific availability groups when you have multiple AGs on the instance.", "", false, "false", "", "" ], [ "Replica", "Specifies the name(s) of the availability group replicas to remove from the AG configuration. Accepts wildcards for pattern matching.\r\nThis parameter is required when using SqlInstance and typically matches the server name hosting the replica you want to remove.", "", false, "false", "", "" ], [ "InputObject", "Accepts availability group replica objects from the pipeline, typically from Get-DbaAgReplica output.\r\nUse this for batch operations when you need to remove multiple replicas or want to filter replicas before removal.", "", 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": "Remove-DbaAvailabilityGroup", "Name": "Remove-DbaAvailabilityGroup", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Remove-DbaAvailabilityGroup [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-AvailabilityGroup] \u003cString[]\u003e] [-AllAvailabilityGroups] [[-InputObject] \u003cAvailabilityGroup[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per availability group that is successfully removed.\nProperties:\r\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\" for default instance)\r\n- SqlInstance: The full SQL Server instance name in format ComputerName\\InstanceName\r\n- AvailabilityGroup: The name of the availability group that was removed\r\n- Status: Always \"Removed\" when the availability group is successfully dropped", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaAvailabilityGroup -SqlInstance sqlserver2012 -AllAvailabilityGroups\nRemoves all availability groups on the sqlserver2014 instance. Prompts for confirmation.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaAvailabilityGroup -SqlInstance sqlserver2012 -AvailabilityGroup ag1, ag2 -Confirm:$false\nRemoves the ag1 and ag2 availability groups on sqlserver2012. Does not prompt for confirmation.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sqlserver2012 -AvailabilityGroup availabilitygroup1 | Remove-DbaAvailabilityGroup\nRemoves the availability groups returned from the Get-DbaAvailabilityGroup function. Prompts for confirmation.", "Description": "Removes availability groups from SQL Server instances by executing the DROP AVAILABILITY GROUP T-SQL command. This is typically used when decommissioning high availability setups, migrating to different solutions, or cleaning up test environments.\n\nThe function handles the complex considerations around properly removing availability groups to avoid leaving databases in problematic states. If possible, remove the availability group only while connected to the server instance that hosts the primary replica.\nWhen the availability group is dropped from the primary replica, changes are allowed in the former primary databases (without high availability protection).\nDeleting an availability group from a secondary replica leaves the primary replica in the RESTORING state, and changes are not allowed on the databases.\n\nAvoid dropping an availability group when the Windows Server Failover Clustering (WSFC) cluster has no quorum.\nIf you must drop an availability group while the cluster lacks quorum, the metadata availability group that is stored in the cluster is not removed.\nAfter the cluster regains quorum, you will need to drop the availability group again to remove it from the WSFC cluster.\n\nFor more information: https://docs.microsoft.com/en-us/sql/t-sql/statements/drop-availability-group-transact-sql", "Links": "https://dbatools.io/Remove-DbaAvailabilityGroup", "Synopsis": "Removes availability groups from SQL Server instances using DROP AVAILABILITY GROUP.", "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 the name(s) of specific availability groups to remove. Accepts multiple values and wildcards for pattern matching.\r\nUse this when you need to remove only certain availability groups rather than all groups on the instance.", "", false, "false", "", "" ], [ "AllAvailabilityGroups", "Removes all availability groups found on the specified SQL Server instance.\r\nUse this switch when decommissioning a server or performing bulk cleanup operations.", "", false, "false", "False", "" ], [ "InputObject", "Accepts availability group objects from Get-DbaAvailabilityGroup for pipeline operations.\r\nUse this when you need to filter or pre-process availability groups before removal.", "", 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": [ "Backup", "DisasterRecovery" ], "CommandName": "Remove-DbaBackup", "Name": "Remove-DbaBackup", "Author": "Chris Sommer (@cjsommer), www.cjsommer.com", "Syntax": "Remove-DbaBackup [-Path] \u003cString\u003e [-BackupFileExtension] \u003cString\u003e [-RetentionPeriod] \u003cString\u003e [-CheckArchiveBit] [-RemoveEmptyBackupFolder] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "None\nThis function does not return any objects to the pipeline. It performs file and folder deletion operations based on the specified retention period and parameters. Use -WhatIf to see what would be \r\ndeleted without actually removing files.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaBackup -Path \u0027C:\\MSSQL\\SQL Backup\\\u0027 -BackupFileExtension trn -RetentionPeriod 48h\n\u0027*.trn\u0027 files in \u0027C:\\MSSQL\\SQL Backup\\\u0027 and all subdirectories that are more than 48 hours old will be removed.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaBackup -Path \u0027C:\\MSSQL\\SQL Backup\\\u0027 -BackupFileExtension trn -RetentionPeriod 48h -WhatIf\nSame as example #1, but doesn\u0027t actually remove any files. The function will instead show you what would be done.\r\nThis is useful when first experimenting with using the function.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRemove-DbaBackup -Path \u0027C:\\MSSQL\\Backup\\\u0027 -BackupFileExtension bak -RetentionPeriod 7d -CheckArchiveBit\n\u0027*.bak\u0027 files in \u0027C:\\MSSQL\\Backup\\\u0027 and all subdirectories that are more than 7 days old will be removed, but only if the files have been backed up to another location as verified by checking the \r\nArchive bit.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eRemove-DbaBackup -Path \u0027C:\\MSSQL\\Backup\\\u0027 -BackupFileExtension bak -RetentionPeriod 1w -RemoveEmptyBackupFolder\n\u0027*.bak\u0027 files in \u0027C:\\MSSQL\\Backup\\\u0027 and all subdirectories that are more than 1 week old will be removed. Any folders left empty will be removed as well.", "Description": "Recursively searches backup directories and removes SQL Server backup files older than your specified retention period. This function automates the tedious process of manually cleaning up old backup files to free disk space and maintain storage compliance.\n\nYou can target specific backup types by extension (.bak, .trn, .dif) and define retention periods using flexible time units (hours, days, weeks, months). The Archive bit check ensures files are only deleted after they\u0027ve been backed up to another location, preventing accidental loss of unarchived backups.\n\nReplaces the backup cleanup functionality found in SQL Server maintenance plans with more granular control and PowerShell automation. Optionally removes empty backup folders after file cleanup to keep your backup directory structure tidy.", "Links": "https://dbatools.io/Remove-DbaBackup", "Synopsis": "Removes SQL Server backup files from disk based on retention policies and file extension criteria.", "Availability": "Windows, Linux, macOS", "Params": [ [ "Path", "Specifies the root directory where backup files are stored for cleanup. The function recursively searches all subdirectories from this location.\r\nUse this to target your primary backup storage location, whether it\u0027s a local drive, network share, or mounted backup volume.", "BackupFolder", true, "false", "", "" ], [ "BackupFileExtension", "Specifies the file extension for the backup type to clean up. Common values are \u0027bak\u0027 for full backups, \u0027trn\u0027 for transaction log backups, or \u0027dif\u0027 for differential backups.\r\nUse this to target specific backup types during cleanup, allowing you to apply different retention policies for each backup type. Do not include the period.", "", true, "false", "", "" ], [ "RetentionPeriod", "Defines how long to keep backup files before deletion, formatted as number plus unit (48h, 7d, 4w, 1m).\r\nUse shorter periods for transaction log backups (24h-48h) and longer periods for full backups (1w-4w) based on your recovery requirements and storage capacity.\nValid units: h=hours, d=days, w=weeks, m=months\r\nExamples: \u002748h\u0027 keeps files for 48 hours, \u00277d\u0027 for 7 days, \u00274w\u0027 for 4 weeks, \u00271m\u0027 for 1 month", "", true, "false", "", "" ], [ "CheckArchiveBit", "Prevents deletion of files that haven\u0027t been archived to tape or another backup location by checking the Windows Archive bit.\r\nUse this when you have a two-tier backup strategy where files are first copied to disk, then archived to tape or cloud storage before cleanup.", "", false, "false", "False", "" ], [ "RemoveEmptyBackupFolder", "Removes directories that become empty after backup file cleanup to prevent folder structure clutter.\r\nUse this to maintain a clean backup directory structure, especially when backup files are organized by database or date folders.", "", 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.i", "cf", false, "false", "", "" ] ] }, { "Tags": [ "SqlClient", "Alias" ], "CommandName": "Remove-DbaClientAlias", "Name": "Remove-DbaClientAlias", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Remove-DbaClientAlias [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-Alias] \u003cString[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per alias that was successfully removed from the registry.\nProperties:\r\n- ComputerName: The name of the computer where the alias was removed\r\n- Architecture: Registry architecture where the alias was removed (\"32-bit\" or \"64-bit\")\r\n- Alias: The name of the SQL Server client alias that was removed\r\n- Status: The result status, typically \"Removed\" when successful", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaClientAlias -ComputerName workstationX -Alias sqlps\nRemoves the sqlps SQL Client alias on workstationX\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaClientAlias | Remove-DbaClientAlias\nRemoves all SQL Server client aliases on the local computer", "Description": "Removes SQL Server client aliases from the Windows registry by deleting entries from both 32-bit and 64-bit registry locations.\nClient aliases redirect SQL Server connection requests to different servers or instances, but outdated or incorrect aliases can cause connection failures.\nThis function provides a programmatic way to clean up these aliases when the deprecated cliconfg.exe utility is not available or when managing multiple computers remotely.\nCommonly used when decommissioning servers, updating connection strings, or troubleshooting connectivity issues caused by stale alias configurations.", "Links": "https://dbatools.io/Remove-DbaClientAlias", "Synopsis": "Removes SQL Server client aliases from Windows registry on local or remote computers", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the target computer(s) where SQL Server client aliases will be removed from the Windows registry.\r\nUse this when you need to clean up aliases on remote workstations or application servers.\r\nDefaults to the local computer if not specified.", "", false, "true (ByPropertyName)", "$env:COMPUTERNAME", "" ], [ "Credential", "Allows you to login to remote computers using alternative credentials", "", false, "false", "", "" ], [ "Alias", "Specifies the SQL Server client alias name(s) to remove from both 32-bit and 64-bit registry locations.\r\nUse this to clean up outdated aliases that redirect connections to decommissioned servers or incorrect instances.\r\nAccepts multiple alias names for bulk cleanup operations.", "AliasName", true, "true (ByPropertyName)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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": [ "ComputerManagement", "CIM" ], "CommandName": "Remove-DbaCmConnection", "Name": "Remove-DbaCmConnection", "Author": "Friedrich Weinmann (@FredWeinmann)", "Syntax": "Remove-DbaCmConnection [-ComputerName] \u003cDbaCmConnectionParameter[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "None\nThis command does not return any output to the pipeline. It only modifies the internal dbatools connection cache by removing the specified cached connections.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaCmConnection -ComputerName sql2014\nRemoves the cached connection to the server sql2014 from the cache.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaCmConnection | Remove-DbaCmConnection\nClears the entire connection cache.", "Description": "Clears cached connection objects that dbatools uses for remote computer management operations like accessing Windows services, registry, and file systems on SQL Server instances.\nWhen you run dbatools commands against remote servers, these connections are automatically created and cached to improve performance and reduce authentication overhead.\nThis function lets you remove specific cached connections or clear the entire cache, which is useful when credentials change, connections become stale, or you need to force fresh authentication for troubleshooting.", "Links": "https://dbatools.io/Remove-DbaCmConnection", "Synopsis": "Removes cached Windows Management and CIM connections from the dbatools connection cache.", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the computer name(s) whose cached connections should be removed from the dbatools connection cache. Accepts computer names as strings or connection objects from Get-DbaCmConnection.\r\nUse this when you need to clear stale connections after credential changes, network issues, or when troubleshooting remote computer management problems.", "", 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", "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": [ "Certificate", "Security" ], "CommandName": "Remove-DbaComputerCertificate", "Name": "Remove-DbaComputerCertificate", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Remove-DbaComputerCertificate [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-Thumbprint] \u003cString[]\u003e [[-Store] \u003cString\u003e] [[-Folder] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per certificate removal attempt. Each object contains the following properties:\r\n- ComputerName: The computer name where the certificate removal was attempted\r\n- Store: The certificate store location (LocalMachine or CurrentUser)\r\n- Folder: The certificate store folder/subfolder where the certificate was located (My, Root, TrustedPeople, etc.)\r\n- Thumbprint: The SHA-1 hash thumbprint of the certificate that was targeted for removal\r\n- Status: The status of the removal operation. Shows \"Removed\" on success, or \"Certificate not found in Cert:\\$Store\\$Folder\" if the certificate was not found", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaComputerCertificate -ComputerName Server1 -Thumbprint C2BBE81A94FEE7A26FFF86C2DFDAF6BFD28C6C94\nRemoves certificate with thumbprint C2BBE81A94FEE7A26FFF86C2DFDAF6BFD28C6C94 in the LocalMachine store on Server1\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaComputerCertificate | Where-Object Thumbprint -eq E0A071E387396723C45E92D42B2D497C6A182340 | Remove-DbaComputerCertificate\nRemoves certificate using the pipeline\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRemove-DbaComputerCertificate -ComputerName Server1 -Thumbprint C2BBE81A94FEE7A26FFF86C2DFDAF6BFD28C6C94 -Store User -Folder My\nRemoves certificate with thumbprint C2BBE81A94FEE7A26FFF86C2DFDAF6BFD28C6C94 in the User\\My (Personal) store on Server1", "Description": "Removes certificates from Windows certificate stores on local or remote computers using PowerShell remoting. This is essential for managing SSL/TLS certificates used by SQL Server instances for encrypted connections and authentication. DBAs commonly use this to clean up expired certificates, remove compromised certificates during security incidents, or manage certificate lifecycle during SQL Server migrations and decommissions. The function targets specific certificates by thumbprint and can work across multiple certificate stores and folders.", "Links": "https://dbatools.io/Remove-DbaComputerCertificate", "Synopsis": "Removes certificates from Windows certificate stores on local or remote computers", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the target computer(s) where certificates will be removed. Defaults to localhost.\r\nUse this when managing SSL certificates across multiple SQL Server instances or cleaning up certificates on remote servers during migrations.", "", false, "false", "$env:COMPUTERNAME", "" ], [ "Credential", "Allows you to login to $ComputerName using alternative credentials", "", false, "false", "", "" ], [ "Thumbprint", "Specifies the unique thumbprint(s) of the certificate(s) to remove. This is the SHA-1 hash that uniquely identifies each certificate.\r\nUse Get-DbaComputerCertificate to find thumbprints of certificates you want to remove, commonly needed when cleaning up expired SSL certificates or removing compromised certificates.", "", true, "true (ByPropertyName)", "", "" ], [ "Store", "Specifies the certificate store location where certificates will be removed. Defaults to LocalMachine.\r\nUse LocalMachine for system-wide certificates (typical for SQL Server SSL certificates) or CurrentUser for user-specific certificates.", "", false, "false", "LocalMachine", "" ], [ "Folder", "Specifies the certificate store folder (subfolder) where certificates will be removed. Defaults to \u0027My\u0027 (Personal certificates).\r\nCommon folders include \u0027My\u0027 for SSL certificates used by SQL Server, \u0027Root\u0027 for trusted root certificates, or \u0027TrustedPeople\u0027 for trusted person certificates.", "", false, "false", "My", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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": [ "Security", "Credential" ], "CommandName": "Remove-DbaCredential", "Name": "Remove-DbaCredential", "Author": "Mikey Bronowski (@MikeyBronowski), bronowski.it", "Syntax": "Remove-DbaCredential [-SqlInstance \u003cDbaInstanceParameter[]\u003e] [-SqlCredential \u003cPSCredential\u003e] [-Credential \u003cString[]\u003e] [-ExcludeCredential \u003cString[]\u003e] [-Identity \u003cString[]\u003e] [-ExcludeIdentity \u003cString[]\u003e] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nRemove-DbaCredential [-SqlInstance \u003cDbaInstanceParameter[]\u003e] [-SqlCredential \u003cPSCredential\u003e] [-Credential \u003cString[]\u003e] [-ExcludeCredential \u003cString[]\u003e] [-Identity \u003cString[]\u003e] [-ExcludeIdentity \u003cString[]\u003e] -InputObject \u003cCredential[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per credential removed. Each object contains 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)\r\n- Name: The name of the SQL credential that was targeted for removal\r\n- Status: The status of the removal operation. Shows \"Dropped\" on success, or the error message on failure\r\n- IsRemoved: Boolean indicating whether the credential was successfully removed ($true) or the removal failed ($false)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaCredential -SqlInstance localhost, localhost\\namedinstance\nRemoves all SQL credentials on the localhost, localhost\\namedinstance instances.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaCredential -SqlInstance localhost -Credential MyDatabaseCredential\nRemoves MyDatabaseCredential SQL credential on the localhost.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaCredential -SqlInstance SRV1 | Out-GridView -Title \u0027Select SQL credential(s) to drop\u0027 -OutputMode Multiple | Remove-DbaCredential\nUsing a pipeline this command gets all SQL credentials on SRV1, lets the user select those to remove and then removes the selected SQL credentials.", "Description": "Removes the SQL credential(s) that have passed through the pipeline.\nIf not used with a pipeline, Get-DbaCredential will be executed with the parameters provided\nand the returned SQL credential(s) will be removed.", "Links": "https://dbatools.io/Remove-DbaCredential", "Synopsis": "Removes SQL credential(s).", "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).\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", "", "" ], [ "Credential", "Specifies one or more SQL Server credential names to remove from the instance. Accepts wildcards for pattern matching.\r\nUse this to target specific credentials instead of removing all credentials on the server.", "", false, "false", "", "" ], [ "ExcludeCredential", "Specifies one or more SQL Server credential names to exclude from removal. Accepts wildcards for pattern matching.\r\nUse this when you want to remove most credentials but preserve certain ones like service account or backup credentials.", "", false, "false", "", "" ], [ "Identity", "Filters credentials by their associated identity (the Windows account or certificate the credential represents).\r\nUse this to remove credentials based on the underlying identity rather than the credential name. Enclose identities with spaces in quotes.", "", false, "false", "", "" ], [ "ExcludeIdentity", "Specifies identities to exclude from credential removal operations.\r\nUse this to preserve credentials associated with specific Windows accounts or certificates when removing others.", "", false, "false", "", "" ], [ "InputObject", "Accepts credential objects from Get-DbaCredential for pipeline operations.\r\nUse this to chain credential discovery and removal operations, enabling selective removal through Out-GridView or other filters.", "", 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.\r\nThis is the default. Use -Confirm:$false to suppress these prompts.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "General", "Error" ], "CommandName": "Remove-DbaCustomError", "Name": "Remove-DbaCustomError", "Author": "Adam Lancaster, github.com/lancasteradam", "Syntax": "Remove-DbaCustomError [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-MessageID] \u003cInt32\u003e] [[-Language] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "None\nThis command does not return any output objects. It performs the removal operation on the SQL Server instance and returns control to the pipeline without emitting results.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaCustomError -SqlInstance sqldev01, sqldev02 -MessageID 70001 -Language \"French\"\nRemoves the custom message on the sqldev01 and sqldev02 instances with ID 70001 and language French.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaCustomError -SqlInstance sqldev01, sqldev02 -MessageID 70001 -Language \"All\"\nRemoves all custom messages on the sqldev01 and sqldev02 instances with ID 70001.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$server = Connect-DbaInstance sqldev01\nPS C:\\\u003e $newMessage = New-DbaCustomError -SqlInstance $server -MessageID 70000 -Severity 16 -MessageText \"test_70000\"\nCreates a new custom message on the sqldev01 instance with ID 70000, severity 16, and text \"test_70000\"\nTo modify the custom message at a later time the following can be done to change the severity from 16 to 20:\nPS C:\\\u003e $original = $server.UserDefinedMessages | Where-Object ID -eq 70000\r\nPS C:\\\u003e $messageID = $original.ID\r\nPS C:\\\u003e $severity = 20\r\nPS C:\\\u003e $text = $original.Text\r\nPS C:\\\u003e $language = $original.Language\r\nPS C:\\\u003e $removed = Remove-DbaCustomError -SqlInstance $server -MessageID 70000\r\nPS C:\\\u003e $alteredMessage = New-DbaCustomError -SqlInstance $server -MessageID $messageID -Severity $severity -MessageText $text -Language $language -WithLog\nThe resulting updated message object is available in $alteredMessage.", "Description": "Removes custom error messages that applications have added to SQL Server\u0027s sys.messages catalog, cleaning up obsolete or unwanted user-defined messages with IDs between 50001 and 2147483647. This is essential when decommissioning applications, cleaning up test environments, or managing custom error message lifecycles during application deployments. You can remove messages for specific languages or all language versions of a message ID at once.", "Links": "https://dbatools.io/Remove-DbaCustomError", "Synopsis": "Removes user-defined error messages from the sys.messages system catalog", "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).\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", "", "" ], [ "MessageID", "Specifies the custom error message ID to remove from the sys.messages catalog.\r\nMust be between 50001 and 2147483647, which is the valid range for user-defined error messages.\r\nUse this to target specific custom errors that applications have registered with SQL Server.", "", false, "false", "0", "" ], [ "Language", "Specifies which language version of the custom error message to remove.\r\nAccepts language names or aliases from sys.syslanguages (like \u0027English\u0027, \u0027French\u0027, \u0027Deutsch\u0027).\r\nUse \u0027All\u0027 to remove all language versions of the message ID at once. Defaults to \u0027English\u0027.", "", false, "false", "English", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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": [ "Delete", "Database" ], "CommandName": "Remove-DbaDatabase", "Name": "Remove-DbaDatabase", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Remove-DbaDatabase [-SqlCredential \u003cPSCredential\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nRemove-DbaDatabase -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] -Database \u003cObject[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nRemove-DbaDatabase [-SqlCredential \u003cPSCredential\u003e] -InputObject \u003cDatabase[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database that was processed, regardless of success or failure.\nProperties:\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 that was processed\r\n- Status: Either \"Dropped\" when the database was successfully removed, or the error message if removal failed\nThe command returns results for each database processed even if some fail. Failed databases will have the error message in the Status property instead of \"Dropped\".", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaDatabase -SqlInstance sql2016 -Database containeddb\nPrompts then removes the database containeddb on SQL Server sql2016\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaDatabase -SqlInstance sql2016 -Database containeddb, mydb\nPrompts then removes the databases containeddb and mydb on SQL Server sql2016\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRemove-DbaDatabase -SqlInstance sql2016 -Database containeddb -Confirm:$false\nDoes not prompt and swiftly removes containeddb on SQL Server sql2016\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance server\\instance | Remove-DbaDatabase\nRemoves all the user databases from server\\instance\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance server\\instance | Remove-DbaDatabase -Confirm:$false\nRemoves all the user databases from server\\instance without any confirmation", "Description": "Removes user databases by attempting three different drop methods in sequence until one succeeds. First tries the standard KillDatabase() method, then attempts to set the database to single-user mode with rollback immediate before dropping, and finally uses the SMO Drop() method. This approach handles databases that are stuck due to active connections, replication, mirroring, or other locks that prevent normal removal. System databases are automatically excluded from removal operations.", "Links": "https://dbatools.io/Remove-DbaDatabase", "Synopsis": "Removes user databases using multiple fallback methods to handle stuck or locked databases.", "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, "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 user database(s) to remove from the SQL Server instance. Accepts multiple database names and supports wildcards for pattern matching.\r\nUse this when you need to remove specific databases rather than all user databases. System databases (master, model, msdb, tempdb, resource) are automatically excluded and cannot be removed.", "Name", true, "false", "", "" ], [ "InputObject", "Accepts database objects from the pipeline, typically from Get-DbaDatabase or other dbatools database commands.\r\nUse this for pipeline operations when you want to filter databases first, then remove the filtered results. This provides more flexibility than specifying database names directly.", "", 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": [ "Database", "Delete" ], "CommandName": "Remove-DbaDatabaseSafely", "Name": "Remove-DbaDatabaseSafely", "Author": "Rob Sewell (@SQLDBAWithBeard), sqldbawithabeard.com", "Syntax": "Remove-DbaDatabaseSafely [-SqlInstance] \u003cDbaInstanceParameter\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-Destination] \u003cDbaInstanceParameter\u003e] [[-DestinationSqlCredential] \u003cPSCredential\u003e] [-NoDbccCheckDb] [-BackupFolder] \u003cString\u003e [[-CategoryName] \u003cString\u003e] [[-JobOwner] \u003cString\u003e] [-AllDatabases] [[-BackupCompression] \u003cString\u003e] [-ReuseSourceFolderStructure] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database that completes the removal workflow (backup, restore job creation, drop, verify restore, and cleanup).\nProperties:\r\n- SqlInstance: The source SQL Server instance name where the original database was located\r\n- DatabaseName: The name of the database that was removed\r\n- JobName: The name of the SQL Agent restore job that was created for backup verification testing\r\n- TestingInstance: The SQL Server instance where the restore testing job was created and executed\r\n- BackupFolder: The file path where the final backup of the database was stored before deletion\nNo output is returned if the operation encounters errors during validation, backup, or restore phases (unless -EnableException is used), or if the command is run in WhatIf mode.\nEach database processed generates one output object, containing information about the location of its verified backup and the testing job details for future reference or restore operations.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaDatabaseSafely -SqlInstance \u0027Fade2Black\u0027 -Database RideTheLightning -BackupFolder \u0027C:\\MSSQL\\Backup\\Rationalised - DO NOT DELETE\u0027\nPerforms a DBCC CHECKDB on database RideTheLightning on server Fade2Black. If there are no errors, the database is backup to the folder C:\\MSSQL\\Backup\\Rationalised - DO NOT DELETE. Then, an Agent \r\njob to restore the database from that backup is created. The database is then dropped, the Agent job to restore it run, a DBCC CHECKDB run against the restored database, and then it is dropped again.\nAny DBCC errors will be written to your documents folder\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$Database = \u0027DemoNCIndex\u0027,\u0027RemoveTestDatabase\u0027\nPS C:\\\u003e Remove-DbaDatabaseSafely -SqlInstance \u0027Fade2Black\u0027 -Database $Database -BackupFolder \u0027C:\\MSSQL\\Backup\\Rationalised - DO NOT DELETE\u0027\nPerforms a DBCC CHECKDB on two databases, \u0027DemoNCIndex\u0027 and \u0027RemoveTestDatabase\u0027 on server Fade2Black. Then, an Agent job to restore each database from those backups is created. The databases are \r\nthen dropped, the Agent jobs to restore them run, a DBCC CHECKDB run against the restored databases, and then they are dropped again.\nAny DBCC errors will be written to your documents folder\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRemove-DbaDatabaseSafely -SqlInstance \u0027Fade2Black\u0027 -Destination JusticeForAll -Database RideTheLightning -BackupFolder \u0027\\\\BACKUPSERVER\\BACKUPSHARE\\MSSQL\\Rationalised - DO NOT DELETE\u0027\nPerforms a DBCC CHECKDB on database RideTheLightning on server Fade2Black. If there are no errors, the database is backup to the folder \\\\BACKUPSERVER\\BACKUPSHARE\\MSSQL\\Rationalised - DO NOT DELETE . \r\nThen, an Agent job is created on server JusticeForAll to restore the database from that backup is created. The database is then dropped on Fade2Black, the Agent job to restore it on JusticeForAll is \r\nrun, a DBCC CHECKDB run against the restored database, and then it is dropped from JusticeForAll.\nAny DBCC errors will be written to your documents folder\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eRemove-DbaDatabaseSafely -SqlInstance IronMaiden -Database $Database -Destination TheWildHearts -BackupFolder Z:\\Backups -NoDbccCheckDb -JobOwner \u0027THEBEARD\\Rob\u0027\nFor the databases $Database on the server IronMaiden a DBCC CHECKDB will not be performed before backing up the databases to the folder Z:\\Backups. Then, an Agent job is created on server \r\nTheWildHearts with a Job Owner of THEBEARD\\Rob to restore each database from that backup using the instance\u0027s default file paths. The database(s) is(are) then dropped on IronMaiden, the Agent job(s) \r\nrun, a DBCC CHECKDB run on the restored database(s), and then the database(s) is(are) dropped.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eRemove-DbaDatabaseSafely -SqlInstance IronMaiden -Database $Database -Destination TheWildHearts -BackupFolder Z:\\Backups\nThe databases $Database on the server IronMaiden will be backed up the to the folder Z:\\Backups. Then, an Agent job is created on server TheWildHearts with a Job Owner of THEBEARD\\Rob to restore each \r\ndatabase from that backup using the instance\u0027s default file paths. The database(s) is(are) then dropped on IronMaiden, the Agent job(s) run, a DBCC CHECKDB run on the restored database(s), and then \r\nthe database(s) is(are) dropped.\nIf there is a DBCC Error, the function will continue to perform rest of the actions and will create an Agent job with \u0027DBCCERROR\u0027 in the name and a Backup file with \u0027DBCCError\u0027 in the name.", "Description": "Performs a comprehensive database removal workflow that validates database integrity, creates verified backups, and tests restore procedures before permanently removing databases. This function runs DBCC CHECKDB to verify database health, creates a checksummed backup to a specified location, generates a SQL Agent job for automated restore testing, drops the original database, executes the restore job to verify backup integrity, performs another DBCC check on the restored database, and finally removes the test database.\n\nThis process ensures that removed databases have reliable, tested backups that can be restored if needed later. The automated restore job remains available for future recovery operations, making this ideal for database decommissioning, environment cleanup, or compliance scenarios where you need proof that backups are valid before removing production data.\n\nWith huge thanks to Grant Fritchey and his verify your backups video. Take a look, it\u0027s only 3 minutes long. http://sqlps.io/backuprant", "Links": "https://dbatools.io/Remove-DbaDatabaseSafely", "Synopsis": "Removes databases after creating verified backups and testing restore procedures.", "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", "", "" ], [ "Database", "Specifies one or more databases to safely remove with validated backups. Accepts multiple database names as an array.\r\nUse this to target specific databases for removal, ensuring each gets a verified backup before deletion.", "Name", false, "false", "", "" ], [ "Destination", "Specifies the SQL Server instance where the SQL Agent restore job will be created and executed. Defaults to the same server as SqlInstance if not specified.\r\nUse this when you want to test database backups on a different server than where the original database exists, which is a best practice for backup validation.", "", false, "false", "$SqlInstance", "" ], [ "DestinationSqlCredential", "Credentials for connecting to the destination SQL Server instance when different from SqlCredential. Accepts PowerShell credentials (Get-Credential).\r\nUse this when the destination server requires different authentication than the source server, common in cross-domain or different security context scenarios.", "", false, "false", "", "" ], [ "NoDbccCheckDb", "Skips the initial DBCC CHECKDB integrity check before creating the backup, reducing processing time.\r\nUse this only when you\u0027re confident about database integrity or when time constraints outweigh the risk of backing up a corrupt database.\r\nThe function still runs DBCC on the restored test database, but corruption detection happens after backup creation.", "NoCheck", false, "false", "False", "" ], [ "BackupFolder", "Specifies the directory path where final database backups will be stored before deletion. Must be accessible by both source and destination server service accounts.\r\nUse a UNC path (like \\\\SERVER1\\BACKUPS\\) when source and destination servers are different, or a local path when using the same server for both operations.", "", true, "false", "", "" ], [ "CategoryName", "Sets the SQL Agent job category for the restore jobs that are created. Defaults to \u0027Rationalisation\u0027.\r\nUse a custom category name to organize these restoration jobs separately from other maintenance jobs in SQL Agent.", "", false, "false", "Rationalisation", "" ], [ "JobOwner", "Sets the owner account for the SQL Agent restore job that gets created. Defaults to the \u0027sa\u0027 login.\r\nSpecify a different owner when you need the job to run under specific security context or when \u0027sa\u0027 is disabled in your environment.", "", false, "false", "", "" ], [ "AllDatabases", "Removes all user databases from the source server, excluding system databases. Primarily used for server decommissioning scenarios.\r\nUse with caution and always specify a different Destination server to avoid removing databases from the same server that will test their backups.", "", false, "false", "False", "" ], [ "BackupCompression", "Controls backup compression behavior with values: Default, On, or Off. Default uses the server\u0027s backup compression configuration setting.\r\nUse \u0027On\u0027 to force compression for smaller backup files and reduced network traffic, or \u0027Off\u0027 when compression overhead outweighs benefits.", "", false, "false", "Default", "Default,On,Off" ], [ "ReuseSourceFolderStructure", "Maintains the original database file paths and folder structure during the test restore operation on the destination server.\r\nUse this when you need to preserve specific drive layouts or when the destination server has matching drive structure to the source.", "", false, "false", "False", "" ], [ "Force", "Continues the database removal process even when DBCC integrity checks detect corruption. Creates backups and jobs with \u0027DBCCERROR\u0027 naming to identify them.\r\nUse this only in emergency situations when you must remove a corrupt database and accept the risk of having potentially unusable backups.", "", 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": [ "Security", "Key" ], "CommandName": "Remove-DbaDbAsymmetricKey", "Name": "Remove-DbaDbAsymmetricKey", "Author": "Stuart Moore (@napalmgram), stuart-moore.com", "Syntax": "Remove-DbaDbAsymmetricKey [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Name] \u003cString[]\u003e] [[-Database] \u003cString[]\u003e] [[-InputObject] \u003cAsymmetricKey[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per asymmetric key successfully removed.\nProperties:\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name (e.g., MSSQLSERVER, SQLEXPRESS)\r\n- SqlInstance: The full SQL Server instance name (ComputerName\\InstanceName or ComputerName for default instance)\r\n- Database: The name of the database from which the asymmetric key was removed\r\n- Name: The name of the asymmetric key that was removed\r\n- Status: String indicating the removal result (typically \"Success\" for successful operations)\nNo output is returned if the operation is skipped (WhatIf) or fails (with EnableException disabled).", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaDbAsymmetricKey -SqlInstance Server1 -Database Enctest -Name AsCert1\nThe Asymmetric Key AsCert1 will be removed from the Enctest database on Instance Server1\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbAsymmetricKey -SqlInstance Server1 -Database Enctest | Remove-DbaDbAsymmetricKey\nWill remove all the asymmetric keys found in the Enctrst databae on the Server1 instance", "Description": "Removes asymmetric keys from SQL Server databases by executing DROP ASYMMETRIC KEY commands. Asymmetric keys are part of SQL Server\u0027s cryptographic hierarchy used for encryption, digital signatures, and protecting symmetric keys or certificates. This function helps DBAs clean up unused encryption objects during security audits, decommission old encryption schemes, or remove keys that are no longer needed for compliance requirements. Supports both direct parameter input and pipeline input from Get-DbaDbAsymmetricKey for bulk operations.", "Links": "https://dbatools.io/Remove-DbaDbAsymmetricKey", "Synopsis": "Removes asymmetric keys from 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", "", "" ], [ "Name", "Specifies the name of the asymmetric key to remove from the database.\r\nUse this when you know the exact key name to target specific encryption objects for deletion.", "", false, "false", "", "" ], [ "Database", "Specifies the database containing the asymmetric key to be removed. Defaults to \u0027master\u0027 if not specified.\r\nUse this to target specific databases when cleaning up encryption objects during security audits or decommissioning operations.", "", false, "false", "master", "" ], [ "InputObject", "Accepts AsymmetricKey objects from Get-DbaDbAsymmetricKey for pipeline operations.\r\nUse this when you need to remove multiple keys or when filtering keys based on specific criteria before deletion.", "", 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": [ "Delete", "Backup", "Restore", "Database" ], "CommandName": "Remove-DbaDbBackupRestoreHistory", "Name": "Remove-DbaDbBackupRestoreHistory", "Author": "IJeb Reitsma", "Syntax": "Remove-DbaDbBackupRestoreHistory [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-KeepDays] \u003cInt32\u003e] [[-Database] \u003cString[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "None\nThis command performs cleanup operations on the MSDB database backup and restore history tables but does not return any objects to the pipeline. It modifies data through SMO methods \r\n(DeleteBackupHistory for server-level cleanup and DropBackupHistory for database-level cleanup).", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaDbBackupRestoreHistory -SqlInstance sql2016\nPrompts for confirmation then deletes backup and restore history on SQL Server sql2016 older than 30 days (default period)\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaDbBackupRestoreHistory -SqlInstance sql2016 -KeepDays 100 -Confirm:$false\nRemove backup and restore history on SQL Server sql2016 older than 100 days. Does not prompt for confirmation.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRemove-DbaDbBackupRestoreHistory -SqlInstance sql2016 -Database db1\nPrompts for confirmation then deletes all backup and restore history for database db1 on SQL Server sql2016\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2016 | Remove-DbaDbBackupRestoreHistory -WhatIf\nRemove complete backup and restore history for all databases on SQL Server sql2016", "Description": "Removes backup and restore history records from MSDB database tables to prevent them from consuming excessive disk space and degrading performance. Over time, these history tables can grow substantially on busy SQL Server instances with frequent backup operations.\n\nWorks in two modes: server-level cleanup removes records older than a specified retention period (default 30 days), while database-level cleanup removes the complete backup/restore history for specific databases. This is particularly useful when decommissioning databases or cleaning up after major maintenance operations.\n\nThe backup and restore history tables reside in the MSDB database and include backupset, backupfile, restorehistory, and related system tables. Large history accumulations can impact backup operations, SSMS performance when viewing backup history, and overall MSDB database size.\n\nFor production environments, consider scheduling regular cleanup using the sp_delete_backuphistory agent job from Ola Hallengren\u0027s SQL Server Maintenance Solution (https://ola.hallengren.com) rather than manual cleanup operations.", "Links": "https://dbatools.io/Remove-DbaDbBackupRestoreHistory", "Synopsis": "Removes backup and restore history records from MSDB database to prevent excessive growth", "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.", "", 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", "", "" ], [ "KeepDays", "Specifies how many days of backup and restore history to retain when performing server-level cleanup. Records older than this period will be deleted from MSDB history tables.\r\nUse this for regular maintenance to prevent MSDB growth while preserving recent history for troubleshooting. Cannot be combined with Database parameter.", "", false, "false", "0", "" ], [ "Database", "Specifies specific databases to completely remove all backup and restore history records regardless of age. Accepts multiple database names and wildcards.\r\nUse this when decommissioning databases or performing targeted cleanup after major maintenance operations. Cannot be combined with KeepDays parameter.", "", false, "false", "", "" ], [ "InputObject", "Accepts database objects piped from Get-DbaDatabase to remove complete backup and restore history for those specific databases.\r\nUse this for pipeline operations when working with filtered database collections or when combining with other dbatools database 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", "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": "Remove-DbaDbCertificate", "Name": "Remove-DbaDbCertificate", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Remove-DbaDbCertificate [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-Certificate] \u003cString[]\u003e] [[-InputObject] \u003cCertificate[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per certificate successfully removed, 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)\r\n- Database: The name of the database where the certificate was removed\r\n- Certificate: The name of the certificate that was removed\r\n- Status: Removal status (Success when the certificate was successfully dropped)\nCertificates that fail to remove do not produce output; errors are handled via Stop-Function with -Continue behavior.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaDbCertificate -SqlInstance Server1\nThe certificate in the master database on server1 will be removed if it exists.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaDbCertificate -SqlInstance Server1 -Database db1 -Confirm:$false\nSuppresses all prompts to remove the certificate in the \u0027db1\u0027 database and drops the key.", "Description": "Removes database certificates from specified SQL Server databases using the DROP CERTIFICATE statement. This function is commonly used during certificate rotation, security cleanup, or when decommissioning encryption features like Transparent Data Encryption (TDE) or Always Encrypted. Certificates can be targeted individually by name or removed in bulk using pipeline input from Get-DbaDbCertificate.", "Links": "https://dbatools.io/Remove-DbaDbCertificate", "Synopsis": "Removes database certificates from SQL Server databases", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The SQL Server to create the certificates on.", "", 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 target databases containing certificates to remove. Accepts multiple database names.\r\nWhen omitted, the function will process certificates from all databases that contain the specified certificates.", "", false, "false", "", "" ], [ "Certificate", "Specifies the names of certificates to remove from the target databases. Supports multiple certificate names.\r\nUse this to target specific certificates rather than removing all certificates found by Get-DbaDbCertificate.", "", false, "false", "", "" ], [ "InputObject", "Accepts certificate objects from Get-DbaDbCertificate via pipeline input.\r\nThis allows for advanced filtering and bulk operations when combined with other dbatools certificate functions.", "", 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": [ "Check", "Constraint", "Database" ], "CommandName": "Remove-DbaDbCheckConstraint", "Name": "Remove-DbaDbCheckConstraint", "Author": "Mikey Bronowski (@MikeyBronowski), bronowski.it", "Syntax": "Remove-DbaDbCheckConstraint [-SqlInstance \u003cDbaInstanceParameter[]\u003e] [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-ExcludeSystemTable] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nRemove-DbaDbCheckConstraint [-SqlInstance \u003cDbaInstanceParameter[]\u003e] [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-ExcludeSystemTable] -InputObject \u003cCheck[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per check constraint processed, with details about the removal operation result.\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 database where the check constraint was located\r\n- Name: The name of the check constraint\r\n- Status: The result of the removal operation - either \"Dropped\" if successful, or an error message if the operation failed\r\n- IsRemoved: Boolean indicating whether the check constraint was successfully removed (true) or failed (false)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaDbCheckConstraint -SqlInstance localhost, sql2016 -Database db1, db2\nRemoves all check constraints from db1 and db2 on the local and sql2016 SQL Server instances.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$chkcs = Get-DbaDbCheckConstraint -SqlInstance localhost, sql2016 -Database db1, db2\nPS C:\\\u003e $chkcs | Remove-DbaDbCheckConstraint\nRemoves all check constraints from db1 and db2 on the local and sql2016 SQL Server instances.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRemove-DbaDbCheckConstraint -SqlInstance localhost, sql2016 -Database db1, db2 -ExcludeSystemTable\nRemoves all check constraints except those in system tables from db1 and db2 on the local and sql2016 SQL Server instances.", "Description": "Removes check constraints from database tables across one or more SQL Server instances. Check constraints enforce data integrity by validating that column values meet specific criteria before allowing INSERT or UPDATE operations.\n\nThis function is useful when modifying table schemas, removing outdated business rules, or preparing databases for data migration where existing constraints might block bulk operations. You can target specific databases or remove constraints across multiple instances simultaneously.\n\nSupports piping from Get-DbaDbCheckConstraint to remove only specific constraints that match your criteria, such as constraints containing particular patterns or on specific tables.", "Links": "https://dbatools.io/Remove-DbaDbCheckConstraint", "Synopsis": "Removes check constraints from SQL Server database tables", "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 target for check constraint removal. Accepts wildcards and arrays for multiple databases.\r\nUse this when you need to remove constraints from specific databases rather than all databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific databases from check constraint removal operations. Accepts wildcards and arrays for multiple databases.\r\nUse this to protect critical databases like master, msdb, or production databases when running against multiple instances.", "", false, "false", "", "" ], [ "ExcludeSystemTable", "Excludes check constraints on system tables from the removal operation, focusing only on user-created tables.\r\nUse this switch when you want to modify only business logic constraints while preserving SQL Server\u0027s built-in constraints.", "", false, "false", "False", "" ], [ "InputObject", "Accepts check constraint objects from Get-DbaDbCheckConstraint for targeted removal operations.\r\nUse this to remove only specific constraints that match your filtering criteria, such as constraints with certain patterns or on particular tables.", "", 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.\r\nThis is the default. Use -Confirm:$false to suppress these prompts.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Table", "Data" ], "CommandName": "Remove-DbaDbData", "Name": "Remove-DbaDbData", "Author": "Jess Pomfret (@jpomfret), jesspomfret.com", "Syntax": "Remove-DbaDbData [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-ExcludeDatabase] \u003cString[]\u003e] [[-InputObject] \u003cObject[]\u003e] [[-Path] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "None\nThis command performs data removal operations but does not return any output objects to the pipeline. It only performs the truncation operations and displays informational messages.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaDbData -SqlInstance localhost -Database dbname\nRemoves all data from the dbname database on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaDbData -SqlInstance mssql1 -ExcludeDatabase DBA -Confirm:$False\nRemoves all data from all databases on mssql1 except the DBA Database. Doesn\u0027t prompt for confirmation.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$svr = Connect-DbaInstance -SqlInstance mssql1\nPS C:\\\u003e $svr | Remove-DbaDbData -Database AdventureWorks2017\nRemoves all data from AdventureWorks2017 on the mssql1 SQL Server Instance, uses piped input from Connect-DbaInstance.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance mssql1 -Database AdventureWorks2017 | Remove-DbaDbData\nRemoves all data from AdventureWorks2017 on the mssql1 SQL Server Instance, uses piped input from Get-DbaDatabase.", "Description": "Removes all data from user tables by truncating each table in the specified databases. When foreign keys or views exist that would prevent truncation, the function automatically scripts them out, drops them temporarily, performs the truncation, then recreates the objects with their original definitions and permissions. This provides a fast way to clear databases for testing or development environments without having to rebuild schemas. The function excludes system databases and only processes user databases to prevent accidental damage to SQL Server internals.", "Links": "https://dbatools.io/Remove-DbaDbData", "Synopsis": "Truncates all user tables in specified databases to remove all data while preserving table structure.", "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 clear of data. Accepts wildcards for pattern matching.\r\nWhen omitted, the function processes all user databases on the instance. System databases are always excluded for safety.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific databases from data removal operations. Use this to protect important databases when clearing multiple databases.\r\nCommonly used with production or reference databases that should remain untouched during development environment resets.", "", false, "false", "", "" ], [ "InputObject", "Accepts piped database objects from Get-DbaDatabase or server connections from Connect-DbaInstance.\r\nUse this for pipeline operations when you need to filter databases with complex criteria before clearing data.", "", false, "true (ByValue)", "", "" ], [ "Path", "Sets the temporary directory for storing drop and create scripts during the data removal process.\r\nThe function creates temporary SQL scripts for foreign keys and views, then automatically removes them when complete. Defaults to the configured dbatools export path.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \u0027Path.DbatoolsExport\u0027)", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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": "Remove-DbaDbEncryptionKey", "Name": "Remove-DbaDbEncryptionKey", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Remove-DbaDbEncryptionKey [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-InputObject] \u003cDatabaseEncryptionKey[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per successfully removed encryption key 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)\r\n- Database: The name of the database from which the encryption key was removed\r\n- Status: The status of the operation (\"Success\")\nNo objects are returned if the operation fails or is skipped by WhatIf.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaDbEncryptionKey -SqlInstance sql01 -Database test\nRemoves the encryption key in the master database on sql01 if it exists.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaDbEncryptionKey -SqlInstance sql01 -Database db1 -Confirm:$false\nSuppresses all prompts then removes the encryption key in the \u0027db1\u0027 database on sql01.", "Description": "Removes database encryption keys (DEK) from specified databases by executing DROP DATABASE ENCRYPTION KEY. This is typically used when disabling Transparent Data Encryption (TDE) on a database or during encryption key rotation workflows. The database must be unencrypted before the key can be removed, so run ALTER DATABASE [database] SET ENCRYPTION OFF first if TDE is currently active.", "Links": "https://dbatools.io/Remove-DbaDbEncryptionKey", "Synopsis": "Removes database encryption keys from SQL Server databases to disable Transparent Data Encryption", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The SQL Server to create the encryption keys on.", "", 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) from which to remove the database encryption key (DEK).\r\nRequired when using SqlInstance parameter to target specific databases for encryption key removal.", "", false, "false", "", "" ], [ "InputObject", "Accepts database encryption key objects from Get-DbaDbEncryptionKey via pipeline.\r\nUse this when you need to remove keys from a filtered set of databases or when chaining 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", "" ], [ "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", "Data", "File", "FileGroup" ], "CommandName": "Remove-DbaDbFileGroup", "Name": "Remove-DbaDbFileGroup", "Author": "Adam Lancaster, github.com/lancasteradam", "Syntax": "Remove-DbaDbFileGroup [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-FileGroup] \u003cString[]\u003e] [[-InputObject] \u003cObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "None\nThis command removes filegroups and does not return output objects on success. All information about the operation is conveyed through the ShouldProcess mechanism (WhatIf/Confirm prompts) and error \r\nmessages if failures occur.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaDbFileGroup -SqlInstance sqldev1 -Database TestDb -FileGroup HRFG1\nRemoves the HRFG1 filegroup on the TestDb database on the sqldev1 instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sqldev1 -Database TestDb | Remove-DbaDbFileGroup -FileGroup HRFG1\nPasses in the TestDB database from the sqldev1 instance and removes the HRFG1 filegroup.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbFileGroup -SqlInstance sqldev1 -Database TestDb -FileGroup HRFG1 | Remove-DbaDbFileGroup\nPasses in the HRFG1 filegroup from the TestDB database on the sqldev1 instance and removes the filegroup.", "Description": "Removes one or more filegroups from SQL Server databases after validating they contain no data files. This command is useful for cleaning up unused filegroups after moving data to different filegroups or during database reorganization projects. The function performs safety checks to ensure filegroups are empty before removal and provides detailed error messages if removal fails due to dependencies or constraints.", "Links": "https://dbatools.io/Remove-DbaDbFileGroup", "Synopsis": "Removes empty filegroups 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 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 target for filegroup removal. Required when using SqlInstance parameter.\r\nUse this to limit the operation to specific databases instead of all databases on the instance.", "", false, "false", "", "" ], [ "FileGroup", "Specifies the name(s) of the filegroup(s) to remove from the target databases. Required when specifying databases directly.\r\nOnly empty filegroups (containing no data files) can be removed. Common scenarios include removing filegroups after data migration or database cleanup projects.", "", false, "false", "", "" ], [ "InputObject", "Accepts database or filegroup objects from Get-DbaDatabase or Get-DbaDbFileGroup for pipeline operations.\r\nUse this when you need to remove filegroups from a filtered set of databases or when working with specific filegroup objects.", "", 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": "LogShipping", "CommandName": "Remove-DbaDbLogShipping", "Name": "Remove-DbaDbLogShipping", "Author": "Sander Stad (@sqlstad), sqlstad.nl", "Syntax": "Remove-DbaDbLogShipping [-PrimarySqlInstance] \u003cDbaInstanceParameter\u003e [[-SecondarySqlInstance] \u003cDbaInstanceParameter\u003e] [[-PrimarySqlCredential] \u003cPSCredential\u003e] [[-SecondarySqlCredential] \u003cPSCredential\u003e] [-Database] \u003cObject[]\u003e [-RemoveSecondaryDatabase] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "None\nThis command does not produce any output. It performs configuration changes on the SQL Server instances (removing log shipping setup from msdb and optionally dropping the secondary database) but does \r\nnot return any objects to the pipeline.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaDbLogShipping -PrimarySqlInstance sql1 -SecondarySqlInstance sql2 -Database DB1\nRemove the log shipping for database DB1\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaDbLogShipping -PrimarySqlInstance sql1 -Database DB1\nRemove the log shipping for database DB1 and let the command figure out the secondary instance\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRemove-DbaDbLogShipping -PrimarySqlInstance localhost -SecondarySqlInstance sql2 -Database DB1, DB2\nRemove the log shipping for multiple database\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eRemove-DbaDbLogShipping -PrimarySqlInstance localhost -SecondarySqlInstance localhost -Database DB2 -RemoveSecondaryDatabase\nRemove the log shipping for database DB2 and remove the database from the secondary instance", "Description": "Completely removes log shipping setup from both primary and secondary instances by cleaning up all associated SQL Agent jobs, monitor configurations, and database relationships stored in msdb. This function calls the proper SQL Server system stored procedures (sp_delete_log_shipping_primary_secondary, sp_delete_log_shipping_primary_database, and sp_delete_log_shipping_secondary_database) to ensure clean removal without orphaned objects.\n\nUse this when migrating to different disaster recovery solutions, cleaning up failed log shipping setups, or decommissioning secondary servers. The function automatically discovers secondary server information from the log shipping configuration if not specified.\n\nBy default, the secondary database remains intact and accessible after log shipping removal. Use -RemoveSecondaryDatabase to completely drop the secondary database as part of the cleanup process.", "Links": "https://dbatools.io/Remove-DbaDbLogShipping", "Synopsis": "Dismantles SQL Server log shipping configurations and removes associated jobs and monitoring", "Availability": "Windows, Linux, macOS", "Params": [ [ "PrimarySqlInstance", "The SQL Server instance hosting the primary database(s) in the log shipping configuration. This server contains the source database that is being shipped to secondary instances.\r\nYou must have sysadmin access to execute the log shipping removal stored procedures. Requires SQL Server 2000 or later.", "", true, "false", "", "" ], [ "SecondarySqlInstance", "The SQL Server instance hosting the secondary database(s) in the log shipping configuration. If not specified, the function automatically discovers this from the log shipping metadata in msdb.\r\nRequired when removing log shipping from multiple secondary instances or when automatic discovery fails. You must have sysadmin access to clean up secondary database configurations.", "", false, "false", "", "" ], [ "PrimarySqlCredential", "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", "", "" ], [ "SecondarySqlCredential", "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", "The primary database name(s) to remove from log shipping configuration. Accepts multiple databases via pipeline or array input.\r\nMust specify the database name as it exists on the primary instance, not the secondary instance name which may be different.", "", true, "true (ByValue)", "", "" ], [ "RemoveSecondaryDatabase", "Completely drops the secondary database from the secondary instance after removing the log shipping configuration. By default, the secondary database remains intact and accessible.\r\nUse this when decommissioning the secondary server or when you need to start fresh with a new log shipping setup.", "", 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": [ "DatabaseMail", "DbMail", "Mail" ], "CommandName": "Remove-DbaDbMailAccount", "Name": "Remove-DbaDbMailAccount", "Author": "Mikey Bronowski (@MikeyBronowski), bronowski.it", "Syntax": "Remove-DbaDbMailAccount [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Account \u003cString[]\u003e] [-ExcludeAccount \u003cString[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nRemove-DbaDbMailAccount -InputObject \u003cMailAccount[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per Database Mail account removed. Each object contains the following properties:\r\n- ComputerName: The computer name of the SQL Server instance where the account was removed\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The fully qualified SQL Server instance name (ComputerName\\InstanceName)\r\n- Name: The Database Mail account name that was removed\r\n- Status: The result status (\"Dropped\" for successful removal, or error message if removal failed)\r\n- IsRemoved: Boolean indicating whether the account was successfully removed (true) or failed (false)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaDbMailAccount -SqlInstance localhost, localhost\\namedinstance\nRemoves all database mail accounts on the localhost, localhost\\namedinstance instances.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaDbMailAccount -SqlInstance localhost -Account MyDatabaseMailAccount\nRemoves MyDatabaseMailAccount database mail account on the localhost.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbMailAccount -SqlInstance SRV1 | Out-GridView -Title \u0027Select database mail account(s) to drop\u0027 -OutputMode Multiple | Remove-DbaDbMailAccount\nUsing a pipeline this command gets all database mail accounts on SRV1, lets the user select those to remove and then removes the selected database mail accounts.", "Description": "Permanently deletes Database Mail accounts from the specified SQL Server instances, removing them from the MSDB database configuration.\nThis command is useful when decommissioning obsolete email accounts, cleaning up after application retirement, or consolidating accounts during email system migrations.\nWhen used without pipeline input, it automatically retrieves accounts using Get-DbaDbMailAccount with the provided parameters before removal.\nReturns detailed status information for each removal operation, including success/failure status and any error messages encountered.", "Links": "https://dbatools.io/Remove-DbaDbMailAccount", "Synopsis": "Removes Database Mail accounts from SQL Server instances", "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).\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", "", "" ], [ "Account", "Specifies one or more Database Mail account names to remove from the SQL Server instance.\r\nUse this when you need to remove specific accounts rather than all accounts on the server.\r\nAccepts multiple account names as a string array for bulk removal operations.", "", false, "false", "", "" ], [ "ExcludeAccount", "Specifies Database Mail account names to exclude from removal when processing all accounts on the instance.\r\nUse this when you want to remove most accounts but keep certain ones active for ongoing operations.\r\nOnly applies when the Account parameter is not specified.", "", false, "false", "", "" ], [ "InputObject", "Accepts Database Mail account objects from the pipeline, typically from Get-DbaDbMailAccount.\r\nUse this approach when you need to filter or review accounts before removal using PowerShell pipeline operations.\r\nProvides more flexibility than specifying account names directly.", "", 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.\r\nThis is the default. Use -Confirm:$false to suppress these prompts.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "DatabaseMail", "DBMail", "Mail" ], "CommandName": "Remove-DbaDbMailProfile", "Name": "Remove-DbaDbMailProfile", "Author": "Mikey Bronowski (@MikeyBronowski), bronowski.it", "Syntax": "Remove-DbaDbMailProfile [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Profile \u003cString[]\u003e] [-ExcludeProfile \u003cString[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nRemove-DbaDbMailProfile -InputObject \u003cMailProfile[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per Database Mail profile processed, regardless of success or failure.\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 in the format ComputerName\\InstanceName\r\n- Name: The name of the Database Mail profile that was removed or attempted to be removed\r\n- Status: A string indicating the operation result (\"Dropped\" on success, or error message on failure)\r\n- IsRemoved: A boolean value indicating whether the profile was successfully removed ($true for success, $false for failure)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaDbMailProfile -SqlInstance localhost, localhost\\namedinstance\nRemoves all database mail profiles on the localhost, localhost\\namedinstance instances.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaDbMailProfile -SqlInstance localhost -Profile MyDatabaseMailProfile\nRemoves MyDatabaseMailProfile database mail profile on the localhost.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbMailProfile -SqlInstance SRV1 | Out-GridView -Title \u0027Select database mail profile(s) to drop\u0027 -OutputMode Multiple | Remove-DbaDbMailProfile\nUsing a pipeline this command gets all database mail profiles on SRV1, lets the user select those to remove and then removes the selected database mail profiles.", "Description": "Deletes specified Database Mail profiles from the msdb database, permanently removing their configuration and preventing them from sending emails.\nThis is commonly used during security hardening to remove unused profiles or when cleaning up misconfigured mail setups.\nAccepts profiles via pipeline from Get-DbaDbMailProfile or directly through parameters, making it easy to selectively remove profiles based on specific criteria.\nReturns detailed results showing which profiles were successfully removed and any that failed during deletion.", "Links": "https://dbatools.io/Remove-DbaDbMailProfile", "Synopsis": "Removes Database Mail profiles from SQL Server instances.", "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", "", "" ], [ "Profile", "Specifies one or more Database Mail profile names to remove from the instance. Supports wildcards for pattern matching.\r\nUse this when you need to remove specific profiles instead of all profiles on the instance. If unspecified, all profiles will be removed.", "", false, "false", "", "" ], [ "ExcludeProfile", "Specifies one or more Database Mail profile names to exclude from removal. Supports wildcards for pattern matching.\r\nUse this when removing all profiles except certain ones you want to keep active for ongoing email operations.", "", false, "false", "", "" ], [ "InputObject", "Accepts Database Mail profile objects from Get-DbaDbMailProfile via pipeline.\r\nThis allows for advanced filtering and selection of profiles before removal, such as selecting profiles based on account configuration or last usage date.", "", 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.\r\nThis is the default. Use -Confirm:$false to suppress these prompts.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Certificate", "Security" ], "CommandName": "Remove-DbaDbMasterKey", "Name": "Remove-DbaDbMasterKey", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Remove-DbaDbMasterKey [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-ExcludeDatabase] \u003cString[]\u003e] [-All] [[-InputObject] \u003cMasterKey[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per master key removed from the database.\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 in the format ComputerName\\InstanceName\r\n- Database: The name of the database from which the master key was removed\r\n- Status: A string indicating the operation result (\"Master key removed\" on success, or error message on failure)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaDbMasterKey -SqlInstance sql2017, sql2016 -Database pubs\nThe master key in the pubs database on sql2017 and sql2016 will be removed if it exists.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaDbMasterKey -SqlInstance sql2017 -Database db1 -Confirm:$false\nSuppresses all prompts to remove the master key in the \u0027db1\u0027 database and drops the key.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbMasterKey -SqlInstance sql2017 -Database db1 | Remove-DbaDbMasterKey -Confirm:$false\nSuppresses all prompts to remove the master key in the \u0027db1\u0027 database and drops the key.", "Description": "Removes database master keys from specified SQL Server databases by executing DROP MASTER KEY. Database master keys are used to encrypt other database-level encryption keys, including those for Transparent Data Encryption (TDE), Always Encrypted, and certificate private keys. This function is typically used when decommissioning database encryption, migrating to different encryption strategies, or cleaning up unused encryption infrastructure during database maintenance or compliance changes.", "Links": "https://dbatools.io/Remove-DbaDbMasterKey", "Synopsis": "Removes database master keys from 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 remove master keys from. Accepts multiple database names.\r\nUse this when you need to remove encryption from specific databases during TDE decommissioning or security policy changes.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies databases to skip when using the -All parameter to remove master keys from all databases.\r\nUse this to protect critical databases that must retain their encryption while cleaning up master keys from other databases on the instance.", "", false, "false", "", "" ], [ "All", "Removes master keys from all user databases on the SQL Server instance.\r\nUse this when decommissioning encryption across an entire instance or during major security architecture changes.", "", false, "false", "False", "" ], [ "InputObject", "Accepts master key objects from Get-DbaDbMasterKey through the pipeline.\r\nUse this approach when you need to filter or inspect master keys before removing them, providing more control over the removal process.", "", 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": "Remove-DbaDbMirror", "Name": "Remove-DbaDbMirror", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Remove-DbaDbMirror [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database where the mirroring partnership was removed.\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 where mirroring was removed\r\n- Status: Status of the operation (always \"Removed\" on success)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaDbMirror -SqlInstance localhost -Database TestDB\nStops the database mirroring session for the TestDB on the localhost instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaDbMirror -SqlInstance localhost -Database TestDB1, TestDB2\nStops the database mirroring session for the TestDB1 and TestDB2 databases on the localhost instance.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance localhost -Database TestDB1, TestDB2 | Remove-DbaDbMirror\nStops the database mirroring session for the TestDB1 and TestDB2 databases on the localhost instance.", "Description": "Terminates database mirroring sessions by breaking the partnership between principal and mirror databases. This command stops the mirroring relationship completely, which is useful when decommissioning mirrors, performing maintenance that requires breaking the partnership, or during disaster recovery scenarios where you need to bring a database online independently.\n\nImportant: This function only breaks the mirroring partnership - it does not automatically recover databases that are left in a \"Restoring\" state. You\u0027ll need to manually restore those databases with RECOVERY to make them accessible for normal operations.", "Links": "https://dbatools.io/Remove-DbaDbMirror", "Synopsis": "Breaks database mirroring partnerships and stops mirroring sessions", "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 names of databases whose mirroring partnerships should be terminated. Accepts multiple database names.\r\nRequired when using SqlInstance parameter. Use this to target specific mirrored databases rather than processing all databases on the instance.", "", false, "false", "", "" ], [ "InputObject", "Accepts database objects from the pipeline, typically from Get-DbaDatabase.\r\nUse this when you want to filter databases using Get-DbaDatabase\u0027s capabilities before breaking mirroring partnerships.", "", 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": "Remove-DbaDbMirrorMonitor", "Name": "Remove-DbaDbMirrorMonitor", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Remove-DbaDbMirrorMonitor [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance where the mirror monitoring was removed.\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 (always \"Removed\" on success)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaDbMirrorMonitor -SqlInstance sql2008, sql2012\nStops and deletes the mirroring monitor job for all the databases on sql2008 and sql2012.", "Description": "Stops and deletes the mirroring monitor job for all the databases on the server instance.\n\nBasically executes sp_dbmmonitordropmonitoring.", "Links": "https://dbatools.io/Remove-DbaDbMirrorMonitor", "Synopsis": "Stops and deletes the mirroring monitor job for all the databases 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": [ "User", "Orphan", "Login" ], "CommandName": "Remove-DbaDbOrphanUser", "Name": "Remove-DbaDbOrphanUser", "Author": "Claudio Silva (@ClaudioESSilva) | Simone Bizzotto (@niphlod)", "Syntax": "Remove-DbaDbOrphanUser [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-User] \u003cObject[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object for each schema operation (ownership change or drop) that occurs during orphaned user removal. No output is generated if:\r\n- An orphaned user owns no schemas\r\n- A user is skipped due to schema complexity without the -Force parameter\r\n- A matching login exists and -Force is not specified\nWhen schema operations occur, returns objects with the following properties:\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- DatabaseName: The database containing the schema being modified\r\n- SchemaName: The name of the schema being modified\r\n- Action: The operation performed - either \"DROP\" or \"ALTER OWNER\"\r\n- SchemaOwnerBefore: The original owner of the schema before the operation\r\n- SchemaOwnerAfter: The new owner of the schema after the operation (either \"dbo\" for ALTER OWNER or \"N/A\" for DROP)\nNote: User removal is performed silently without output objects. Output objects track only schema ownership changes and drops, not the user removal itself.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaDbOrphanUser -SqlInstance sql2005\nFinds and drops all orphan users without matching Logins in all databases present on server \u0027sql2005\u0027.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaDbOrphanUser -SqlInstance sqlserver2014a -SqlCredential $cred\nFinds and drops all orphan users without matching Logins in all databases present on server \u0027sqlserver2014a\u0027. SQL Server authentication will be used in connecting to the server.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRemove-DbaDbOrphanUser -SqlInstance sqlserver2014a -Database db1, db2 -Force\nFinds and drops orphan users even if they have a matching Login on both db1 and db2 databases.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eRemove-DbaDbOrphanUser -SqlInstance sqlserver2014a -ExcludeDatabase db1, db2 -Force\nFinds and drops orphan users even if they have a matching Login from all databases except db1 and db2.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eRemove-DbaDbOrphanUser -SqlInstance sqlserver2014a -User OrphanUser\nRemoves user OrphanUser from all databases only if there is no matching login.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eRemove-DbaDbOrphanUser -SqlInstance sqlserver2014a -User OrphanUser -Force\nRemoves user OrphanUser from all databases even if they have a matching Login. Any schema that the user owns will change ownership to dbo.", "Description": "Removes orphaned database users from one or more databases, handling schema ownership transfers automatically to prevent dependency issues.\n\nOrphaned users occur when a database user exists but its corresponding login in the master database has been deleted or doesn\u0027t exist on the current server. This commonly happens after login deletions, database migrations, or restores to servers where the original logins don\u0027t exist.\n\nThe function intelligently handles schema ownership:\n- Drops empty schemas that have the same name as the orphaned user\n- Transfers ownership of other schemas to \u0027dbo\u0027 to maintain database integrity\n- Requires -Force parameter when schemas contain objects, ensuring you make conscious decisions about ownership changes\n\nWhen a login with the same name exists on the server (suggesting the user could be repaired with Repair-DbaDbOrphanUser instead), removal is blocked unless -Force is specified. This safety check prevents accidental deletions when remediation might be more appropriate than removal.\n\nContained databases are automatically skipped since they manage authentication differently and cannot have orphaned users in the traditional sense.", "Links": "https://dbatools.io/Remove-DbaDbOrphanUser", "Synopsis": "Removes orphaned database users that no longer have corresponding SQL Server logins", "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 single database names, comma-separated lists, or arrays.\r\nWhen omitted, all accessible, non-read-only databases on the instance are processed. Contained databases are automatically skipped since they cannot have orphaned users.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies databases to skip during orphaned user removal. Useful when you want to process most databases but avoid specific ones.\r\nCommonly used to exclude system databases, databases undergoing maintenance, or databases where user cleanup should be handled separately.", "", false, "false", "", "" ], [ "User", "Specifies specific orphaned users to target for removal instead of processing all orphaned users found.\r\nUse this when you need to remove only certain orphaned users rather than all orphans in the database. The function will verify these users are actually orphaned before removal.", "", false, "true (ByValue)", "", "" ], [ "Force", "Bypasses safety checks that normally prevent orphaned user removal in potentially problematic scenarios.\r\nRequired when the user owns schemas containing objects (ownership transfers to \u0027dbo\u0027) or when a matching login exists on the server (suggesting repair might be more appropriate than removal).\r\nUse with caution as this can change schema ownership and remove users that could potentially be repaired instead.", "", 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": [ "PartitionFunction", "Database" ], "CommandName": "Remove-DbaDbPartitionFunction", "Name": "Remove-DbaDbPartitionFunction", "Author": "Mikey Bronowski (@MikeyBronowski), bronowski.it", "Syntax": "Remove-DbaDbPartitionFunction [-SqlInstance \u003cDbaInstanceParameter[]\u003e] [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cString[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nRemove-DbaDbPartitionFunction [-SqlInstance \u003cDbaInstanceParameter[]\u003e] [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cString[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] -InputObject \u003cPartitionFunction[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per partition function removal attempt. The object contains information about the operation outcome regardless of success or failure.\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- Database: The database containing the partition function\r\n- PartitionFunctionName: The name of the partition function that was removed\r\n- Status: The outcome of the drop operation - either \"Dropped\" on success or the error message on failure\r\n- IsRemoved: Boolean indicating whether the partition function was successfully removed ($true) or not ($false)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaDbPartitionFunction -SqlInstance localhost, sql2016 -Database db1, db2\nRemoves partition functions from db1 and db2 on the local and sql2016 SQL Server instances.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbPartitionFunction -SqlInstance SRV1 | Out-GridView -Title \u0027Select partition function(s) to drop\u0027 -OutputMode Multiple | Remove-DbaDbPartitionFunction\nUsing a pipeline this command gets all partition functions on SRV1, lets the user select those to remove and then removes the selected partition functions.", "Description": "Removes partition functions from specified databases across one or more SQL Server instances. Partition functions define the value ranges used to split table data across multiple filegroups, and removing unused functions helps maintain a clean database schema. This command is commonly used during partition cleanup operations, schema migrations, or when decommissioning partitioned tables that no longer require their associated partition functions.", "Links": "https://dbatools.io/Remove-DbaDbPartitionFunction", "Synopsis": "Drops partition functions from SQL Server databases to clean up unused partitioning schemes.", "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(s) from which to remove partition functions. Accepts wildcard patterns for matching multiple databases.\r\nUse this to target specific databases when you need to clean up partitioning objects from particular databases rather than all databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes the specified database(s) from partition function removal operations. Auto-populated with available databases from the target server.\r\nUse this when you want to remove partition functions from most databases but need to preserve them in specific databases like production or critical systems.", "", false, "false", "", "" ], [ "InputObject", "Accepts partition function objects from Get-DbaDbPartitionFunction for targeted removal operations.\r\nUse this with pipeline operations when you need to selectively remove specific partition functions based on criteria like name patterns, usage, or dependencies.", "", 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.\r\nThis is the default. Use -Confirm:$false to suppress these prompts.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "PartitionScheme", "Partition", "Database" ], "CommandName": "Remove-DbaDbPartitionScheme", "Name": "Remove-DbaDbPartitionScheme", "Author": "Mikey Bronowski (@MikeyBronowski), bronowski.it", "Syntax": "Remove-DbaDbPartitionScheme [-SqlInstance \u003cDbaInstanceParameter[]\u003e] [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cString[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nRemove-DbaDbPartitionScheme [-SqlInstance \u003cDbaInstanceParameter[]\u003e] [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cString[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] -InputObject \u003cPartitionScheme[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per partition scheme removal operation with the following properties:\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)\r\n- Database: The name of the database containing the partition scheme\r\n- PartitionSchemeName: The name of the partition scheme that was processed\r\n- Status: The result of the removal operation (\"Dropped\" on success, or error message on failure)\r\n- IsRemoved: Boolean indicating whether the partition scheme was successfully dropped (true) or failed (false)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaDbPartitionScheme -SqlInstance localhost, sql2016 -Database db1, db2\nRemoves partition schemes from db1 and db2 on the local and sql2016 SQL Server instances.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbPartitionScheme -SqlInstance SRV1 | Out-GridView -Title \u0027Select partition scheme(s) to drop\u0027 -OutputMode Multiple | Remove-DbaDbPartitionScheme\nUsing a pipeline this command gets all partition schemes on SRV1, lets the user select those to remove and then removes the selected partition schemes.", "Description": "Removes partition schemes from specified databases across one or more SQL Server instances. Partition schemes define how partitioned tables and indexes map to filegroups, and this function helps clean up unused schemes during database reorganization or migration projects.\n\nThe function integrates seamlessly with Get-DbaDbPartitionScheme through pipeline support, allowing you to first identify partition schemes and then selectively remove them. This is particularly useful when consolidating databases or simplifying partition strategies.\n\nEach removal operation includes confirmation prompts by default to prevent accidental deletion of partition schemes that may still be referenced by tables or indexes.", "Links": "https://dbatools.io/Remove-DbaDbPartitionScheme", "Synopsis": "Removes database partition schemes from 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 scan for partition schemes to remove. Accepts multiple database names.\r\nUse this when you need to remove partition schemes from specific databases rather than all databases on the instance, such as during database decommissioning or partition strategy simplification.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies databases to skip when scanning for partition schemes to remove. Accepts multiple database names.\r\nUse this to exclude system databases or specific databases you want to preserve during bulk partition scheme cleanup operations.", "", false, "false", "", "" ], [ "InputObject", "Accepts partition scheme objects piped from Get-DbaDbPartitionScheme for targeted removal operations.\r\nUse this for selective removal workflows where you first identify specific partition schemes and then remove only those schemes.", "", 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.\r\nThis is the default. Use -Confirm:$false to suppress these prompts.", "cf", false, "false", "", "" ] ] }, { "Tags": "Role", "CommandName": "Remove-DbaDbRole", "Name": "Remove-DbaDbRole", "Author": "Ben Miller (@DBAduck), the dbatools team + Claude", "Syntax": "Remove-DbaDbRole [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-ExcludeDatabase] \u003cString[]\u003e] [[-Role] \u003cString[]\u003e] [[-ExcludeRole] \u003cString[]\u003e] [-IncludeSystemDbs] [[-InputObject] \u003cObject[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "None\nThis function performs role removal operations but does not return any output objects. Success or failure information is provided through verbose messages and warning messages during execution.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaDbRole -SqlInstance localhost -Database dbname -Role \"customrole1\", \"customrole2\"\nRemoves roles customrole1 and customrole2 from the database dbname on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaDbRole -SqlInstance localhost, sql2016 -Database db1, db2 -Role role1, role2, role3\nRemoves role1,role2,role3 from db1 and db2 on the local and sql2016 SQL Server instances\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$servers = Get-Content C:\\servers.txt\nPS C:\\\u003e $servers | Remove-DbaDbRole -Database db1, db2 -Role role1\nRemoves role1 from db1 and db2 on the servers in C:\\servers.txt\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$roles = Get-DbaDbRole -SqlInstance localhost, sql2016 -Database db1, db2 -Role role1, role2, role3\nPS C:\\\u003e $roles | Remove-DbaDbRole\nRemoves role1,role2,role3 from db1 and db2 on the local and sql2016 SQL Server instances", "Description": "Removes user-defined database roles from SQL Server databases while protecting against accidental deletion of system roles and intelligently handling schema ownership. This function automatically excludes fixed database roles (like db_owner, db_datareader) and the public role, ensuring only custom roles created for specific security requirements can be removed.\n\nWhen a role owns schemas, the function intelligently manages the cleanup: schemas with the same name as the role are dropped (if empty), while other owned schemas have their ownership transferred to \u0027dbo\u0027. If schemas contain objects, use -Force to allow ownership transfer and proceed with role removal.\n\nYou can target specific roles across multiple databases and instances, making it ideal for standardizing security configurations or bulk cleanup operations. By default, system databases are excluded unless explicitly included with the IncludeSystemDbs parameter.", "Links": "https://dbatools.io/Remove-DbaDbRole", "Synopsis": "Removes custom database roles 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 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 remove roles from. Accepts multiple database names and supports wildcards for pattern matching.\r\nWhen omitted, the function processes all user databases on the instance. Use this when you need to clean up roles from specific databases only.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific databases from role removal operations. Accepts multiple database names and supports wildcards.\r\nUse this when processing all databases except certain ones, such as excluding production databases during cleanup operations.", "", false, "false", "", "" ], [ "Role", "Specifies which custom database roles to remove. Accepts multiple role names and supports wildcards for pattern matching.\r\nWhen omitted, all custom roles in the target databases will be removed. Fixed database roles (db_owner, db_datareader, etc.) and the public role are automatically protected from deletion.", "", false, "false", "", "" ], [ "ExcludeRole", "Excludes specific roles from removal operations. Accepts multiple role names and supports wildcards.\r\nUse this when you want to remove most custom roles but preserve certain ones, such as keeping application-specific roles while cleaning up deprecated security configurations.", "", false, "false", "", "" ], [ "IncludeSystemDbs", "Allows role removal operations to target system databases (master, model, msdb, tempdb).\r\nBy default, system databases are excluded to prevent accidental removal of roles that may be required for SQL Server operations. Only use this when you specifically need to clean up custom roles from \r\nsystem databases.", "", false, "false", "False", "" ], [ "InputObject", "Accepts piped objects from Get-DbaDbRole, Get-DbaDatabase, or SQL Server instances for processing.\r\nUse this for pipeline operations where you first retrieve specific roles or databases, then remove roles from them. This allows for more complex filtering and processing scenarios.", "", false, "true (ByValue)", "", "" ], [ "Force", "Forces schema ownership transfer to \u0027dbo\u0027 when the role owns schemas containing database objects. Without this, role removal fails if owned schemas contain objects.\r\nUse this during role cleanup when you need to ensure complete removal regardless of schema dependencies.", "", 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": [ "Role", "User" ], "CommandName": "Remove-DbaDbRoleMember", "Name": "Remove-DbaDbRoleMember", "Author": "Ben Miller (@DBAduck)", "Syntax": "Remove-DbaDbRoleMember [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-Role] \u003cString[]\u003e] [-User] \u003cString[]\u003e [[-InputObject] \u003cObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "None\nThis command does not return any output objects. It removes specified users from database roles and returns no information about the operation.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaDbRoleMember -SqlInstance localhost -Database mydb -Role db_owner -User user1\nRemoves user1 from the role db_owner in the database mydb on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaDbRoleMember -SqlInstance localhost, sql2016 -Role SqlAgentOperatorRole -User user1 -Database msdb\nRemoves user1 in servers localhost and sql2016 in the msdb database from the SqlAgentOperatorRole\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$servers = Get-Content C:\\servers.txt\nPS C:\\\u003e $servers | Remove-DbaDbRoleMember -Role SqlAgentOperatorRole -User user1 -Database msdb\nRemoves user1 from the SqlAgentOperatorRole in the msdb database in every server in C:\\servers.txt\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$db = Get-DbaDataabse -SqlInstance localhost -Database DEMODB\nPS C:\\\u003e $db | Remove-DbaDbRoleMember -Role \"db_datareader\",\"db_datawriter\" -User user1\nRemoves user1 in the database DEMODB on the server localhost from the roles db_datareader and db_datawriter\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$roles = Get-DbaDbRole -SqlInstance localhost -Role \"db_datareader\",\"db_datawriter\"\nPS C:\\\u003e $roles | Remove-DbaDbRoleMember -User user1", "Description": "Removes database users from specified database roles, supporting both built-in roles (like db_datareader, db_datawriter, db_owner) and custom database roles. This function streamlines user access management when you need to revoke permissions during employee transitions, security reviews, or role-based access cleanup.\n\nHandles user removal from multiple roles simultaneously and works across multiple databases and instances. Particularly useful for bulk permission changes, compliance requirements, or when migrating users between different security models. The function validates that users are actually members of the specified roles before attempting removal, preventing unnecessary errors.", "Links": "https://dbatools.io/Remove-DbaDbRoleMember", "Synopsis": "Removes database users from 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 member removal. Accepts wildcards for pattern matching.\r\nWhen omitted, the function processes all databases on the instance. Use this to target specific databases during security reviews or when cleaning up permissions in development environments.", "", false, "false", "", "" ], [ "Role", "Specifies the database roles to remove users from, such as db_datareader, db_datawriter, db_owner, or custom roles.\r\nAccepts multiple roles to remove users from several roles simultaneously. Required unless you\u0027re piping in DatabaseRole objects from Get-DbaDbRole.", "", false, "false", "", "" ], [ "User", "Specifies the database users to remove from the specified roles. Accepts multiple usernames for bulk operations.\r\nThe function validates that users are actually members of the roles before attempting removal, preventing errors when users aren\u0027t currently assigned to the roles.", "", true, "false", "", "" ], [ "InputObject", "Accepts piped input from Get-DbaDatabase, Get-DbaDbRole, or SQL Server instance objects.\r\nUse this to chain commands together, such as piping specific databases or roles to process only those objects instead of specifying them via parameters.", "", 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": [ "Schema", "Database" ], "CommandName": "Remove-DbaDbSchema", "Name": "Remove-DbaDbSchema", "Author": "Adam Lancaster, github.com/lancasteradam", "Syntax": "Remove-DbaDbSchema [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [-Schema] \u003cString[]\u003e [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "None\nThis command does not return any output objects. It removes the specified database schemas and returns no information about the operation.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaDbSchema -SqlInstance sqldev01 -Database example1 -Schema TestSchema1\nRemoves the TestSchema1 schema in the example1 database in the sqldev01 instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sqldev01, sqldev02 -Database example1 | Remove-DbaDbSchema -Schema TestSchema1, TestSchema2\nPasses in the example1 db via pipeline and removes the TestSchema1 and TestSchema2 schemas.", "Description": "Removes database schemas from SQL Server databases using the DROP SCHEMA T-SQL command. This function is useful for cleaning up unused schemas during database maintenance, development environment resets, or application decommissioning. The schema must be completely empty before removal - any tables, views, functions, or other objects within the schema will prevent the drop operation from succeeding. You\u0027ll need to remove or relocate all schema objects first before running this command.", "Links": "https://dbatools.io/Remove-DbaDbSchema", "Synopsis": "Removes database schemas from one or more 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 target database(s) where schemas will be removed. Required when using SqlInstance parameter.\r\nUse this to limit schema removal to specific databases rather than affecting all databases on the instance.", "", false, "false", "", "" ], [ "Schema", "Specifies the name(s) of the schema(s) to remove from the target databases. The schema must be completely empty before removal.\r\nAny tables, views, functions, stored procedures, or other objects within the schema must be dropped or moved first.", "", true, "false", "", "" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase via pipeline input. Use this when you need to work with pre-filtered database collections.\r\nEliminates the need to specify SqlInstance and Database parameters when database objects are already available.", "", 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": "Remove-DbaDbSequence", "Name": "Remove-DbaDbSequence", "Author": "Adam Lancaster, github.com/lancasteradam", "Syntax": "Remove-DbaDbSequence [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cString[]\u003e] [-Sequence \u003cString[]\u003e] [-Schema \u003cString[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nRemove-DbaDbSequence -InputObject \u003cSequence[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per sequence removed, with the following properties:\n- ComputerName: The name of the computer where the sequence was dropped\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 sequence\r\n- Sequence: The fully qualified sequence name in format schema.name\r\n- SequenceName: The name of the sequence without schema qualification\r\n- SequenceSchema: The schema name containing the sequence\r\n- Status: The result of the drop operation (either \"Dropped\" on success or the error message on failure)\r\n- IsRemoved: Boolean indicating if the sequence was successfully dropped ($true) or failed ($false)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaDbSequence -SqlInstance sqldev01 -Database TestDB -Sequence TestSequence\nRemoves the sequence TestSequence in the TestDB database on the sqldev01 instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbSequence -SqlInstance SRV1 | Out-GridView -Title \u0027Select sequence(s) to drop\u0027 -OutputMode Multiple | Remove-DbaDbSequence\nUsing a pipeline this command gets all sequences on SRV1, lets the user select those to remove and then removes the selected sequences.", "Description": "Removes sequence objects from SQL Server databases, freeing up schema namespace and cleaning up unused database objects.\nSequences are commonly used for generating unique numeric values and may need removal during application changes or database cleanup.\n\nWhen used without a pipeline, the function will first retrieve matching sequences using Get-DbaDbSequence with the provided parameters, then remove them.\nPipeline input from Get-DbaDbSequence allows for selective removal after review or filtering.", "Links": "https://dbatools.io/Remove-DbaDbSequence", "Synopsis": "Removes database sequence objects from SQL Server instances.", "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 search for sequences to remove. Accepts wildcards for pattern matching.\r\nUse this to limit sequence removal to specific databases instead of searching all databases on the instance.", "", false, "false", "", "" ], [ "Sequence", "Specifies the name(s) of the sequences to remove. Accepts wildcards for pattern matching.\r\nUse this when you know the exact sequence names or want to remove sequences matching a naming pattern.", "Name", false, "false", "", "" ], [ "Schema", "Filters sequences to remove by schema name. Accepts wildcards for pattern matching.\r\nUseful when you need to remove sequences from specific schemas only, such as during application module cleanup.", "", false, "false", "", "" ], [ "InputObject", "Accepts sequence objects piped from Get-DbaDbSequence for removal.\r\nThis allows you to first review sequences with Get-DbaDbSequence before selectively removing them.", "", 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.\r\nThis is the default. Use -Confirm:$false to suppress these prompts.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Snapshot", "Database" ], "CommandName": "Remove-DbaDbSnapshot", "Name": "Remove-DbaDbSnapshot", "Author": "Simone Bizzotto (@niphold)", "Syntax": "Remove-DbaDbSnapshot [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-ExcludeDatabase] \u003cString[]\u003e] [[-Snapshot] \u003cString[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-AllSnapshots] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per snapshot dropped, with the following properties:\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The name of the computer where the snapshot was dropped\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 snapshot that was dropped (displayed as Name, stored as Database)\r\n- Status: The result of the drop operation (either \"Dropped\" on success or the error message on failure)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaDbSnapshot -SqlInstance sql2014 -Snapshot HR_snap_20161201, HR_snap_20161101\nRemoves database snapshots named HR_snap_20161201 and HR_snap_20161101\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaDbSnapshot -SqlInstance sql2014 -Database HR, Accounting\nRemoves all database snapshots having HR and Accounting as base dbs\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbSnapshot -SqlInstance sql2014 -Database HR, Accounting | Remove-DbaDbSnapshot\nRemoves all database snapshots having HR and Accounting as base dbs\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eRemove-DbaDbSnapshot -SqlInstance sql2014 -Snapshot HR_snapshot, Accounting_snapshot\nRemoves HR_snapshot and Accounting_snapshot\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaDbSnapshot -SqlInstance sql2016 | Where-Object SnapshotOf -like \u0027*dumpsterfire*\u0027 | Remove-DbaDbSnapshot\nRemoves all snapshots associated with databases that have dumpsterfire in the name\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaDbSnapshot -SqlInstance sql2016 | Out-GridView -PassThru | Remove-DbaDbSnapshot\nAllows the selection of snapshots on sql2016 to remove\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eRemove-DbaDbSnapshot -SqlInstance sql2014 -AllSnapshots\nRemoves all database snapshots from sql2014\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eRemove-DbaDbSnapshot -SqlInstance sql2014 -AllSnapshots -Confirm\nRemoves all database snapshots from sql2014 and prompts for each database", "Description": "Removes database snapshots by executing DROP DATABASE statements against the target SQL Server instances. Database snapshots are point-in-time, read-only copies of databases that consume minimal space through copy-on-write technology. This function helps DBAs clean up obsolete snapshots that are no longer needed for reporting, testing, or recovery purposes. The Force parameter can terminate active connections to snapshots that might otherwise prevent the drop operation from succeeding.", "Links": "https://dbatools.io/Remove-DbaDbSnapshot", "Synopsis": "Drops database snapshots 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", "", "" ], [ "Database", "Specifies the base database(s) whose snapshots should be removed. Only snapshots created from these source databases will be dropped.\r\nUse this when you need to clean up snapshots for specific databases while leaving other snapshots intact.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes snapshots from the specified base database(s) from removal. All other snapshots on the instance will be removed.\r\nUse this when you want to remove most snapshots but preserve those from critical databases.", "", false, "false", "", "" ], [ "Snapshot", "Specifies the exact snapshot name(s) to remove. Accepts multiple snapshot names for targeted removal operations.\r\nUse this when you know the specific snapshot names you want to drop, such as outdated test or reporting snapshots.", "", false, "false", "", "" ], [ "InputObject", "Accepts database snapshot objects from Get-DbaDbSnapshot for pipeline operations. This allows filtering and processing snapshots before removal.\r\nUse this for complex filtering scenarios where you first identify specific snapshots with Get-DbaDbSnapshot.", "", false, "true (ByValue)", "", "" ], [ "AllSnapshots", "Removes all database snapshots found on the target SQL Server instance(s). This affects every snapshot regardless of source database.\r\nUse this for complete snapshot cleanup operations, typically during maintenance windows or server decommissioning.", "", false, "false", "False", "" ], [ "Force", "Terminates active connections and running queries against snapshots to allow the drop operation to complete successfully.\r\nUse this when snapshots have active sessions that would normally block the removal process.", "", 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", "wi", false, "false", "", "" ], [ "Confirm", "Prompts for confirmation of every step.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Synonym", "Database" ], "CommandName": "Remove-DbaDbSynonym", "Name": "Remove-DbaDbSynonym", "Author": "Mikey Bronowski (@MikeyBronowski), bronowski.it", "Syntax": "Remove-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] \u003cObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per synonym successfully removed, containing the following properties:\n- ComputerName: The name of the computer where the SQL Server instance resides\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 from which the synonym was removed\r\n- Synonym: The name of the synonym that was removed\r\n- Status: The status of the removal operation (set to \"Removed\" on success)\nNote: Failed removal operations are reported through error handling but do not produce output objects.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaDbSynonym -SqlInstance localhost -Database db1 -Synonym \"synonym1\", \"synonym2\"\nRemoves synonyms synonym1 and synonym2 from the database db1 on the local default SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaDbSynonym -SqlInstance localhost, sql2016 -Database db1, db2 -Synonym synonym1, synonym2, synonym3\nRemoves synonym1, synonym2, synonym3 from db1 and db2 on the local and sql2016 SQL Server instances\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$servers = Get-Content C:\\servers.txt\nPS C:\\\u003e $servers | Remove-DbaDbSynonym -Database db1, db2 -Synonym synonym1\nRemoves synonym1 from db1 and db2 on the servers in C:\\servers.txt\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$synonyms = Get-DbaDbSynonym -SqlInstance localhost, sql2016 -Database db1, db2 -Synonym synonym1, synonym2, synonym3\nPS C:\\\u003e $synonyms | Remove-DbaDbSynonym\nRemoves synonym1, synonym2, synonym3 from db1 and db2 on the local and sql2016 SQL Server instances", "Description": "Removes one or more database synonyms from SQL Server databases by executing DROP SYNONYM commands. Synonyms are database objects that provide alternate names for tables, views, or other objects, often used to simplify complex object names or provide abstraction layers. This function helps clean up obsolete synonyms during database refactoring, migrations, or general maintenance activities, so you don\u0027t have to manually script DROP statements across multiple databases or instances.", "Links": "https://dbatools.io/Remove-DbaDbSynonym", "Synopsis": "Removes database synonyms 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 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 remove synonyms from. Accepts wildcards for pattern matching.\r\nUse this to target specific databases instead of processing all databases on the instance. If unspecified, all databases will be processed.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies databases to skip during synonym removal operations.\r\nUse this when you want to process most databases but exclude specific ones like system databases or production databases during maintenance windows.", "", false, "false", "", "" ], [ "Schema", "Specifies which schemas to target for synonym removal within the selected databases.\r\nUse this to limit removal to synonyms in specific schemas like \u0027dbo\u0027, \u0027reporting\u0027, or custom application schemas. If unspecified, all schemas will be processed.", "", false, "false", "", "" ], [ "ExcludeSchema", "Specifies schemas to skip during synonym removal operations.\r\nUse this to avoid removing synonyms from critical schemas while processing others, such as excluding \u0027sys\u0027 or application-specific schemas.", "", false, "false", "", "" ], [ "Synonym", "Specifies the exact synonym names to remove from the target databases.\r\nUse this when you need to remove specific synonyms by name rather than all synonyms. Supports multiple synonym names for bulk operations. If unspecified, all synonyms will be processed.", "", false, "false", "", "" ], [ "ExcludeSynonym", "Specifies synonym names to skip during the removal operation.\r\nUse this when you want to remove most synonyms but preserve specific ones that are still in use by applications or reports.", "", false, "false", "", "" ], [ "InputObject", "Accepts piped input from Get-DbaDbSynonym, Get-DbaDatabase, or SQL Server instances.\r\nUse this to remove synonyms that were identified by Get-DbaDbSynonym or to process multiple server instances from pipeline input. This enables more precise control over which synonyms to remove.", "", 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": [ "Table", "Database" ], "CommandName": "Remove-DbaDbTable", "Name": "Remove-DbaDbTable", "Author": "Andreas Jordan (@JordanOrdix), ordix.de", "Syntax": "Remove-DbaDbTable [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-Table] \u003cString[]\u003e] [[-InputObject] \u003cTable[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per table removed, containing the following properties:\n- ComputerName: The name of the computer where the SQL Server instance resides\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 table\r\n- Table: The full table name in schema.name format\r\n- TableName: The name of the table without schema prefix\r\n- TableSchema: The schema name containing the table\r\n- Status: The result of the removal operation (\"Dropped\" on success, or the error message on failure)\r\n- IsRemoved: Boolean indicating whether the table was successfully removed (true for success, false for failure)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaDbTable -SqlInstance localhost, sql2016 -Database db1, db2 -Table table1, table2, table3\nRemoves table1, table2, table3 from db1 and db2 on the local and sql2016 SQL Server instances.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$tables = Get-DbaDbTable -SqlInstance localhost, sql2016 -Database db1, db2 -Table table1, table2, table3\nPS C:\\\u003e $tables | Remove-DbaDbTable\nRemoves table1, table2, table3 from db1 and db2 on the local and sql2016 SQL Server instances.", "Description": "Permanently removes tables from one or more databases using SQL Server Management Objects (SMO). This function provides a safer alternative to manual DROP TABLE statements by including built-in confirmation prompts and comprehensive error handling. You can specify tables directly by name or pipe table objects from Get-DbaDbTable for more complex filtering scenarios. Each removal operation returns detailed status information including success confirmation and specific error messages when failures occur.", "Links": "https://dbatools.io/Remove-DbaDbTable", "Synopsis": "Drops tables from SQL Server databases with safety controls and detailed status reporting.", "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 target for table removal operations. Accepts multiple database names as an array.\r\nUse this when you need to remove tables from specific databases rather than searching across all databases on the instance.", "", false, "false", "", "" ], [ "Table", "Specifies the names of tables to remove from the target databases. Accepts multiple table names as an array.\r\nTables should be specified by name only (without schema prefix) as the function will find tables regardless of schema. Use Get-DbaDbTable for more complex filtering scenarios.", "Name", false, "false", "", "" ], [ "InputObject", "Accepts table objects directly from Get-DbaDbTable for removal operations. This approach allows for advanced filtering and validation before deletion.\r\nUse this parameter when you need to remove tables based on complex criteria like size, row count, or schema patterns that Get-DbaDbTable can filter.", "", 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.\r\nThis is the default. Use -Confirm:$false to suppress these prompts.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Table", "Data" ], "CommandName": "Remove-DbaDbTableData", "Name": "Remove-DbaDbTableData", "Author": "Adam Lancaster, github.com/lancasteradam", "Syntax": "Remove-DbaDbTableData [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-BatchSize] \u003cInt32\u003e] [[-Table] \u003cString\u003e] [[-DeleteSql] \u003cString\u003e] [[-LogBackupPath] \u003cString\u003e] [[-LogBackupTimeStampFormat] \u003cString\u003e] [[-AzureBaseUrl] \u003cString[]\u003e] [[-AzureCredential] \u003cString\u003e] [[-InputObject] \u003cObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database where table data removal was performed, providing detailed metrics about the batch deletion operation.\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- Database: The name of the database where table data was removed\r\n- Sql: The T-SQL DELETE statement that was executed\r\n- TotalRowsDeleted: The total number of rows deleted from the table across all batches (integer)\r\n- TotalTimeMillis: The total execution time for all delete operations in milliseconds (double)\r\n- AvgTimeMillis: The average execution time per batch iteration in milliseconds (double)\r\n- TotalIterations: The number of batch iterations performed (integer)\nAdditional properties available (all properties accessible via Select-Object *):\r\n- Timings: Array of TimeSpan objects representing the execution time of each individual batch deletion iteration\r\n- LogBackups: Array of backup objects returned from Backup-DbaDatabase operations performed during the deletion (empty for Simple recovery model or Azure SQL Database)\nWhen using Select-DefaultView without parameters, only the default properties listed above are displayed. Use Select-Object * to access the Timings and LogBackups array properties if needed for \r\nadvanced analysis of the deletion performance metrics.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaDbTableData -SqlInstance localhost -Database TestDb -Table dbo.Test -BatchSize 1000000 -LogBackupPath E:\\LogBackups -Confirm:$false\nRemoves all data from the dbo.Test table in the TestDb database on the local SQL instance. The deletes are done in batches of 1000000 rows each and the log backups are written to E:\\LogBackups.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaDbTableData -SqlInstance localhost -Database TestDb -DeleteSql \"DELETE TOP (1000000) deleteFromTable FROM dbo.Test deleteFromTable LEFT JOIN dbo.Test2 b ON deleteFromTable.Id = b.Id\" \r\n-LogBackupPath E:\\LogBackups -Confirm:$false\nRemoves data from the dbo.Test table in the TestDb database on the local SQL instance. When specifying -DeleteSql the DELETE statement needs to specify the TOP (N) clause. In this example the deletes \r\nare done in batches of 1000000 rows each and the log backups are written to E:\\LogBackups.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRemove-DbaDbTableData -SqlInstance localhost -Database TestDb -Table dbo.Test -DeleteSql \"WITH ToDelete AS (SELECT TOP (1000000) Id FROM dbo.Test ORDER BY Id DESC;) DELETE FROM ToDelete;\" \r\n-LogBackupPath E:\\LogBackups -Confirm:$false\nRemoves data from the dbo.Test table based on the DELETE statement specified in the -DeleteSql. The deletes occur in the TestDb database on the local SQL instance. The deletes are done in batches of \r\n1000000 rows each and the log backups are written to E:\\LogBackups.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance localhost -Database TestDb1, TestDb2 | Remove-DbaDbTableData -Table dbo.Test -BatchSize 1000000 -LogBackupPath E:\\LogBackups -Confirm:$false\nRemoves data from the dbo.Test table in the TestDb1 and TestDb2 databases on the local SQL instance. The deletes are done in batches of 1000000 rows each and the log backups are written to \r\nE:\\LogBackups.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$server, $server2 | Remove-DbaDbTableData -Database TestDb -Table dbo.Test -BatchSize 1000000 -LogBackupPath E:\\LogBackups -Confirm:$false\nRemoves data from the dbo.Test table in the TestDb database on the SQL instances represented by $server and $server2. The deletes are done in batches of 1000000 rows each and the log backups are \r\nwritten to E:\\LogBackups.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e$server = Connect-DbaInstance -ConnectionString \"Data Source=TCP:yourserver.database.windows.net,1433;MultipleActiveResultSets=False;Connect \r\nTimeout=30;Encrypt=True;TrustServerCertificate=False;User Id=dbuser;Password=strongpassword;Database=TestDb\"\nRemove-DbaDbTableData -SqlInstance $server -Database TestDb -Table dbo.Test -BatchSize 1000000 -Confirm:$false\nRemoves data from the dbo.Test table in the TestDb database on the Azure SQL server yourserver.database.windows.net. The deletes are done in batches of 1000000 rows. Log backups are managed by Azure \r\nSQL. Note: for Azure SQL databases error 40552 could occur for large batch deletions: \r\nhttps://docs.microsoft.com/en-us/azure/azure-sql/database/troubleshoot-common-errors-issues#error-40552-the-session-has-been-terminated-because-of-excessive-transaction-log-space-usage", "Description": "Safely removes large amounts of table data without causing transaction log file growth issues that typically occur with single large DELETE operations. This command implements Aaron Bertrand\u0027s chunked deletion technique (https://sqlperformance.com/2013/03/io-subsystem/chunk-deletes) to break large deletions into manageable batches, preventing log file expansion and blocking issues.\n\nThis is essential for DBAs who need to purge historical data, clean up audit tables, implement data retention policies, or remove test data without impacting database performance or running out of log space. The command automatically handles transaction log management based on your recovery model - taking log backups for Full/Bulk-logged recovery or performing checkpoints for Simple recovery.\n\nForeign key constraints are respected and not temporarily disabled, so you need to delete from dependent tables first or ensure cascading deletes are configured. The command works with both on-premises SQL Server and Azure SQL Database, automatically adjusting log management strategies for each platform.\n\nTwo deletion modes are supported:\n1. Simple table deletion using -Table and -BatchSize parameters where the DELETE statement is automatically generated\n2. Complex deletions with custom WHERE clauses, JOINs, or ORDER BY using the -DeleteSql parameter for advanced scenarios\n\nThe command returns detailed metadata about the deletion process including row counts, timing information, and log backup details to help you monitor progress and performance.", "Links": "https://dbatools.io/Remove-DbaDbTableData", "Synopsis": "Performs batch deletion of table data while controlling transaction log growth during large-scale data removal operations.", "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 include in the table data removal operation. Accepts wildcards for pattern matching.\r\nIf unspecified, all user databases on the instance will be processed, which means the same table deletion will occur across multiple databases.", "", false, "false", "", "" ], [ "BatchSize", "Controls how many rows are deleted per batch to prevent transaction log growth and blocking issues. Defaults to 100,000 rows and accepts values between 1 and 1 billion.\r\nUse smaller batch sizes (10,000-50,000) for heavily indexed tables or when other users need access during the operation. Can only be used with -Table parameter.\r\nFor Azure SQL databases, large batch sizes may trigger error 40552 due to transaction log space limits.", "", false, "false", "100000", "" ], [ "Table", "Specifies the fully qualified table name from which to delete data (e.g., dbo.CustomerHistory, Sales.OrderDetails).\r\nUse this for simple scenarios where you want to delete all rows from a table. For complex deletions with WHERE clauses or JOINs, use -DeleteSql instead.", "", false, "false", "", "" ], [ "DeleteSql", "Provides a custom DELETE statement for complex deletion scenarios involving WHERE clauses, JOINs, or ORDER BY conditions.\r\nMust include a TOP (N) clause to control batch size (e.g., \"DELETE TOP (100000) FROM dbo.Orders WHERE OrderDate \u003c \u00272020-01-01\u0027\").\r\nUse this when -Table parameter is insufficient for your deletion logic. Cannot be combined with -Table or -BatchSize parameters.", "", false, "false", "", "" ], [ "LogBackupPath", "Specifies the directory path where transaction log backup files will be created during the deletion process.\r\nRequired for databases in Full or Bulk-logged recovery models to prevent log file growth during large deletions. Only applies to on-premises SQL Server instances.\r\nThe SQL Server service account must have write permissions to this directory. Not used for Simple recovery model or Azure SQL databases.", "", false, "false", "", "" ], [ "LogBackupTimeStampFormat", "Controls the timestamp format used in transaction log backup file names. Defaults to \u0027yyyyMMddHHmm\u0027 (e.g., 202312151430).\r\nUse Get-Date format strings to customize the naming pattern. Invalid formats will cause the operation to fail.\r\nHelps organize log backup files chronologically when performing multiple large deletion operations.", "", false, "false", "", "" ], [ "AzureBaseUrl", "Specifies the Azure Storage container URL for storing transaction log backups during the deletion process.\r\nUse this when you need log backups stored in Azure Blob Storage instead of local file system storage.\r\nCannot be combined with -LogBackupPath parameter. See Backup-DbaDatabase documentation for container URL format requirements.", "", false, "false", "", "" ], [ "AzureCredential", "Provides the credential name for authenticating to Azure Storage when using -AzureBaseUrl for log backups.\r\nMust reference a SQL Server credential that contains the Azure Storage account access key or SAS token.\r\nRequired when backing up transaction logs to Azure Blob Storage during the deletion process.", "", false, "false", "", "" ], [ "InputObject", "Accepts piped input from other dbatools commands like Get-DbaDatabase or Connect-DbaInstance.\r\nUse this to chain commands together, such as filtering databases first and then performing table data removal.\r\nSupports Database, Server, and DbaInstanceParameter objects from the dbatools 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", "" ], [ "WhatIf", "Shows what would happen if the command were to run. No actions are actually performed.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts for confirmation before executing any data modification operations.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Udf", "Database" ], "CommandName": "Remove-DbaDbUdf", "Name": "Remove-DbaDbUdf", "Author": "Mikey Bronowski (@MikeyBronowski), bronowski.it", "Syntax": "Remove-DbaDbUdf [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cString[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-ExcludeSystemUdf] [-Schema \u003cString[]\u003e] [-ExcludeSchema \u003cString[]\u003e] [-Name \u003cString[]\u003e] [-ExcludeName \u003cString[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nRemove-DbaDbUdf -InputObject \u003cObject[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per user-defined function or user-defined aggregate that was processed for removal.\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 fully qualified SQL Server instance name (computer\\instance format)\r\n- Database: The name of the database containing the UDF or UDA\r\n- Udf: The fully qualified name of the function (schema.name format)\r\n- UdfName: The unqualified function name\r\n- UdfSchema: The schema name containing the function\r\n- Status: The result of the removal operation (\"Dropped\" for successful removals, or error message for failures)\r\n- IsRemoved: Boolean indicating whether the UDF or UDA was successfully removed (True if dropped, False if failed)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaDbUdf -SqlInstance localhost, sql2016 -Database db1, db2 -Name udf1, udf2, udf3\nRemoves udf1, udf2, udf3 from db1 and db2 on the local and sql2016 SQL Server instances.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$udfs = Get-DbaDbUdf -SqlInstance localhost, sql2016 -Database db1, db2 -Name udf1, udf2, udf3\nPS C:\\\u003e $udfs | Remove-DbaDbUdf\nRemoves udf1, udf2, udf3 from db1 and db2 on the local and sql2016 SQL Server instances.", "Description": "Removes user-defined functions and user-defined aggregates from specified databases, providing a clean way to drop obsolete or unwanted UDFs and UDAs without manual T-SQL scripting. This function is particularly useful during database cleanup operations, code refactoring projects, or when removing deprecated functions that are no longer needed. Supports filtering by schema and function name, and can exclude system UDFs to prevent accidental removal of built-in functions. Works seamlessly with Get-DbaDbUdf for pipeline operations.", "Links": "https://dbatools.io/Remove-DbaDbUdf", "Synopsis": "Removes user-defined functions and user-defined aggregates from SQL Server databases.", "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 process for UDF removal. Accepts multiple database names and supports wildcards.\r\nUse this to limit the operation to specific databases instead of processing all databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies databases to skip during UDF removal operations. Auto-populated with server database names for tab completion.\r\nUse this when you want to process most databases but exclude specific ones like production or system databases.", "", false, "false", "", "" ], [ "ExcludeSystemUdf", "Excludes system-generated and built-in user-defined functions from removal operations.\r\nUse this safety switch to prevent accidental deletion of system UDFs that may be required for database functionality.", "", false, "false", "False", "" ], [ "Schema", "Specifies which schemas to include when removing UDFs. Accepts multiple schema names.\r\nUse this to target UDFs in specific schemas like \u0027dbo\u0027, \u0027reporting\u0027, or custom application schemas while leaving others untouched.", "", false, "false", "", "" ], [ "ExcludeSchema", "Specifies schemas to skip during UDF removal operations.\r\nUse this to protect critical schemas from modification while processing UDFs in other schemas throughout the database.", "", false, "false", "", "" ], [ "Name", "Specifies the exact names of UDFs to remove. Accepts multiple function names and supports wildcards.\r\nUse this for targeted removal of specific functions like deprecated calculation functions or obsolete business logic UDFs.", "", false, "false", "", "" ], [ "ExcludeName", "Specifies UDF names to skip during removal operations. Accepts multiple function names and wildcards.\r\nUse this to protect specific functions from deletion while removing others that match your criteria.", "", false, "false", "", "" ], [ "InputObject", "Accepts UDF and UDA objects directly from Get-DbaDbUdf pipeline operations.\r\nUse this when you need to filter or examine UDFs or UDAs first before removal, enabling complex selection logic not possible with simple name matching.", "", 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.\r\nThis is the default. Use -Confirm:$false to suppress these prompts.", "cf", false, "false", "", "" ] ] }, { "Tags": "User", "CommandName": "Remove-DbaDbUser", "Name": "Remove-DbaDbUser", "Author": "Doug Meyers (@dgmyrs)", "Syntax": "Remove-DbaDbUser [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] -User \u003cObject[]\u003e [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nRemove-DbaDbUser -InputObject \u003cUser[]\u003e [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per user successfully removed, with the following properties:\r\n- ComputerName: The computer name of the SQL Server instance where the user was removed\r\n- InstanceName: The SQL Server instance name where the user was removed\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: The database name from which the user was removed\r\n- User: The Microsoft.SqlServer.Management.Smo.User object that was removed\r\n- Status: Result of the removal operation - \"Dropped\" on success or \"Not Dropped\" on failure\nWhen a user owns database objects or schemas that cannot be handled (without -Force), no output is generated for that user. Use -Force to override schema ownership restrictions and ensure user \r\nremoval succeeds.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaDbUser -SqlInstance sqlserver2014 -User user1\nDrops user1 from all databases it exists in on server \u0027sqlserver2014\u0027.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaDbUser -SqlInstance sqlserver2014 -Database database1 -User user1\nDrops user1 from the database1 database on server \u0027sqlserver2014\u0027.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRemove-DbaDbUser -SqlInstance sqlserver2014 -ExcludeDatabase model -User user1\nDrops user1 from all databases it exists in on server \u0027sqlserver2014\u0027 except for the model database.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbUser sqlserver2014 | Where-Object Name -In \"user1\" | Remove-DbaDbUser\nDrops user1 from all databases it exists in on server \u0027sqlserver2014\u0027.", "Description": "Safely removes database users from SQL Server databases while automatically handling schema ownership conflicts that would normally prevent user deletion. This eliminates the manual process of identifying and resolving schema ownership issues before removing users.\n\nWhen a user owns schemas, the function intelligently manages the cleanup: schemas with the same name as the user are dropped (if empty), while other owned schemas have their ownership transferred to \u0027dbo\u0027. If schemas contain objects, use -Force to allow ownership transfer and proceed with user removal.\n\nThe function works across multiple databases and instances, making it ideal for cleanup operations during user deprovisioning or database migrations where you need to remove users without leaving orphaned objects or broken ownership chains.", "Links": "https://dbatools.io/Remove-DbaDbUser", "Synopsis": "Removes database users from SQL Server databases with intelligent schema ownership handling", "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 the database(s) from which to remove the specified users. Accepts wildcards for pattern matching.\r\nWhen omitted, the function processes all accessible databases on the instance to find and remove the specified users.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies the database(s) to skip during user removal operations. Use this to protect critical databases like system databases.\r\nCommonly used to exclude model, tempdb, or production databases during bulk user cleanup operations.", "", false, "false", "", "" ], [ "User", "Specifies the database user(s) to remove from the target databases. Accepts multiple user names for bulk operations.\r\nThe function will automatically handle schema ownership conflicts that typically prevent user deletion.", "", true, "false", "", "" ], [ "InputObject", "Accepts user objects from Get-DbaDbUser for pipeline operations. This allows for advanced filtering scenarios.\r\nUse this when you need to remove users based on complex criteria like creation date, permissions, or other user properties.", "", true, "true (ByValue)", "", "" ], [ "Force", "Forces schema ownership transfer to \u0027dbo\u0027 when the user owns schemas containing database objects. Without this, user removal fails if owned schemas contain objects.\r\nUse this during user deprovisioning when you need to ensure complete cleanup regardless of schema dependencies.", "", 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", "If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "View", "Database" ], "CommandName": "Remove-DbaDbView", "Name": "Remove-DbaDbView", "Author": "Mikey Bronowski (@MikeyBronowski), bronowski.it", "Syntax": "Remove-DbaDbView [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cString[]\u003e] [-View \u003cString[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nRemove-DbaDbView -InputObject \u003cView[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per view removed, with the following properties:\r\n- ComputerName: The computer name of the SQL Server instance where the view was removed\r\n- InstanceName: The SQL Server instance name where the view was removed\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- Database: The database name from which the view was removed\r\n- View: The schema-qualified view name in the format \u0027schema.viewname\u0027 (e.g., \u0027dbo.MyView\u0027)\r\n- ViewName: The view name only (without schema prefix)\r\n- ViewSchema: The schema name containing the view\r\n- Status: Result of the removal operation - \"Dropped\" on success or the error message on failure\r\n- IsRemoved: Boolean indicating whether the view was successfully removed ($true) or failed ($false)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaDbView -SqlInstance localhost, sql2016 -Database db1, db2 -View view1, view2, view3\nRemoves view1, view2, view3 from db1 and db2 on the local and sql2016 SQL Server instances.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$views = Get-DbaDbView -SqlInstance localhost, sql2016 -Database db1, db2 -View view1, view2, view3\nPS C:\\\u003e $views | Remove-DbaDbView\nRemoves view1, view2, view3 from db1 and db2 on the local and sql2016 SQL Server instances.", "Description": "Removes one or more database views from specified databases and SQL Server instances. This function streamlines the cleanup of obsolete views during database refactoring, development cleanup, or schema maintenance tasks. You can specify views individually by name or use pipeline input from Get-DbaDbView for bulk operations. Each removal operation includes detailed status reporting and supports WhatIf testing to preview changes before execution.", "Links": "https://dbatools.io/Remove-DbaDbView", "Synopsis": "Removes database views from SQL Server databases", "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 search for views to remove. Accepts multiple database names.\r\nUse this to limit view removal to specific databases instead of searching all databases on the instance.", "", false, "false", "", "" ], [ "View", "Specifies the names of the views to remove. Accepts multiple view names and supports wildcards for pattern matching.\r\nWhen targeting views in specific schemas, use the two-part naming convention like \u0027dbo.ViewName\u0027.", "", false, "false", "", "" ], [ "InputObject", "Accepts view objects from Get-DbaDbView for pipeline operations. Use this for complex filtering scenarios or bulk removals.\r\nThis approach provides better control over which specific views get removed compared to using name-based targeting.", "", 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.\r\nThis is the default. Use -Confirm:$false to suppress these prompts.", "cf", false, "false", "", "" ] ] }, { "Tags": "Endpoint", "CommandName": "Remove-DbaEndpoint", "Name": "Remove-DbaEndpoint", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Remove-DbaEndpoint [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Endpoint] \u003cString[]\u003e] [-AllEndpoints] [[-InputObject] \u003cEndpoint[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per successfully removed endpoint.\nProperties:\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 (ComputerName\\InstanceName)\r\n- Endpoint: The name of the endpoint that was removed\r\n- Status: The status of the removal operation (always \"Removed\" for successful removals)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaEndpoint -SqlInstance sqlserver2012 -AllEndpoints\nRemoves all endpoints on the sqlserver2014 instance. Prompts for confirmation.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaEndpoint -SqlInstance sqlserver2012 -Endpoint endpoint1,endpoint2 -Confirm:$false\nRemoves the endpoint1 and endpoint2 endpoints. Does not prompt for confirmation.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaEndpoint -SqlInstance sqlserver2012 -Endpoint endpoint1 | Remove-DbaEndpoint\nRemoves the endpoints returned from the Get-DbaEndpoint function. Prompts for confirmation.", "Description": "Removes SQL Server endpoints by executing DROP ENDPOINT commands against the target instance. This function handles DatabaseMirroring, ServiceBroker, Soap, and TSql endpoint types, making it useful for decommissioning unused services, cleaning up after failed deployments, or hardening SQL Server instances by removing unnecessary network entry points. You can target specific endpoints by name or remove all endpoints at once, with confirmation prompts to prevent accidental deletions.", "Links": "https://dbatools.io/Remove-DbaEndpoint", "Synopsis": "Removes SQL Server endpoints including DatabaseMirroring, ServiceBroker, Soap, and TSql types.", "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", "", "" ], [ "Endpoint", "Specifies the names of specific endpoints to remove from the SQL Server instance. Accepts multiple endpoint names as an array.\r\nUse this when you need to selectively remove particular endpoints like \u0027Mirroring\u0027 or custom service broker endpoints while leaving others intact.", "", false, "false", "", "" ], [ "AllEndpoints", "Removes all user-defined endpoints from the SQL Server instance, excluding system endpoints that cannot be dropped.\r\nUse this for complete endpoint cleanup during decommissioning or when hardening an instance by removing all custom network entry points.", "", false, "false", "False", "" ], [ "InputObject", "Accepts endpoint objects from the pipeline, typically from Get-DbaEndpoint output. Allows for filtering endpoints before removal.\r\nUse this when you need to apply complex filtering logic or when chaining endpoint discovery and removal operations 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", "" ], [ "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": "extendedproperties", "CommandName": "Remove-DbaExtendedProperty", "Name": "Remove-DbaExtendedProperty", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Remove-DbaExtendedProperty [-InputObject] \u003cExtendedProperty[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per successfully removed extended property.\nProperties:\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 (ComputerName\\InstanceName)\r\n- ParentName: The name of the parent SQL Server object from which the extended property was removed\r\n- PropertyType: The type of extended property that was removed\r\n- Name: The name of the extended property that was removed\r\n- Status: The status of the removal operation (always \"Dropped\" for successful removals)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance localhost -Database mydb | Get-DbaExtendedProperty -Name appversion | Remove-DbaExtendedProperty\nRemoves the appversion extended property from the mydb database\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbTable -SqlInstance localhost -Database mydb -Table mytable | Get-DbaExtendedProperty -Name appversion | Remove-DbaExtendedProperty -Confirm:$false\nRemoves the appversion extended property on the mytable table of the mydb database and does not prompt for confirmation", "Description": "Removes extended properties that contain custom metadata, documentation, and business descriptions from SQL Server objects. Extended properties are commonly used to store object documentation, version information, compliance tags, and business rules directly within the database schema.\n\nThis function accepts piped input from Get-DbaExtendedProperty, making it easy to remove outdated documentation, clean up deprecated metadata, or bulk-remove properties during database restructuring projects. Works with all SQL Server object types including databases, tables, columns, stored procedures, and views.\n\nThe command uses sp_dropextendedproperty internally and returns status information for each removed property, so you can verify successful cleanup operations or track what was removed for audit purposes.", "Links": "https://dbatools.io/Remove-DbaExtendedProperty", "Synopsis": "Removes custom metadata and documentation stored as extended properties from SQL Server objects", "Availability": "Windows, Linux, macOS", "Params": [ [ "InputObject", "Specifies the extended property objects to remove from SQL Server objects. Accepts ExtendedProperty objects from Get-DbaExtendedProperty.\r\nUse this to remove outdated documentation, compliance tags, or metadata stored as extended properties on databases, tables, columns, and other SQL Server objects.", "", 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": [ "Firewall", "Network", "Connection" ], "CommandName": "Remove-DbaFirewallRule", "Name": "Remove-DbaFirewallRule", "Author": "Andreas Jordan (@JordanOrdix), ordix.de", "Syntax": "Remove-DbaFirewallRule [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-Credential \u003cPSCredential\u003e] [-Type \u003cString[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nRemove-DbaFirewallRule -InputObject \u003cObject[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per firewall rule that was removed from the target computer.\nProperties:\r\n- ComputerName: The name of the target computer where the firewall rule was removed\r\n- InstanceName: The SQL Server instance name associated with the firewall rule\r\n- SqlInstance: The full SQL Server instance identifier (ComputerName\\InstanceName)\r\n- DisplayName: The display name of the firewall rule that was removed\r\n- Type: The type of firewall rule removed (Engine, Browser, DAC, DatabaseMirroring, or AllInstance)\r\n- IsRemoved: Boolean indicating whether the firewall rule was successfully removed\r\n- Status: A descriptive status message indicating success or details about any warnings, errors, or exceptions encountered during removal", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaFirewallRule -SqlInstance SRV1\nRemoves the firewall rule for the default instance on SRV1.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaFirewallRule -SqlInstance SRV1\\SQL2016 -Type Engine, Browser\nRemoves the firewall rule for the instance SQL2016 on SRV1 and the firewall rule for the SQL Server Browser.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaFirewallRule -SqlInstance SRV1 -Type AllInstance | Where-Object Type -eq \u0027Engine\u0027 | Remove-DbaFirewallRule\nRemoves the firewall rules for all instance from SRV1. Leaves the firewall rule for the SQL Server Browser in place.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eRemove-DbaFirewallRule -SqlInstance SRV1 -Confirm:$false\nRemoves the firewall rule for the default instance on SRV1. Does not prompt for confirmation.", "Description": "Removes Windows firewall rules for SQL Server components from target computers, cleaning up network access rules when decommissioning instances or changing security configurations. This command only works with firewall rules that were previously created using New-DbaFirewallRule, as it relies on specific naming conventions and rule groups.\n\nThe function can remove rules for SQL Server Engine connections (typically port 1433 for default instances), SQL Server Browser service (UDP port 1434), and Dedicated Admin Connection (DAC) ports. This is particularly useful when decommissioning SQL Server instances, changing network security policies, or troubleshooting connectivity issues.\n\nThis command executes Remove-NetFirewallRule remotely on target computers using PowerShell remoting, so it requires appropriate permissions and network connectivity to the target systems. The function provides detailed status reporting for each removal operation, including success status and any warnings or errors encountered.\n\nThe functionality is currently limited to rules created by dbatools. Future versions may introduce breaking changes, so review scripts after updating dbatools.", "Links": "https://dbatools.io/Remove-DbaFirewallRule", "Synopsis": "Removes Windows firewall rules for SQL Server Engine, Browser, and DAC connections from target computers.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "false", "", "" ], [ "Credential", "Credential object used to connect to the Computer as a different user.", "", false, "false", "", "" ], [ "Type", "Specifies which types of SQL Server firewall rules to remove from the target computer.\r\nUse this to control exactly which network access rules are cleaned up when decommissioning or reconfiguring SQL Server instances.\r\nEngine removes rules for SQL Server database connections, Browser removes UDP port 1434 rules for SQL Server Browser service, DAC removes Dedicated Admin Connection rules, DatabaseMirroring removes \r\ndatabase mirroring or Availability Groups rules, and AllInstance removes all SQL Server-related rules. Defaults to Engine and DAC since Browser rules are often shared between multiple instances.", "", false, "false", "@(\u0027Engine\u0027, \u0027DAC\u0027)", "Engine,Browser,DAC,DatabaseMirroring,AllInstance" ], [ "InputObject", "Accepts firewall rule objects from Get-DbaFirewallRule for pipeline-based removal operations.\r\nUse this when you need to filter or review existing firewall rules before removing them, allowing for more precise control over which rules get deleted.", "", 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", "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": [ "LinkedServer", "Server" ], "CommandName": "Remove-DbaLinkedServer", "Name": "Remove-DbaLinkedServer", "Author": "Adam Lancaster, github.com/lancasteradam", "Syntax": "Remove-DbaLinkedServer [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-LinkedServer] \u003cString[]\u003e] [[-InputObject] \u003cObject[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "None\nThis command removes linked servers but does not return any output objects. It performs the deletion operation and handles any errors or confirmation prompts via -WhatIf and -Confirm parameters.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaLinkedServer -SqlInstance sql01 -LinkedServer linkedServer1 -Confirm:$false\nRemoves the linked server \"linkedServer1\" from the sql01 instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaLinkedServer -SqlInstance sql01 -LinkedServer linkedServer1 -Confirm:$false -Force\nRemoves the linked server \"linkedServer1\" and the associated linked server logins from the sql01 instance.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$linkedServer1 = Get-DbaLinkedServer -SqlInstance sql01 -LinkedServer linkedServer1\nPS C:\\\u003e$linkedServer1 | Remove-DbaLinkedServer -Confirm:$false\nPasses in a linked server via pipeline and removes it from the sql01 instance.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eConnect-DbaInstance -SqlInstance sql01 | Remove-DbaLinkedServer -LinkedServer linkedServer1 -Confirm:$false\nRemoves the linked server \"linkedServer1\" from the sql01 instance, which is passed in via pipeline.", "Description": "Removes one or more linked servers from target SQL Server instances. This function drops the linked server objects from the system catalog, effectively severing the connection between the local and remote servers. When using the -Force parameter, it also removes any associated linked server logins before dropping the linked server itself. This is useful for decommissioning legacy connections, cleaning up unused linked servers during server migrations, or removing connections for security compliance requirements.", "Links": "https://dbatools.io/Remove-DbaLinkedServer", "Synopsis": "Removes linked servers 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 remove from the SQL Server instance.\r\nUse this to target specific linked servers instead of removing all linked servers.\r\nAccepts an array of names when you need to remove multiple linked servers in a single operation.", "", false, "false", "", "" ], [ "InputObject", "Accepts linked server objects from Get-DbaLinkedServer or server instances from Connect-DbaInstance via pipeline.\r\nUse this when you want to remove linked servers that were previously retrieved with Get-DbaLinkedServer.\r\nWhen passing server instances, you must also specify the LinkedServer parameter to identify which linked servers to remove.", "", false, "true (ByValue)", "", "" ], [ "Force", "Removes all linked server logins associated with the linked server before dropping the linked server itself.\r\nUse this when the linked server has associated logins that would prevent removal.\r\nWithout this parameter, the removal will fail if any linked server logins exist, requiring you to manually remove them 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", "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": [ "Security", "Server" ], "CommandName": "Remove-DbaLinkedServerLogin", "Name": "Remove-DbaLinkedServerLogin", "Author": "Adam Lancaster, github.com/lancasteradam", "Syntax": "Remove-DbaLinkedServerLogin [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-LinkedServer] \u003cString[]\u003e] [[-LocalLogin] \u003cString[]\u003e] [[-InputObject] \u003cObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per linked server login processed, whether successfully removed or failed.\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- LinkedServer: The name of the linked server containing the removed login\r\n- Login: The name of the linked server login that was removed\r\n- Status: Either \"Removed\" on success or \"Failure\" if the operation failed", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaLinkedServerLogin -SqlInstance sql01 -LinkedServer linkedServer1 -LocalLogin linkedServerLogin1 -Confirm:$false\nRemoves the linkedServerLogin1 from the linkedServer1 linked server on the sql01 instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$instance = Connect-DbaInstance -SqlInstance sql01\nPS C:\\\u003e$instance | Remove-DbaLinkedServerLogin -LinkedServer linkedServer1 -LocalLogin linkedServerLogin1 -Confirm:$false\nPasses in a SqlInstance via pipeline and removes the linkedServerLogin1 from the linkedServer1 linked server.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$linkedServer1 = Get-DbaLinkedServer -SqlInstance sql01 -LinkedServer linkedServer1\nPS C:\\\u003e$linkedServer1 | Remove-DbaLinkedServerLogin -LocalLogin linkedServerLogin1 -Confirm:$false\nPasses in a linked server via pipeline and removes the linkedServerLogin1.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$linkedServerLogin1 = Get-DbaLinkedServerLogin -SqlInstance sql01 -LinkedServer linkedServer1 -LocalLogin linkedServerLogin1\nPS C:\\\u003e$linkedServerLogin1 | Remove-DbaLinkedServerLogin -Confirm:$false\nPasses in a linked server login via pipeline and removes it.", "Description": "Removes linked server login mappings, which are the credential associations that determine how local SQL Server logins authenticate to remote servers through linked server connections. These mappings control which credentials are used when executing queries against remote servers, so removing them effectively blocks access through that linked server for the specified local login. This is commonly used when decommissioning user access, cleaning up security configurations, or removing entire linked server setups.", "Links": "https://dbatools.io/Remove-DbaLinkedServerLogin", "Synopsis": "Removes linked server login mappings that define credential relationships between local and remote server logins.", "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 of the linked server containing the login mappings to remove. This is the linked server object that holds the credential associations between local and remote server logins.\r\nUse this when you need to remove login mappings from a specific linked server, such as when cleaning up security configurations or decommissioning user access.", "", false, "false", "", "" ], [ "LocalLogin", "Specifies the local login names whose linked server login mappings should be removed. These are the local SQL Server login accounts that have credential mappings defined for remote server access.\r\nUse this to remove specific login mappings rather than all mappings for a linked server, such as when a user account is being deactivated or their remote access needs to be revoked.", "", false, "false", "", "" ], [ "InputObject", "Accepts SQL Server instance objects, linked server objects, or linked server login objects from the pipeline for batch removal operations. Compatible with output from Connect-DbaInstance, \r\nGet-DbaLinkedServer, and Get-DbaLinkedServerLogin.\r\nUse this for pipeline operations when you want to remove login mappings from multiple objects or when chaining commands together for bulk security configuration changes.", "", 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": [ "Delete", "Login" ], "CommandName": "Remove-DbaLogin", "Name": "Remove-DbaLogin", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Remove-DbaLogin [-SqlCredential \u003cPSCredential\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nRemove-DbaLogin -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] -Login \u003cString[]\u003e [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nRemove-DbaLogin [-SqlCredential \u003cPSCredential\u003e] -InputObject \u003cLogin[]\u003e [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per login processed, whether successfully removed or failed.\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- Login: The name of the login that was removed\r\n- Status: Either \"Dropped\" on success or an error message describing the failure", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaLogin -SqlInstance sql2016 -Login mylogin\nPrompts then removes the Login mylogin on SQL Server sql2016\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaLogin -SqlInstance sql2016 -Login mylogin, yourlogin\nPrompts then removes the Logins mylogin and yourlogin on SQL Server sql2016\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRemove-DbaLogin -SqlInstance sql2016 -Login mylogin -Confirm:$false\nDoes not prompt and swiftly removes mylogin on SQL Server sql2016\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaLogin -SqlInstance server\\instance -Login yourlogin | Remove-DbaLogin\nRemoves mylogin on SQL Server server\\instance", "Description": "Removes one or more SQL Server logins from specified instances using the SMO Drop() method. This function handles the complete removal process including dependency checks and provides proper error handling when logins cannot be dropped due to existing sessions or database ownership. Use the -Force parameter to automatically terminate active sessions associated with the login before removal, which is useful when cleaning up test environments or decommissioning user accounts.", "Links": "https://dbatools.io/Remove-DbaLogin", "Synopsis": "Removes SQL Server logins from target instances", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "false", "", "" ], [ "SqlCredential", "Allows you to login to servers using alternative credentials.", "", false, "false", "", "" ], [ "Login", "Specifies the SQL Server login names to remove from the target instance. Accepts multiple login names as an array.\r\nUse this when you know the specific logins to delete, such as when cleaning up test accounts or decommissioned user logins.", "", true, "false", "", "" ], [ "InputObject", "Accepts login objects piped from Get-DbaLogin or other dbatools functions that return SQL Server login objects.\r\nUse this for advanced filtering scenarios or when chaining multiple dbatools commands together in a pipeline.", "", true, "true (ByValue)", "", "" ], [ "Force", "Automatically terminates any active database connections and sessions associated with the login before attempting removal.\r\nUse this when you need to forcibly remove logins that have active sessions, common in development environments or during emergency cleanup.", "", 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": "Remove-DbaNetworkCertificate", "Name": "Remove-DbaNetworkCertificate", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Remove-DbaNetworkCertificate [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance where the network certificate configuration was removed.\nProperties:\r\n- ComputerName: The name of the computer where the certificate was removed\r\n- InstanceName: The SQL Server instance name (extracted from DisplayName)\r\n- SqlInstance: The full SQL Server instance identifier (VSNAME)\r\n- ServiceAccount: The service account used by the SQL Server instance\r\n- RemovedThumbprint: The certificate thumbprint that was removed (or $null if none was configured)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaNetworkCertificate\nRemoves the Network Certificate for the default instance (MSSQLSERVER) on localhost\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaNetworkCertificate -SqlInstance sql1\\SQL2008R2SP2\nRemoves the Network Certificate for the SQL2008R2SP2 instance on sql1\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRemove-DbaNetworkCertificate -SqlInstance localhost\\SQL2008R2SP2 -WhatIf\nShows what would happen if the command were run", "Description": "Removes the certificate thumbprint from SQL Server\u0027s network encryption configuration by clearing the Certificate registry value in SuperSocketNetLib. This disables forced SSL encryption for client connections and returns the instance to unencrypted or optional encryption mode. Use this when decommissioning certificates, troubleshooting SSL connection issues, or when you need to reconfigure encryption settings from scratch.", "Links": "https://dbatools.io/Remove-DbaNetworkCertificate", "Synopsis": "Removes the SSL certificate configuration from SQL Server network encryption settings", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. Defaults to localhost. If target is a cluster, you must also specify InstanceClusterName (see below)", "", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Windows credentials for accessing the target computer\u0027s registry and WMI services. This is used for computer-level authentication, not SQL Server authentication.\r\nRequired when the current user lacks administrative privileges on the target server or when running against remote servers in different 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", "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": "PerfMon", "CommandName": "Remove-DbaPfDataCollectorCounter", "Name": "Remove-DbaPfDataCollectorCounter", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Remove-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 successfully removed from the Data Collector Set.\nProperties:\r\n- ComputerName: The name of the computer where the performance counter was removed\r\n- DataCollectorSet: The name of the Data Collector Set containing the collector\r\n- DataCollector: The name of the specific data collector within the Collector Set where the counter was removed\r\n- Name: The performance counter path that was removed\r\n- Status: The operation status (always \"Removed\" on success)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaPfDataCollectorCounter -ComputerName sql2017 -CollectorSet \u0027System Correlation\u0027 -Collector DataCollector01 -Counter \u0027\\LogicalDisk(*)\\Avg. Disk Queue Length\u0027\nPrompts for confirmation then removes 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-DbaPfDataCollectorCounter | Out-GridView -PassThru | Remove-DbaPfDataCollectorCounter -Confirm:$false\nAllows you to select which counters you\u0027d like on localhost and does not prompt for confirmation.", "Description": "Removes performance counters from existing Data Collector Sets in Windows Performance Monitor. This allows you to clean up monitoring configurations by removing counters that are no longer needed, reducing resource consumption and focusing on relevant metrics. Commonly used when fine-tuning SQL Server performance monitoring setups or removing counters that were added for troubleshooting specific issues.", "Links": "https://dbatools.io/Remove-DbaPfDataCollectorCounter", "Synopsis": "Removes specific performance counters from Windows Performance Monitor Data Collector Sets.", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the target computer(s) where the Performance Monitor Data Collector Set is configured. Accepts multiple computer names for bulk operations.\r\nUse this when you need to remove counters from collector sets on remote SQL Server machines or when managing performance monitoring across multiple servers.", "", false, "false", "$env:COMPUTERNAME", "" ], [ "Credential", "Allows you to login to the target computer 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 Performance Monitor Data Collector Set containing the counters to be removed. Supports wildcards for pattern matching across multiple sets.\r\nUse this when you know the specific collector set name where your performance counters are configured, such as \u0027System Correlation\u0027 or custom SQL Server monitoring sets.", "DataCollectorSet", false, "false", "", "" ], [ "Collector", "Specifies the name of the individual data collector within the collector set that contains the performance counters to remove. Supports multiple collector names.\r\nUse this to target specific data collectors when your collector set contains multiple collectors, allowing you to remove counters from only the collectors you specify.", "DataCollector", false, "false", "", "" ], [ "Counter", "Specifies the exact performance counter name(s) to remove from the data collector. Must use the full counter path format like \u0027\\Processor(_Total)\\% Processor Time\u0027 or \u0027\\SQLServer:Buffer \r\nManager\\Buffer cache hit ratio\u0027.\r\nUse this when you need to remove specific SQL Server or system performance counters that are no longer needed for monitoring, such as counters added for troubleshooting that are now consuming \r\nunnecessary resources.", "Name", true, "true (ByPropertyName)", "", "" ], [ "InputObject", "Accepts performance counter objects from Get-DbaPfDataCollectorCounter via the pipeline, allowing you to remove counters discovered through previous queries.\r\nUse this when you want to first review existing counters with Get-DbaPfDataCollectorCounter and then selectively remove specific ones through pipeline 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", "" ], [ "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": "PerfMon", "CommandName": "Remove-DbaPfDataCollectorSet", "Name": "Remove-DbaPfDataCollectorSet", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Remove-DbaPfDataCollectorSet [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-CollectorSet] \u003cString[]\u003e] [[-InputObject] \u003cObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per Performance Monitor Data Collector Set removed.\nProperties:\r\n- ComputerName: The name of the computer from which the collector set was removed\r\n- Name: The name of the Data Collector Set that was removed\r\n- Status: The operation status (Removed)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaPfDataCollectorSet\nPrompts for confirmation then removes all ready Collectors on localhost.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaPfDataCollectorSet -ComputerName sql2017 -Confirm:$false\nAttempts to remove all ready Collectors on localhost and does not prompt to confirm.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRemove-DbaPfDataCollectorSet -ComputerName sql2017, sql2016 -Credential ad\\sqldba -CollectorSet \u0027System Correlation\u0027\nPrompts for confirmation then removes the \u0027System Correlation\u0027 Collector on sql2017 and sql2016 using alternative credentials.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorSet -CollectorSet \u0027System Correlation\u0027 | Remove-DbaPfDataCollectorSet\nRemoves the \u0027System Correlation\u0027 Collector.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorSet -CollectorSet \u0027System Correlation\u0027 | Stop-DbaPfDataCollectorSet | Remove-DbaPfDataCollectorSet\nStops and removes the \u0027System Correlation\u0027 Collector.", "Description": "Removes Windows Performance Monitor Data Collector Sets that are no longer needed for SQL Server performance monitoring. This is useful for cleaning up old monitoring configurations, freeing disk space, or standardizing performance monitoring setups across your SQL Server environment. The collector set must be stopped before removal - running collector sets will generate an error and must be stopped first using Stop-DbaPfDataCollectorSet. When removing collector sets from the local computer, administrator privileges are required.", "Links": "https://dbatools.io/Remove-DbaPfDataCollectorSet", "Synopsis": "Removes Windows Performance Monitor Data Collector Sets from local or remote computers", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the target computer(s) where Performance Monitor Data Collector Sets will be removed. Supports multiple computers for bulk operations.\r\nUse this when removing collector sets from remote SQL Server hosts or when standardizing monitoring configurations across multiple servers.", "", false, "false", "$env:COMPUTERNAME", "" ], [ "Credential", "Allows you to login to the target computer using alternative credentials. To use:\n$cred = Get-Credential, then pass $cred object to the -Credential parameter.", "", false, "false", "", "" ], [ "CollectorSet", "Specifies the exact name(s) of the Performance Monitor Data Collector Sets to remove. Accepts multiple collector set names for batch operations.\r\nUse this when you need to remove specific monitoring configurations rather than all available collector sets on the target computer.", "DataCollectorSet", false, "false", "", "" ], [ "InputObject", "Accepts Data Collector Set objects from Get-DbaPfDataCollectorSet for pipeline operations. Enables chaining commands together for workflow automation.\r\nUse this when you need to filter collector sets with Get-DbaPfDataCollectorSet first, then remove only the matching 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", "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": "Remove-DbaRegServer", "Name": "Remove-DbaRegServer", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Remove-DbaRegServer [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Name] \u003cString[]\u003e] [[-ServerName] \u003cString[]\u003e] [[-Group] \u003cString[]\u003e] [[-InputObject] \u003cRegisteredServer[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per registered server removed from CMS or local registered server groups.\nDefault display properties vary based on server type:\nFor Central Management Server registered servers (with ID):\r\n- ComputerName: The name of the computer hosting the CMS instance\r\n- InstanceName: The SQL Server instance name of the CMS\r\n- SqlInstance: The full SQL Server instance name in format ComputerName\\InstanceName\r\n- Name: The display name of the registered server as shown in SSMS\r\n- ServerName: The actual SQL Server instance name or connection string\r\n- Status: The operation status (Dropped)\nFor local registered server groups (without ID):\r\n- Name: The display name of the registered server\r\n- ServerName: The actual SQL Server instance name or connection string\r\n- Status: The operation status (Dropped)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaRegServer -SqlInstance sql2012 -Group HR, Accounting\nRemoves all servers from the HR and Accounting groups on sql2012\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaRegServer -SqlInstance sql2012 -Group HR\\Development\nRemoves all servers from the HR and sub-group Development from the CMS on sql2012.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRemove-DbaRegServer -SqlInstance sql2012 -Confirm:$false\nRemoves all registered servers on sql2012 and turns off all prompting", "Description": "Removes registered servers from SQL Server Central Management Server (CMS) or local registered server groups within SQL Server Management Studio. This command helps DBAs clean up outdated server registrations, remove decommissioned servers, or reorganize server inventory without manually navigating through SSMS interfaces.\n\nYou can remove servers by specifying individual server names, registered server display names, or entire groups. The function works with both CMS hierarchies and local registered server groups, but cannot modify Azure Data Studio registered servers.", "Links": "https://dbatools.io/Remove-DbaRegServer", "Synopsis": "Removes registered servers from SQL Server Central Management Server or local registered server groups.", "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 registered server display names to remove from CMS or local registered servers.\r\nUse this when you need to remove servers by their friendly names as shown in the SSMS Registered Servers pane rather than actual server instance names.", "", false, "false", "", "" ], [ "ServerName", "Specifies actual SQL Server instance names to remove from registered servers.\r\nUse this when you need to remove servers by their connection strings or network names rather than display names, which is helpful when cleaning up instances that may have been registered with \r\ndifferent friendly names.", "", false, "false", "", "" ], [ "Group", "Removes all registered servers from specified Central Management Server groups. Supports hierarchical paths using backslash notation (e.g., \"Production\\Database Servers\").\r\nUse this when you need to clean out entire groups during environment changes, server migrations, or organizational restructuring.", "", false, "false", "", "" ], [ "InputObject", "Accepts registered server objects from Get-DbaRegServer for targeted removal operations.\r\nUse this for complex removal scenarios where you first query and filter servers, then pipe the results to remove specific servers based on properties or conditions.", "", 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": "Remove-DbaRegServerGroup", "Name": "Remove-DbaRegServerGroup", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Remove-DbaRegServerGroup [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Name] \u003cString[]\u003e] [[-InputObject] \u003cServerGroup[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per server group removed.\nFor server groups on Central Management Server (CMS), default display properties are:\r\n- ComputerName: The computer name of the CMS instance\r\n- InstanceName: The instance name of the CMS\r\n- SqlInstance: The full instance name of the CMS (computer\\instance)\r\n- Name: The name of the server group that was removed\r\n- Status: \"Dropped\" if successful\nFor local registered server groups, default display properties are:\r\n- Name: The name of the server group that was removed\r\n- Status: \"Dropped\" if successful\nNote: The PSCustomObject includes all properties listed above regardless of display mode. Use Select-Object * to see all properties when needed.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaRegServerGroup -SqlInstance sql2012 -Group HR, Accounting\nRemoves the HR and Accounting groups on sql2012\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaRegServerGroup -SqlInstance sql2012 -Group HR\\Development -Confirm:$false\nRemoves the Development subgroup within the HR group on sql2012 and turns off all prompting", "Description": "Deletes specified server groups from Central Management Server, including all nested subgroups and registered servers within those groups. This permanently removes the organizational structure you\u0027ve built in CMS, so use with caution. The function works with both local registered servers and CMS-based groups, and supports piping from Get-DbaRegServerGroup for targeted removal operations.", "Links": "https://dbatools.io/Remove-DbaRegServerGroup", "Synopsis": "Removes server groups from SQL Server Central Management Server (CMS).", "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 the name of one or more server groups to remove from Central Management Server or local registered servers. Supports hierarchical paths like \"HR\\Development\" to target subgroups within \r\nparent groups.\r\nUse this when you know the exact group names to delete and want to remove specific organizational structures from your CMS or local registered server configuration.", "Group", false, "false", "", "" ], [ "InputObject", "Accepts ServerGroup objects from Get-DbaRegServerGroup for pipeline operations. This allows you to first filter or query specific server groups, then remove them in a controlled manner.\r\nUse this approach when you need to perform complex filtering, review groups before deletion, or process large numbers of groups with conditional logic.", "", 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": "Remove-DbaReplArticle", "Name": "Remove-DbaReplArticle", "Author": "Jess Pomfret (@jpomfret), jesspomfret.com", "Syntax": "Remove-DbaReplArticle [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString\u003e] [[-Publication] \u003cString\u003e] [[-Schema] \u003cString\u003e] [[-Name] \u003cString\u003e] [[-InputObject] \u003cPSObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per article removed from the replication publication.\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 publication database name\r\n- ObjectName: The name of the replicated object (table, view, or stored procedure)\r\n- ObjectSchema: The schema that owns the replicated object\r\n- Status: \"Removed\" on successful removal, or an error message if the operation failed\r\n- IsRemoved: Boolean indicating whether the article was successfully removed (true) or failed (false)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaReplArticle -SqlInstance mssql1 -Database Pubs -Publication PubFromPosh -Name \u0027publishers\u0027\nRemoves the publishers article from a publication called PubFromPosh on mssql1\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaReplArticle -SqlInstance mssql1 -Database Pubs -Publication TestPub | Remove-DbaReplArticle\nRemoves all articles from a publication called TestPub on mssql1", "Description": "Removes articles from SQL Server replication publications, automatically handling subscription cleanup when subscribers exist. This function is essential when you need to stop replicating specific tables, views, or stored procedures without dismantling the entire publication.\n\nWhen articles have active subscriptions, the function first removes them from all subscribers using sp_dropsubscription before removing the article from the publication itself. This prevents orphaned subscription entries that could cause synchronization issues.\n\nImportant considerations: Dropping an article from a publication does not remove the actual object from the publication database or the corresponding object from the subscription database. Use DROP \u003cObject\u003e statements to remove these objects if necessary. Additionally, dropping an article invalidates the current snapshot, so a new snapshot must be created before the next synchronization cycle.", "Links": "https://dbatools.io/Remove-DbaReplArticle", "Synopsis": "Removes articles from SQL Server replication publications and their associated subscriptions.", "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 publication database on the publisher that contains the article to remove from replication.\r\nThis is the database where the source objects (tables, views, stored procedures) exist and are published for replication.", "", false, "false", "", "" ], [ "Publication", "Specifies the name of the replication publication from which to remove the article.\r\nUse Get-DbaReplPublication to list available publications if you\u0027re unsure of the exact name.", "", false, "false", "", "" ], [ "Schema", "Specifies the schema name of the replicated object to remove from the publication. Defaults to \u0027dbo\u0027.\r\nRequired when multiple schemas contain objects with the same name, ensuring you remove the correct article.", "", false, "false", "dbo", "" ], [ "Name", "Specifies the name of the article to remove from the publication.\r\nThis corresponds to the source object name (table, view, or stored procedure) that was added to replication.", "", false, "false", "", "" ], [ "InputObject", "Accepts replication article objects from Get-DbaReplArticle for pipeline operations.\r\nUse this to remove multiple articles efficiently: Get-DbaReplArticle | Remove-DbaReplArticle.", "", 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": [ "repl", "Replication" ], "CommandName": "Remove-DbaReplPublication", "Name": "Remove-DbaReplPublication", "Author": "Jess Pomfret (@jpomfret), jesspomfret.com", "Syntax": "Remove-DbaReplPublication [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString\u003e] [[-Name] \u003cString\u003e] [[-InputObject] \u003cPSObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per publication removed, containing details about the removal 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)\r\n- Database: The database name containing the publication\r\n- Name: The publication name that was removed\r\n- Type: The publication type (Transactional, Snapshot, or Merge)\r\n- Status: The result of the removal operation (\"Removed\" on success, or error message on failure)\r\n- IsRemoved: Boolean indicating whether the publication was successfully removed (True if successful, False if failed or not found)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaReplPublication -SqlInstance mssql1 -Database Northwind -Name PubFromPosh\nRemoves a publication called PubFromPosh from the Northwind database on mssql1", "Description": "Removes a publication from the database on the target SQL instances.\n\nhttps://learn.microsoft.com/en-us/sql/relational-databases/replication/publish/delete-a-publication?view=sql-server-ver16#RMOProcedure", "Links": "https://dbatools.io/Remove-DbaReplPublication", "Synopsis": "Removes a publication from the database on the target SQL 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", "", "" ], [ "Database", "Specifies the database containing the replication publication to remove. Required when using SqlInstance to identify which database\u0027s publications to target.\r\nUse this to scope the operation to a specific database when multiple databases have replication configured.", "", false, "false", "", "" ], [ "Name", "Specifies the exact name of the replication publication to remove. Required when using SqlInstance to identify which specific publication to target.\r\nUse this when you know the publication name and want to remove a specific publication rather than all publications in a database.", "", false, "false", "", "" ], [ "InputObject", "Accepts replication publication objects from Get-DbaReplPublication for pipeline operations. Use this when you want to filter publications first, then remove selected ones.\r\nParticularly useful when removing multiple publications based on specific criteria or when integrating with other replication management 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": [ "repl", "Replication" ], "CommandName": "Remove-DbaReplSubscription", "Name": "Remove-DbaReplSubscription", "Author": "Jess Pomfret (@jpomfret), jesspomfret.com", "Syntax": "Remove-DbaReplSubscription [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Database] \u003cString\u003e [-PublicationName] \u003cString\u003e [-SubscriberSqlInstance] \u003cDbaInstanceParameter\u003e [[-SubscriberSqlCredential] \u003cPSCredential\u003e] [-SubscriptionDatabase] \u003cString\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "None\nThis command does not return any objects to the pipeline. It performs the subscription removal operation and displays informational messages via Write-Message and Write-Warning.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$sub = @{\n\u003e\u003e SqlInstance = \u0027mssql1\u0027\r\n\u003e\u003e Database = \u0027pubs\u0027\r\n\u003e\u003e PublicationName = \u0027testPub\u0027\r\n\u003e\u003e SubscriberSqlInstance = \u0027mssql2\u0027\r\n\u003e\u003e SubscriptionDatabase = \u0027pubs\u0027\r\n\u003e\u003e }\r\nPS C:\\\u003e Remove-DbaReplSubscription @sub\nRemoves a subscription for the testPub publication on mssql2.pubs.", "Description": "Removes a subscription for the target SQL instances.\n\nhttps://learn.microsoft.com/en-us/sql/relational-databases/replication/delete-a-push-subscription?view=sql-server-ver16\nhttps://learn.microsoft.com/en-us/sql/relational-databases/replication/delete-a-pull-subscription?view=sql-server-ver16", "Links": "https://dbatools.io/Remove-DbaReplSubscription", "Synopsis": "Removes a subscription for the target SQL instances.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target publisher SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target publisher 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 publisher database that contains the replication publication.\r\nThis is the source database where the published data originates from.", "", true, "false", "", "" ], [ "PublicationName", "Specifies the exact name of the replication publication to remove the subscription from.\r\nMust match an existing publication name on the publisher database.", "", true, "false", "", "" ], [ "SubscriberSqlInstance", "Specifies the SQL Server instance that receives replicated data from the publisher.\r\nUse this to identify which subscriber instance should have its subscription removed.", "", true, "false", "", "" ], [ "SubscriberSqlCredential", "Login to the subscriber instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).\r\nRequired when the subscriber instance uses different authentication than the publisher.\r\nWindows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "SubscriptionDatabase", "Specifies the database on the subscriber instance that receives the replicated data.\r\nThis is the target database where the subscription will be removed from.", "", 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", "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": [ "ResourcePool", "ResourceGovernor" ], "CommandName": "Remove-DbaRgResourcePool", "Name": "Remove-DbaRgResourcePool", "Author": "John McCall (@lowlydba), lowlydba.com", "Syntax": "Remove-DbaRgResourcePool [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-ResourcePool] \u003cString[]\u003e] [[-Type] \u003cString\u003e] [-SkipReconfigure] [[-InputObject] \u003cObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "None\nThis command does not return any output objects. It only performs removal and reconfiguration operations on the Resource Governor.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaRgResourcePool -SqlInstance sql2016 -ResourcePool \"poolAdmin\" -Type Internal\nRemoves an internal resource pool named \"poolAdmin\" for the instance sql2016.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaRgResourcePool -SqlInstance sql2016 -Type \"Internal\" | Where-Object { $_.IsSystemObject -eq $false } | Remove-DbaRgResourcePool\nRemoves all user internal resource pools for the instance sql2016 by piping output from Get-DbaRgResourcePool.", "Description": "Removes user-defined resource pools from SQL Server\u0027s Resource Governor, freeing up the allocated memory, CPU, and IO resources for redistribution to other workloads. This is typically done when cleaning up unused resource pools, consolidating workload management, or reconfiguring resource allocation strategies.\n\nResource pools define the physical resource boundaries (memory, CPU, IO) that can be assigned to different database workloads through workload groups. Removing unused pools helps maintain a clean Resource Governor configuration and prevents resource fragmentation.\n\nThe function automatically reconfigures Resource Governor after pool removal to ensure changes take effect immediately, unless you specify -SkipReconfigure for batch operations.", "Links": "https://dbatools.io/Remove-DbaRgResourcePool", "Synopsis": "Removes internal or external resource pools from SQL Server Resource Governor configuration", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", false, "true (ByValue, ByPropertyName)", "", "" ], [ "SqlCredential", "Credential object used to connect to the Windows server as a different user", "", false, "true (ByPropertyName)", "", "" ], [ "ResourcePool", "Name of the resource pool to remove from Resource Governor configuration. Accepts multiple pool names.\r\nUse this when you need to clean up specific unused pools or consolidate resource management by removing obsolete pools.", "", false, "false", "", "" ], [ "Type", "Specifies whether to remove Internal or External resource pools. Defaults to Internal.\r\nInternal pools manage CPU and memory for regular SQL Server workloads, while External pools manage resources for R/Python/Java external scripts.", "", false, "false", "Internal", "Internal,External" ], [ "SkipReconfigure", "Skips the automatic Resource Governor reconfiguration after removing resource pools. By default, Resource Governor is reconfigured to apply changes immediately.\r\nUse this when removing multiple pools in batch operations to avoid repeated reconfigurations, then manually reconfigure once at the end.", "", false, "false", "False", "" ], [ "InputObject", "Accepts resource pool objects piped from Get-DbaRgResourcePool for removal. Supports both Internal and External resource pool objects.\r\nUse this for pipeline operations when you need to filter pools before removal or process multiple pools 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": [ "WorkloadGroup", "ResourceGovernor" ], "CommandName": "Remove-DbaRgWorkloadGroup", "Name": "Remove-DbaRgWorkloadGroup", "Author": "John McCall (@lowlydba), lowlydba.com", "Syntax": "Remove-DbaRgWorkloadGroup [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-WorkloadGroup] \u003cString[]\u003e] [[-ResourcePool] \u003cString\u003e] [[-ResourcePoolType] \u003cString\u003e] [-SkipReconfigure] [[-InputObject] \u003cWorkloadGroup[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per workload group removed, containing the following 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 (computer\\instance)\r\n- Name: The name of the workload group that was removed\r\n- Status: Status of the removal operation (\"Dropped\" on success, or error message on failure)\r\n- IsRemoved: Boolean indicating whether the workload group was successfully removed ($true or $false)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaRgResourcePool -SqlInstance sql2016 -WorkloadGroup \"groupAdmin\" -ResourcePool \"poolAdmin\" -ResourcePoolType Internal\nRemoves a workload group named \"groupAdmin\" in the \"poolAdmin\" resource pool for the instance sql2016\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaRgResourcePool -SqlInstance sql2016 -WorkloadGroup \"groupAdmin\"\nRemoves a workload group named \"groupAdmin\" in the default resource pool for the instance sql2016.", "Description": "Removes specified workload groups from SQL Server Resource Governor and automatically reconfigures the Resource Governor so changes take effect immediately.\nWorkload groups define resource allocation policies for incoming requests, and removing them eliminates those resource controls.\nUseful for cleaning up test environments, removing deprecated resource policies, or simplifying Resource Governor configurations during performance tuning.\nWorks with both internal and external resource pools, and can process multiple workload groups through pipeline input from Get-DbaRgWorkloadGroup.", "Links": "https://dbatools.io/Remove-DbaRgWorkloadGroup", "Synopsis": "Removes workload groups from SQL Server Resource Governor", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", false, "true (ByValue, ByPropertyName)", "", "" ], [ "SqlCredential", "Credential object used to connect to the Windows server as a different user.", "", false, "true (ByPropertyName)", "", "" ], [ "WorkloadGroup", "Specifies the name of the workload group(s) to remove from Resource Governor.\r\nUse this when you need to eliminate specific resource allocation policies or clean up deprecated workload configurations.", "", false, "false", "", "" ], [ "ResourcePool", "Specifies the resource pool containing the workload group to be removed. Defaults to \"default\" pool.\r\nRequired when workload groups exist in custom resource pools rather than the default SQL Server resource pool.", "", false, "false", "default", "" ], [ "ResourcePoolType", "Specifies whether to target Internal or External resource pools. Defaults to \"Internal\".\r\nUse \"External\" when removing workload groups that manage external script execution resources like R or Python jobs.", "", false, "false", "Internal", "Internal,External" ], [ "SkipReconfigure", "Skips the automatic Resource Governor reconfiguration that makes workload group changes take effect immediately.\r\nUse this when removing multiple workload groups in sequence to avoid repeated reconfigurations, but remember to manually reconfigure afterwards.", "", false, "false", "False", "" ], [ "InputObject", "Accepts workload group objects piped from Get-DbaRgWorkloadGroup for removal.\r\nUse this approach when you need to filter workload groups first or when processing multiple groups across different resource pools.", "", 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": [ "Role", "Login" ], "CommandName": "Remove-DbaServerRole", "Name": "Remove-DbaServerRole", "Author": "Claudio Silva (@ClaudioESSilva), claudioessilva.com", "Syntax": "Remove-DbaServerRole [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-ServerRole] \u003cString[]\u003e] [[-InputObject] \u003cServerRole[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per server role removed, with the following properties:\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- ServerRole: The name of the server role that was dropped\r\n- Status: The result of the removal operation (\"Success\" or \"Failed\")", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaServerRole -SqlInstance Server1 -ServerRole \u0027serverExecuter\u0027\nServer-role \u0027serverExecuter\u0027 on Server1 will be removed if it exists.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaServerRole -SqlInstance Server1 -ServerRole \u0027serverExecuter\u0027 -Confirm:$false\nSuppresses all prompts to remove the server-role \u0027serverExecuter\u0027 on \u0027Server1\u0027.", "Description": "Removes custom server-level roles that are no longer needed from SQL Server instances. This function helps clean up security configurations by permanently dropping user-defined server roles while preserving built-in system roles. Use this when decommissioning applications, consolidating permissions, or cleaning up after security audits. The operation requires confirmation due to its permanent nature and potential security impact.", "Links": "https://dbatools.io/Remove-DbaServerRole", "Synopsis": "Removes custom server-level roles 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", "", "" ], [ "ServerRole", "Specifies the name of the custom server-level role to remove from the SQL Server instance.\r\nOnly user-defined server roles can be removed - built-in roles like sysadmin or serveradmin are protected.\r\nUse this when you need to clean up obsolete custom roles after application decommissioning or security reviews.", "", false, "false", "", "" ], [ "InputObject", "Accepts server role objects from Get-DbaServerRole for pipeline operations.\r\nUse this when you need to remove multiple roles or want to filter roles before removal.\r\nAllows for more complex scenarios like removing all custom roles that match specific criteria.", "", 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": [ "Role", "Login" ], "CommandName": "Remove-DbaServerRoleMember", "Name": "Remove-DbaServerRoleMember", "Author": "Mikey Bronowski (@MikeyBronowski), bronowski.it", "Syntax": "Remove-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 produce any output. It performs role membership modifications via SMO methods ($ServerRole.DropMember() and $ServerRole.DropMembershipFromRole()) without returning objects to \r\nthe pipeline.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaServerRoleMember -SqlInstance server1 -ServerRole dbcreator -Login login1\nRemoves login1 from the dbcreator fixed server-level role on the instance server1.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaServerRoleMember -SqlInstance server1, sql2016 -ServerRole customrole -Login login1\nRemoves login1 from customrole custom server-level role on the instance server1 and sql2016.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRemove-DbaServerRoleMember -SqlInstance server1 -ServerRole customrole -Role dbcreator\nRemoves customrole custom server-level role from the dbcreator fixed server-level role.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$servers = Get-Content C:\\servers.txt\nPS C:\\\u003e $servers | Remove-DbaServerRoleMember -ServerRole sysadmin -Login login1\nRemoves login1 from the sysadmin fixed server-level role in every server in C:\\servers.txt.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eRemove-DbaServerRoleMember -SqlInstance localhost -ServerRole bulkadmin, dbcreator -Login login1\nRemoves login1 from the bulkadmin and dbcreator fixed server-level roles on the server localhost.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e$roles = Get-DbaServerRole -SqlInstance localhost -ServerRole bulkadmin, dbcreator\nPS C:\\\u003e $roles | Remove-DbaServerRoleMember -Login login1\nRemoves login1 from the bulkadmin and dbcreator fixed server-level roles on the server localhost.\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:\\ Remove-DbaServerRoleMember -Login $logins -ServerRole mycustomrole\nRemoves all the logins found in C:\\logins.txt from mycustomrole custom server-level role on server1.", "Description": "Revokes membership from server-level roles by removing logins or nested roles from target roles like sysadmin, dbcreator, or custom server roles. This is essential for security management when you need to reduce user privileges or clean up role assignments after organizational changes. The function works with both fixed server roles (sysadmin, securityadmin, etc.) and user-defined server roles, supporting bulk operations across multiple instances.", "Links": "https://dbatools.io/Remove-DbaServerRoleMember", "Synopsis": "Revokes server-level role membership from SQL Server logins and roles.", "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) from which to remove members. Accepts both fixed server roles like sysadmin, securityadmin, dbcreator, and custom user-defined server roles.\r\nUse this when you need to revoke specific permissions by removing logins or nested roles from elevated privilege roles.", "", false, "false", "", "" ], [ "Login", "Specifies the login name(s) to remove from the target server role(s). Accepts SQL Server logins, Windows logins, and Active Directory accounts.\r\nUse this when removing user access after role changes, departures, or security reviews where individual logins need privilege reduction.", "", false, "false", "", "" ], [ "Role", "Specifies the server role name(s) to remove from the target server role(s), enabling nested role management.\r\nUse this when restructuring role hierarchies or removing inherited permissions where one server role should no longer be a member of another.", "", false, "false", "", "" ], [ "InputObject", "Accepts piped server role objects from Get-DbaServerRole, allowing you to chain role discovery with member removal operations.\r\nUse this pattern when you need to filter roles first then remove specific members 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", "" ], [ "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": "SPN", "CommandName": "Remove-DbaSpn", "Name": "Remove-DbaSpn", "Author": "Drew Furgiuele (@pittfurg), port1433.com", "Syntax": "Remove-DbaSpn [-SPN] \u003cString\u003e [-ServiceAccount] \u003cString\u003e [[-Credential] \u003cPSCredential\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one or two objects per SPN removal operation, depending on what was removed:\nFirst object indicates the SPN removal result:\r\n- Name: The Service Principal Name that was processed\r\n- ServiceAccount: The Active Directory account from which the SPN was removed\r\n- Property: Always \"servicePrincipalName\" for the first object\r\n- IsSet: Boolean indicating whether the SPN is still set (true if removal failed, false if successful or not found)\r\n- Notes: Status message such as \"Successfully removed SPN\", \"SPN not found\", or \"Failed to remove SPN\"\nSecond object (if SPN removal succeeded) indicates the delegation cleanup result:\r\n- Name: The Service Principal Name that was processed\r\n- ServiceAccount: The Active Directory account from which delegation was removed\r\n- Property: Always \"msDS-AllowedToDelegateTo\" for the second object\r\n- IsSet: Boolean indicating whether the delegation entry is still set (true if removal failed, false if successful or not found)\r\n- Notes: Status message such as \"Successfully removed delegation\", \"Delegation not found\", or \"Failed to remove delegation\"", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaSpn -SPN MSSQLSvc\\SQLSERVERA.domain.something -ServiceAccount domain\\account\nConnects to Active Directory and removes a provided SPN from the given account (and also the relative delegation)\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaSpn -SPN MSSQLSvc\\SQLSERVERA.domain.something -ServiceAccount domain\\account -EnableException\nConnects to Active Directory and removes a provided SPN from the given account, suppressing all error messages and throw exceptions that can be caught instead\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRemove-DbaSpn -SPN MSSQLSvc\\SQLSERVERA.domain.something -ServiceAccount domain\\account -Credential ad\\sqldba\nConnects to Active Directory and removes a provided SPN to the given account. Uses alternative account to connect to AD.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eTest-DbaSpn -ComputerName sql2005 | Where-Object { $_.isSet -eq $true } | Remove-DbaSpn -WhatIf\nShows what would happen trying to remove all set SPNs for sql2005 and the relative delegations\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eTest-DbaSpn -ComputerName sql2005 | Where-Object { $_.isSet -eq $true } | Remove-DbaSpn\nRemoves all set SPNs for sql2005 and the relative delegations", "Description": "Connects to Active Directory to remove specified SPNs from SQL Server service accounts and automatically cleans up associated Kerberos delegation settings. This is essential when decommissioning SQL Server instances, changing service accounts, or troubleshooting Kerberos authentication issues where duplicate or incorrect SPNs exist. The function searches for the service account (user or computer), removes the SPN from the servicePrincipalName property, and also removes any corresponding delegation entries from msDS-AllowedToDelegateTo to maintain a clean AD environment.\n\nRequires write access to Active Directory through the provided credentials.", "Links": "https://dbatools.io/Remove-DbaSpn", "Synopsis": "Removes Service Principal Names from Active Directory service accounts and cleans up related Kerberos delegation", "Availability": "Windows, Linux, macOS", "Params": [ [ "SPN", "Specifies the exact Service Principal Name to remove from Active Directory. Must include the full SPN format like \u0027MSSQLSvc/servername:port\u0027 or \u0027MSSQLSvc/servername.domain.com\u0027.\r\nUse this when decommissioning SQL instances, changing service accounts, or cleaning up duplicate SPNs that cause Kerberos authentication failures.", "RequiredSPN", true, "true (ByPropertyName)", "", "" ], [ "ServiceAccount", "Specifies the Active Directory account (user or computer) that currently owns the SPN to be removed. Use domain\\username format for user accounts or COMPUTERNAME$ for computer accounts.\r\nThis should match the account currently running the SQL Server service that you\u0027re decommissioning or reconfiguring.", "InstanceServiceAccount,AccountName", true, "true (ByPropertyName)", "", "" ], [ "Credential", "The credential you want to use to connect to Active Directory to make the changes", "", false, "true (ByPropertyName)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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 was executed", "wi", false, "false", "", "" ], [ "Confirm", "Turns confirmations before changes on or off", "cf", false, "false", "", "" ] ] }, { "Tags": "Trace", "CommandName": "Remove-DbaTrace", "Name": "Remove-DbaTrace", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Remove-DbaTrace [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Id] \u003cInt32[]\u003e] [[-InputObject] \u003cObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per trace that was successfully removed.\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- Id: The trace ID that was removed (integer)\r\n- Status: Status message indicating \"Stopped, closed and deleted\"", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaTrace -SqlInstance sql2008\nStops and removes all traces on sql2008\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaTrace -SqlInstance sql2008 -Id 1\nStops and removes all trace with ID 1 on sql2008\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaTrace -SqlInstance sql2008 | Out-GridView -PassThru | Remove-DbaTrace\nStops and removes selected traces on sql2008", "Description": "Stops active SQL Server traces and permanently removes their definitions from the server using sp_trace_setstatus. This function helps clean up unnecessary traces that may be consuming server resources or disk space from previous troubleshooting sessions. The default trace is protected and cannot be removed - use Set-DbaSpConfigure to disable it instead. Traces are stopped first, then their definitions are deleted in a two-step process to ensure clean removal.", "Links": "https://dbatools.io/Remove-DbaTrace", "Synopsis": "Stops and removes SQL Server traces by ID or piped input from Get-DbaTrace.", "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", "", "" ], [ "Id", "Specifies the trace IDs to stop and remove from the SQL Server instance. Accepts one or more integer values.\r\nUse this when you know the specific trace IDs you want to remove, which you can obtain from Get-DbaTrace or SQL Server Profiler.", "", false, "false", "", "" ], [ "InputObject", "Accepts trace objects from Get-DbaTrace via the pipeline for removal operations.\r\nThis enables filtering traces with Get-DbaTrace before removing specific ones, such as removing only traces with certain characteristics.", "", 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": [ "ExtendedEvent", "XE", "XEvent" ], "CommandName": "Remove-DbaXESession", "Name": "Remove-DbaXESession", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Remove-DbaXESession [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] -Session \u003cObject[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nRemove-DbaXESession [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] -AllSessions [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nRemove-DbaXESession -InputObject \u003cSession[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per Extended Events session removed.\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- Session: The name of the Extended Events session that was removed\r\n- Status: String value \"Removed\" indicating the session was successfully dropped\nNo output is generated for sessions that fail to be removed due to errors.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRemove-DbaXESession -SqlInstance sql2012 -AllSessions\nRemoves all Extended Event Session on the sqlserver2014 instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRemove-DbaXESession -SqlInstance sql2012 -Session xesession1,xesession2\nRemoves the xesession1 and xesession2 Extended Event sessions.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaXESession -SqlInstance sql2017 | Remove-DbaXESession -Confirm:$false\nRemoves all sessions from sql2017, bypassing prompts.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaXESession -SqlInstance sql2012 -Session xesession1 | Remove-DbaXESession\nRemoves the sessions returned from the Get-DbaXESession function.", "Description": "Removes Extended Events sessions from SQL Server instances, giving you the option to target specific sessions by name or remove all user-created sessions at once. This function preserves critical system sessions (system_health, telemetry_xevents, and AlwaysOn_health) when using the AllSessions parameter, so you can safely clean up monitoring sessions without breaking SQL Server\u0027s built-in diagnostics. Useful for removing outdated monitoring configurations or cleaning up test sessions that are no longer needed.", "Links": "https://dbatools.io/Remove-DbaXESession", "Synopsis": "Removes Extended Events sessions 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 2008 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", "", "" ], [ "Session", "Specifies one or more Extended Events session names to remove from the target instance.\r\nUse this when you want to selectively remove specific monitoring sessions rather than all user sessions.\r\nAccepts session names as strings, with support for arrays to remove multiple sessions in one command.", "Name,Sessions", true, "false", "", "" ], [ "AllSessions", "Removes all user-created Extended Events sessions while preserving critical system sessions.\r\nUse this for cleanup operations when you want to clear all monitoring sessions without breaking SQL Server\u0027s built-in diagnostics.\r\nAutomatically excludes system_health, telemetry_xevents, and AlwaysOn_health sessions to maintain server functionality.", "", true, "false", "False", "" ], [ "InputObject", "Accepts Extended Events session objects directly from Get-DbaXESession for pipeline operations.\r\nUse this when you need to filter sessions with Get-DbaXESession first, then remove the filtered results.\r\nEnables complex filtering scenarios and integration with other dbatools XE functions.", "", 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", "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": [ "Database", "Rename" ], "CommandName": "Rename-DbaDatabase", "Name": "Rename-DbaDatabase", "Author": "Simone Bizzotto (@niphold)", "Syntax": "Rename-DbaDatabase -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-AllDatabases] [-DatabaseName \u003cString\u003e] [-FileGroupName \u003cString\u003e] [-LogicalName \u003cString\u003e] [-FileName \u003cString\u003e] [-ReplaceBefore] [-Force] [-Move] [-SetOffline] [-Preview] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nRename-DbaDatabase [-SqlCredential \u003cPSCredential\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-AllDatabases] [-DatabaseName \u003cString\u003e] [-FileGroupName \u003cString\u003e] [-LogicalName \u003cString\u003e] [-FileName \u003cString\u003e] [-ReplaceBefore] [-Force] [-Move] [-SetOffline] [-Preview] -InputObject \u003cDatabase[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database processed, containing detailed information about all renames performed.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The computer name of the SQL Server instance where the database resides\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL Server instance name (computer\\instance format)\r\n- Database: The Microsoft.SqlServer.Management.Smo.Database object representing the database\r\n- DBN: Hashtable containing database name renames (original name as key, new name as value)\r\n- FGN: Hashtable containing filegroup name renames (original name as key, new name as value)\r\n- LGN: Hashtable containing logical file name renames (original name as key, new name as value)\r\n- FNN: Hashtable containing physical file name renames (original path as key, new path as value)\r\n- PendingRenames: ArrayList of PSCustomObject items with Source and Destination properties for files that need to be moved on disk (empty if no file renames)\r\n- Status: String indicating completion status - \"FULL\" for complete success, \"PARTIAL\" if some operations were skipped or failed\nHidden display properties (accessible with Select-Object *):\r\n- DatabaseRenames: String with newline-separated list showing database rename transformations (e.g., \"OldDB --\u003e NewDB\")\r\n- FileGroupsRenames: String with newline-separated list showing filegroup rename transformations\r\n- LogicalNameRenames: String with newline-separated list showing logical file name transformations\r\n- FileNameRenames: String with newline-separated list showing physical file path transformations\nAll hashtable properties (DBN, FGN, LGN, FNN) are empty when no renames of that type occur. Hidden string properties show human-readable summaries of changes for troubleshooting.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -DatabaseName HR2 -Preview | Select-Object *\nShows the detailed result set you\u0027ll get renaming the HR database to HR2 without doing anything\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -DatabaseName HR2\nRenames the HR database to HR2\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sqlserver2014a -Database HR | Rename-DbaDatabase -DatabaseName HR2\nSame as before, but with a piped database (renames the HR database to HR2)\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eRename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -DatabaseName \"dbatools_\u003cDBN\u003e\"\nRenames the HR database to dbatools_HR\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eRename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -DatabaseName \"dbatools_\u003cDBN\u003e_\u003cDATE\u003e\"\nRenames the HR database to dbatools_HR_20170807 (if today is 07th Aug 2017)\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eRename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -FileGroupName \"dbatools_\u003cFGN\u003e\"\nRenames every FileGroup within HR to \"dbatools_[the original FileGroup name]\"\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eRename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -DatabaseName \"dbatools_\u003cDBN\u003e\" -FileGroupName \"\u003cDBN\u003e_\u003cFGN\u003e\"\nRenames the HR database to \"dbatools_HR\", then renames every FileGroup within to \"dbatools_HR_[the original FileGroup name]\"\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eRename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -FileGroupName \"dbatools_\u003cDBN\u003e_\u003cFGN\u003e\"\nPS C:\\\u003e Rename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -DatabaseName \"dbatools_\u003cDBN\u003e\"\nRenames the HR database to \"dbatools_HR\", then renames every FileGroup within to \"dbatools_HR_[the original FileGroup name]\"\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003eRename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -DatabaseName \"dbatools_\u003cDBN\u003e\" -FileName \"\u003cDBN\u003e_\u003cFGN\u003e_\u003cFNN\u003e\"\nRenames the HR database to \"dbatools_HR\" and then all filenames as \"dbatools_HR_[Name of the FileGroup]_[original_filename]\"\r\nThe db stays online (watch out!). You can then proceed manually to move/copy files by hand, set the db offline and then online again to finish the rename process\n-------------------------- EXAMPLE 10 --------------------------\nPS C:\\\u003eRename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -DatabaseName \"dbatools_\u003cDBN\u003e\" -FileName \"\u003cDBN\u003e_\u003cFGN\u003e_\u003cFNN\u003e\" -SetOffline\nRenames the HR database to \"dbatools_HR\" and then all filenames as \"dbatools_HR_[Name of the FileGroup]_[original_filename]\"\r\nThe db is then set offline (watch out!). You can then proceed manually to move/copy files by hand and then set it online again to finish the rename process\n-------------------------- EXAMPLE 11 --------------------------\nPS C:\\\u003eRename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -DatabaseName \"dbatools_\u003cDBN\u003e\" -FileName \"\u003cDBN\u003e_\u003cFGN\u003e_\u003cFNN\u003e\" -Move\nRenames the HR database to \"dbatools_HR\" and then all filenames as \"dbatools_HR_[Name of the FileGroup]_[original_filename]\"\r\nThe db is then set offline (watch out!). The function tries to do a simple rename and then sets the db online again to finish the rename process", "Description": "Systematically renames all database components using template-based naming conventions to enforce consistent standards across your SQL Server environment.\nThis function addresses the common challenge of standardizing database naming when inheriting inconsistent systems or implementing new naming policies.\n\nThe renaming process follows SQL Server\u0027s object hierarchy and executes in this order:\n- Database name is changed (optionally forcing users out)\n- Filegroup names are changed accordingly\n- Logical file names are changed accordingly\n- Physical file names are changed accordingly\n- If Move is specified, the database goes offline for file operations, then back online\n- If Move is not specified, the database remains online (unless SetOffline), and you handle file moves manually\n\nThe function uses powerful template placeholders like \u003cDBN\u003e for database name, \u003cFGN\u003e for filegroup name, \u003cDATE\u003e for current date, and \u003cFT\u003e for file type.\nWhen naming conflicts occur, automatic counters are appended to ensure uniqueness.\nIf any step fails, the entire process stops to prevent partial renames that could leave your database in an inconsistent state.\n\nAlways backup your databases before using this function, and take a full backup of master after completion.\nThe function returns detailed objects showing all completed renames, with hidden properties providing human-readable summaries.\n\nStore results in a variable for troubleshooting: \"$result = Rename-DbaDatabase .....\"\nUse the -Preview parameter first to see exactly what changes would occur: \"Rename-DbaDatabase .... -Preview | Select-Object *\"", "Links": "https://dbatools.io/Rename-DbaDatabase", "Synopsis": "Renames database names, filegroups, logical files, and physical files using customizable templates with placeholder support.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "Target any number of instances, in order to return their build state.", "", 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 renaming operation. Accepts database names, wildcards, or arrays of database names.\r\nUse this when you need to rename specific databases instead of all user databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies databases to exclude from the renaming operation. Accepts database names, wildcards, or arrays of database names.\r\nUse this to protect specific databases when using -AllDatabases or when you want to process most databases except certain ones.", "", false, "false", "", "" ], [ "AllDatabases", "Applies the renaming operation to all user databases on the SQL Server instance. System databases are automatically excluded.\r\nUse this switch when standardizing naming conventions across your entire instance rather than targeting specific databases.", "", false, "false", "False", "" ], [ "DatabaseName", "Specifies a template for renaming database names using placeholder substitution. Creates new database names based on the template pattern.\r\nUse this when you need to standardize database names according to organizational naming conventions. Common patterns include adding prefixes, suffixes, or date stamps.\r\nValid placeholders are: \u003cDBN\u003e (current database name), \u003cDATE\u003e (current date in yyyyMMdd format).", "", false, "false", "", "" ], [ "FileGroupName", "Specifies a template for renaming filegroup names within databases using placeholder substitution. Note that the PRIMARY filegroup cannot be renamed due to SQL Server restrictions.\r\nUse this when you need consistent filegroup naming across databases or when implementing data organization strategies that require specific filegroup names.\r\nValid placeholders are: \u003cFGN\u003e (current filegroup name), \u003cDBN\u003e (current database name), \u003cDATE\u003e (current date in yyyyMMdd format). If distinct names cannot be generated, a counter is appended (0001, \r\n0002, etc).", "", false, "false", "", "" ], [ "LogicalName", "Specifies a template for renaming the logical names of database files using placeholder substitution. Logical names are used internally by SQL Server to reference files.\r\nUse this when you need consistent logical file naming for backup operations, maintenance scripts, or troubleshooting, as logical names are referenced in many SQL commands.\r\nValid placeholders are: \u003cFT\u003e (file type: ROWS, LOG, MMO, FS), \u003cLGN\u003e (current logical name), \u003cFGN\u003e (current filegroup name), \u003cDBN\u003e (current database name), \u003cDATE\u003e (current date in yyyyMMdd format). If \r\ndistinct names cannot be generated, a counter is appended (0001, 0002, etc).", "", false, "false", "", "" ], [ "FileName", "Specifies a template for renaming physical database file names on disk using placeholder substitution. Changes only the file name, preserving the original directory and file extension.\r\nUse this when you need to align physical file names with your database naming standards for easier file management, monitoring, and disaster recovery operations.\r\nValid placeholders are: \u003cFNN\u003e (current file name without directory or extension), \u003cFT\u003e (file type: ROWS, LOG, MMO, FS), \u003cLGN\u003e (current logical name), \u003cFGN\u003e (current filegroup name), \u003cDBN\u003e (current \r\ndatabase name), \u003cDATE\u003e (current date in yyyyMMdd format). If distinct names cannot be generated, a counter is appended (0001, 0002, etc).", "", false, "false", "", "" ], [ "ReplaceBefore", "Modifies how placeholder substitution works by removing old database, filegroup, and logical names from current names before applying templates. This prevents duplicate naming components in nested \r\nscenarios.\r\nUse this when your existing names already contain components that would be duplicated by the template placeholders, resulting in cleaner final names.\r\nFor example, with -ReplaceBefore, renaming database \"HR_DB\" to \"PROD_HR\" and using template \"\u003cDBN\u003e_Data\" results in \"PROD_HR_Data\" instead of \"PROD_HR_HR_DB_Data\".", "", false, "false", "False", "" ], [ "Force", "Terminates all active connections to target databases to allow renaming operations to proceed. Required when databases have active connections that would prevent rename operations.\r\nUse this when you need to force database renames in production environments where applications may maintain persistent connections.", "", false, "false", "False", "" ], [ "Move", "Automatically moves physical database files to match renamed file names. Sets the database offline, performs file operations, then brings the database back online.\r\nUse this for a complete automated renaming solution when you want the function to handle all file operations. Requires PowerShell remoting access to the SQL Server\u0027s file system.", "", false, "false", "False", "" ], [ "SetOffline", "Forces the database offline after renaming operations to prepare for manual file moves. Terminates active connections and sets database state to offline.\r\nUse this when you need to rename physical files but want to handle the file movement operations manually rather than having the function move them automatically.", "", false, "false", "False", "" ], [ "Preview", "Displays what renaming operations would be performed without executing any changes to the databases. Shows the complete rename plan including all affected components.\r\nUse this first to verify your templates and parameters will produce the desired results before committing to actual database changes.", "", false, "false", "False", "" ], [ "InputObject", "Accepts database objects from the pipeline, typically from Get-DbaDatabase. Allows for advanced filtering and database selection before renaming.\r\nUse this when you need complex database selection logic or when chaining database operations in a pipeline.", "", 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", "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": "Login", "CommandName": "Rename-DbaLogin", "Name": "Rename-DbaLogin", "Author": "Mitchell Hamann (@SirCaptainMitch)", "Syntax": "Rename-DbaLogin [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Login] \u003cString\u003e [-NewLogin] \u003cString\u003e [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per operation performed (login rename and/or user renames). Each object includes the following properties:\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 being renamed (null for login-level rename operations)\r\n- PreviousLogin: The original login name (populated for login rename, null for user renames)\r\n- NewLogin: The new login name (populated for login rename, null for user renames)\r\n- PreviousUser: The original database user name (null for login rename, populated for user renames)\r\n- NewUser: The new database user name (null for login rename, populated for successful user renames)\r\n- Status: Result of the operation (Successful, Failure, or \"Failure to rename. Rolled back change.\" when rollback occurs)\nWhen -Force is not specified, only one object is returned representing the login rename operation.\nWhen -Force is specified, multiple objects are returned - one for the login rename operation and one per database user that was successfully renamed. If any user rename fails, the login is rolled \r\nback and a rollback status is returned.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRename-DbaLogin -SqlInstance localhost -Login DbaToolsUser -NewLogin captain\nSQL Login Example\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRename-DbaLogin -SqlInstance localhost -Login domain\\oldname -NewLogin domain\\newname\nChange the windowsuser login name.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRename-DbaLogin -SqlInstance localhost -Login dbatoolsuser -NewLogin captain -WhatIf\nWhatIf Example", "Description": "Renames SQL Server logins at the instance level, solving the common problem of needing to update login names after migrations, domain changes, or when improving naming conventions.\n\nWhen migrating logins between environments or standardizing naming conventions, manually updating login names and all their database user mappings is time-consuming and error-prone. This function handles both the login rename and optionally updates all associated database users in a single operation.\n\nBy default, only the server-level login is renamed. Use the -Force parameter to also rename the corresponding database users across all databases where the login is mapped. If any database user rename fails, the function automatically rolls back the login name change to maintain consistency.", "Links": "https://dbatools.io/Rename-DbaLogin", "Synopsis": "Renames SQL Server logins and optionally their associated database users", "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.", "", 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", "", "" ], [ "Login", "Specifies the existing login name that you want to rename on the SQL Server instance.\r\nThis must be an exact match for a login that currently exists on the server.", "", true, "false", "", "" ], [ "NewLogin", "Specifies the new name for the login after the rename operation.\r\nFor Windows logins, the new name must resolve to the same SID as the original login to maintain security mappings.", "", true, "false", "", "" ], [ "Force", "Renames corresponding database users across all databases where the login is mapped.\r\nWithout this parameter, only the server-level login is renamed, leaving database users unchanged. If any database user rename fails, the entire operation rolls back to maintain consistency.", "", 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 to confirm actions", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Mirroring", "Mirror", "HA" ], "CommandName": "Repair-DbaDbMirror", "Name": "Repair-DbaDbMirror", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Repair-DbaDbMirror [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Database\nReturns the repaired database object for each database where mirroring was successfully resumed. One object is returned per database processed.\nAll properties from the SMO Database object are available, including:\r\n- Name: Database name\r\n- Owner: Database owner login\r\n- CreateDate: DateTime when the database was created\r\n- LastBackupDate: DateTime of the most recent full backup\r\n- LastDifferentialBackupDate: DateTime of the most recent differential backup\r\n- LastLogBackupDate: DateTime of the most recent transaction log backup\r\n- RecoveryModel: The recovery model (Simple, Full, BulkLogged)\r\n- Status: Current database status (Normal, Restoring, RecoveryPending, Suspect, etc.)\r\n- MirroringStatus: State of database mirroring (Disabled, Suspended, Synchronizing, Synchronized, Disconnected)\r\n- Size: Total size of the database in megabytes\r\n- SpaceAvailable: Available space in the database in megabytes\r\n- Tables: Collection of tables in the database\r\n- Views: Collection of views in the database\r\n- StoredProcedures: Collection of stored procedures in the database", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRepair-DbaDbMirror -SqlInstance sql2017 -Database pubs\nAttempts to repair the mirrored but suspended pubs database on sql2017.\r\nRestarts the endpoints then sets the partner to resume. Prompts for confirmation.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2017 -Database pubs | Repair-DbaDbMirror -Confirm:$false\nAttempts to repair the mirrored but suspended pubs database on sql2017.\r\nRestarts the endpoints then sets the partner to resume. Does not prompt for confirmation.", "Description": "Restores database mirroring functionality when mirroring sessions become suspended due to network connectivity issues, log space problems, or other transient failures. This function performs the standard troubleshooting steps that DBAs typically execute manually: stops and restarts the database mirroring endpoints on the SQL Server instance, then resumes the mirroring session between the principal and mirror databases.\n\nWhen database mirroring is suspended, the mirror database stops receiving transaction log records from the principal database, creating a potential data loss risk. This command automates the common recovery process, eliminating the need to manually restart endpoints and issue ALTER DATABASE commands to resume mirroring.", "Links": "https://dbatools.io/Repair-DbaDbMirror", "Synopsis": "Repairs suspended database mirroring sessions by restarting endpoints and resuming mirroring", "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 name of the mirrored database that needs repair on the SQL Server instance.\r\nUse this when you know the specific database with suspended mirroring that requires endpoint restart and session resumption.\r\nAccepts multiple database names and supports wildcards for pattern matching.", "", false, "false", "", "" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase pipeline input to repair multiple mirrored databases in a single operation.\r\nUse this approach when you need to repair several databases at once or when working with the output of database filtering commands.\r\nEach database object must represent a database that has mirroring configured.", "", 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": "Orphan", "CommandName": "Repair-DbaDbOrphanUser", "Name": "Repair-DbaDbOrphanUser", "Author": "Claudio Silva (@ClaudioESSilva) | Simone Bizzotto (@niphlod)", "Syntax": "Repair-DbaDbOrphanUser [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-Users] \u003cObject[]\u003e] [-RemoveNotExisting] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per orphaned user found, regardless of whether it was successfully repaired or not. The output indicates the repair status for each user encountered.\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- DatabaseName: The name of the database where the orphaned user exists\r\n- User: The name of the orphaned database user\r\n- Status: The outcome of the repair attempt. Values are:\r\n - \"Success\": User was successfully remapped to their matching server login\r\n - \"No matching login\": No matching server login was found for the user (returned only when -RemoveNotExisting is not specified)\nWhen -RemoveNotExisting is specified, users without matching logins are passed to Remove-DbaDbOrphanUser instead of being returned in the output.\nNo output is returned if no orphaned users are found in the specified database(s).", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRepair-DbaDbOrphanUser -SqlInstance sql2005\nFinds and repairs all orphan users of all databases present on server \u0027sql2005\u0027\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRepair-DbaDbOrphanUser -SqlInstance sqlserver2014a -SqlCredential $cred\nFinds and repair all orphan users in all databases present on server \u0027sqlserver2014a\u0027. SQL credentials are used to authenticate to the server.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRepair-DbaDbOrphanUser -SqlInstance sqlserver2014a -Database db1, db2\nFinds and repairs all orphan users in both db1 and db2 databases.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eRepair-DbaDbOrphanUser -SqlInstance sqlserver2014a -Database db1 -Users OrphanUser\nFinds and repairs user \u0027OrphanUser\u0027 in \u0027db1\u0027 database.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eRepair-DbaDbOrphanUser -SqlInstance sqlserver2014a -Users OrphanUser\nFinds and repairs user \u0027OrphanUser\u0027 on all databases\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eRepair-DbaDbOrphanUser -SqlInstance sqlserver2014a -RemoveNotExisting\nFinds all orphan users of all databases present on server \u0027sqlserver2014a\u0027. Removes all users that do not have matching Logins.", "Description": "Identifies and repairs orphaned database users - users that exist in a database but are no longer associated with a server login. This commonly occurs after database restores, migrations, or when logins are recreated.\n\nThe function searches each database for users where the Login property is empty, then attempts to remap them to existing server logins with matching names. For a login to be eligible for remapping, it must be enabled, not a system object, not locked, and have the exact same name as the orphaned user.\n\nUses modern ALTER USER syntax for SQL Server 2005+ or the legacy sp_change_users_login procedure for SQL Server 2000. Optionally removes orphaned users that have no matching server login when -RemoveNotExisting is specified.", "Links": "https://dbatools.io/Repair-DbaDbOrphanUser", "Synopsis": "Repairs orphaned database users by remapping them to matching server logins or optionally removing them.", "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 orphaned users. Accepts wildcards for pattern matching and multiple database names.\r\nUse this when you only need to repair orphaned users in specific databases rather than scanning all databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies databases to skip when scanning for orphaned users. Useful for avoiding system databases or databases under maintenance.\r\nCommonly used to exclude tempdb, distribution databases, or databases where orphaned users should remain untouched.", "", false, "false", "", "" ], [ "Users", "Specifies specific database users to repair rather than processing all orphaned users found.\r\nUse this when you need to target specific problematic users or when working with large databases where selective repair is preferred.", "", false, "true (ByValue)", "", "" ], [ "RemoveNotExisting", "Removes orphaned database users that have no corresponding server login instead of just reporting them.\r\nUse this after database migrations or when cleaning up databases where some users should no longer exist. Exercise caution as this permanently removes users.", "", false, "false", "False", "" ], [ "Force", "Bypasses confirmation prompts and forces schema ownership changes to dbo when removing orphaned users.\r\nRequired when orphaned users own database schemas that prevent their removal. Use with caution as it can affect database object ownership.", "", 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": [ "SPN", "Instance", "Utility" ], "CommandName": "Repair-DbaInstanceName", "Name": "Repair-DbaInstanceName", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Repair-DbaInstanceName [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-AutoFix] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object when the server name is successfully updated. The object contains instance identification and rename confirmation details from the Test-DbaInstanceName command.\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- ServerName: The configured server name after the rename operation\r\n- NewServerName: The expected server name based on hostname and instance name\r\n- RenameRequired: Boolean indicating whether a rename was needed (should be false after successful rename)\r\n- Updatable: Boolean indicating if the instance could be renamed (true when rename completed)\r\n- Warnings: Warning message about SQL Server Reporting Services needing update if found, or \"N/A\" if not applicable\r\n- Blockers: Array of reasons that prevented rename before fix, or \"N/A\" if no blockers existed\nNo output is returned if the operation is skipped (instance already has correct name, clustered environment, or rename cancelled).", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRepair-DbaInstanceName -SqlInstance sql2014\nChecks to see if the server name is updatable and changes the name with a number of prompts.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRepair-DbaInstanceName -SqlInstance sql2014 -AutoFix\nChecks to see if the server name is updatable and automatically performs the change. Replication or mirroring will be broken if necessary.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRepair-DbaInstanceName -SqlInstance sql2014 -AutoFix -Force\nChecks to see if the server name is updatable and automatically performs the change, bypassing most prompts and confirmations. Replication or mirroring will be broken if necessary.", "Description": "Updates SQL Server\u0027s @@SERVERNAME system variable to match the current Windows hostname, which is required after renaming a Windows server. This ensures proper functionality for Kerberos authentication and Availability Groups.\n\nThe function automatically detects the correct new server name and uses sp_dropserver and sp_addserver to update the SQL Server system tables. It handles common blockers like active replication and database mirroring, optionally removing them with the -AutoFix parameter.\n\nA SQL Server service restart is required to complete the rename process, which the function can perform automatically. The function will skip the operation if the names already match.\n\nhttps://www.mssqltips.com/sqlservertip/2525/steps-to-change-the-server-name-for-a-sql-server-machine/", "Links": "https://dbatools.io/Repair-DbaInstanceName", "Synopsis": "Updates SQL Server\u0027s @@SERVERNAME system variable to match the Windows hostname", "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", "", "" ], [ "AutoFix", "Automatically resolves blockers that prevent the server name repair, including removing replication distribution and disabling database mirroring.\r\nUse this when you need to fix the server name without manual intervention to remove these blocking configurations.\r\nThis parameter will prompt for confirmation before breaking replication or mirroring unless combined with -Force.", "", false, "false", "False", "" ], [ "Force", "Bypasses confirmation prompts for potentially destructive operations like stopping SQL services and breaking replication or mirroring.\r\nUse this for unattended automation or when you\u0027re certain about proceeding with all changes.\r\nCombine with -AutoFix for fully automated server name repairs without any prompts.", "", 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", "Instance", "Utility" ], "CommandName": "Reset-DbaAdmin", "Name": "Reset-DbaAdmin", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Reset-DbaAdmin [-SqlInstance] \u003cDbaInstanceParameter\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Login] \u003cString\u003e] [[-SecurePassword] \u003cSecureString\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Dataplat.Dbatools.Login\nReturns one login object representing the account that was reset or created. The object contains login properties and credentials information for the account that now has sysadmin privileges on the \r\nSQL Server instance.\nProperties include:\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 format)\r\n- Name: The login name (either SQL or Windows authentication account)\r\n- LoginType: The type of login (SqlLogin or WindowsUser)\r\n- CreateDate: The date/time the login was created\r\n- LastLogin: The date/time of the most recent login (if available)\r\n- IsDisabled: Boolean indicating if the login is disabled\r\n- IsLocked: Boolean indicating if the login is locked out\r\n- IsSysAdmin: Boolean indicating if the login has sysadmin privileges (should be True after successful reset)\nIf an error occurs during the reset process and the function cannot reconnect to verify the login, no output is returned.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eReset-DbaAdmin -SqlInstance sqlcluster -SqlCredential sqladmin\nPrompts for password, then resets the \"sqladmin\" account password on sqlcluster.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eReset-DbaAdmin -SqlInstance sqlserver\\sqlexpress -Login ad\\administrator -Confirm:$false\nAdds the domain account \"ad\\administrator\" as a sysadmin to the SQL instance.\nIf the account already exists, it will be added to the sysadmin role.\nDoes not prompt for a password since it is not a SQL login. Does not prompt for confirmation since -Confirm is set to $false.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eReset-DbaAdmin -SqlInstance sqlserver\\sqlexpress -Login sqladmin -Force\nSkips restart confirmation, prompts for password, then adds a SQL Login \"sqladmin\" with sysadmin privileges.\r\nIf the account already exists, it will be added to the sysadmin role and the password will be reset.", "Description": "Recovers access to SQL Server instances when you\u0027re locked out due to forgotten passwords, disabled accounts, or authentication issues. This emergency recovery tool stops the SQL Server service and restarts it in single-user mode, allowing exclusive access to reset credentials and restore administrative privileges.\n\nThe function handles both standalone and clustered SQL Server instances, working with SQL authentication logins (like sa) and Windows authentication accounts. It automatically enables mixed mode authentication when working with SQL logins and ensures the target login is enabled, unlocked, and granted sysadmin privileges.\n\nThis is accomplished by stopping the SQL services or SQL Clustered Resource Group, then restarting SQL via the command-line using the /mReset-DbaAdmin parameter which starts the server in Single-User mode and only allows this script to connect.\n\nOnce the service is restarted, the following tasks are performed:\n- Login is added if it doesn\u0027t exist\n- If login is a Windows User, an attempt is made to ensure it exists\n- If login is a SQL Login, password policy will be set to OFF when creating the login, and SQL Server authentication will be set to Mixed Mode\n- Login will be enabled and unlocked\n- Login will be added to sysadmin role\n\nIf failures occur at any point, a best attempt is made to restart the SQL Server normally. The function uses Microsoft.Data.SqlClient and Get-WmiObject for maximum compatibility across different environments without requiring additional tools.\n\nFor remote SQL Server instances, ensure WinRM is configured and accessible. If remote access isn\u0027t possible, run the script locally on the target server. Requires Windows administrator access to the server hosting SQL Server.\n\nSupports SQL Server 2005 and above on clustered and standalone configurations.", "Links": "https://dbatools.io/Reset-DbaAdmin", "Synopsis": "Regains administrative access to SQL Server instances when passwords or access has been lost", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. SQL Server must be 2005 and above, and can be a clustered or stand-alone instance.", "", true, "false", "", "" ], [ "SqlCredential", "Instead of using Login and SecurePassword, you can just pass in a credential object.", "", false, "false", "", "" ], [ "Login", "Specifies the login account to reset or create with sysadmin privileges. Defaults to \"sa\" if not specified.\r\nUse this when you need to regain access through a specific account rather than the default sa login. Accepts both SQL authentication logins (like \"sqladmin\") and Windows authentication accounts (like \r\n\"DOMAIN\\User\" or \"DOMAIN\\Group\").\r\nIf the login doesn\u0027t exist, it will be created automatically. For Windows logins on remote servers, use domain accounts that the SQL Server can validate, not local machine accounts.", "", false, "false", "sa", "" ], [ "SecurePassword", "Provides the password for SQL authentication logins as a SecureString to avoid interactive prompts.\r\nUse this when automating the reset process or when you don\u0027t want to be prompted to enter the password manually. Only required for SQL logins, not Windows authentication accounts.\r\nThe password will be applied during login creation or when resetting an existing SQL login\u0027s password.", "", false, "false", "", "" ], [ "Force", "Bypasses all confirmation prompts and proceeds with the service restart and login reset operations.\r\nUse this when you need to automate the recovery process or when you\u0027re certain about proceeding without manual confirmation. This includes the high-impact confirmation for stopping and restarting SQL \r\nServer services.\r\nDoes not actually drop and recreate logins - the existing description appears to be incorrect for this function.", "", 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": "Module", "CommandName": "Reset-DbatoolsConfig", "Name": "Reset-DbatoolsConfig", "Author": "Friedrich Weinmann (@FredWeinmann)", "Syntax": "Reset-DbatoolsConfig [-ConfigurationItem \u003cConfig[]\u003e] [-FullName \u003cString[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nReset-DbatoolsConfig -Module \u003cString\u003e [-Name \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "None\nThis command does not return any objects to the pipeline. It performs configuration resets as a side effect. Use -WhatIf to preview what settings would be reset without making changes.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eReset-DbatoolsConfig -Module MyModule\nResets all configuration items of the MyModule to default.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbatoolsConfig | Reset-DbatoolsConfig\nResets ALL configuration items to default.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eReset-DbatoolsConfig -FullName MyModule.Group.Setting1\nResets the configuration item named \u0027MyModule.Group.Setting1\u0027.", "Description": "Restores dbatools configuration settings to their original default values, useful when troubleshooting connectivity issues, fixing misconfigured connection strings, or starting fresh after environment changes. This is particularly helpful when dbatools settings have been customized for specific environments and you need to restore the baseline behavior.\n\nThe function can reset individual configuration items, all settings within a specific module, or all dbatools configuration settings at once. This saves you from manually tracking down and reconfiguring individual settings.\n\nIn order for a reset to be possible, two conditions must be met:\n- The setting must have been initialized.\n- The setting cannot have been enforced by policy.", "Links": "https://dbatools.io/Reset-DbatoolsConfig", "Synopsis": "Resets dbatools module configuration settings back to their default values.", "Availability": "Windows, Linux, macOS", "Params": [ [ "ConfigurationItem", "One or more configuration objects as returned by Get-DbatoolsConfig.\r\nUse this when you want to reset specific configuration items that you\u0027ve already identified through Get-DbatoolsConfig, allowing for precise control over which settings get reset.", "", false, "true (ByValue)", "", "" ], [ "FullName", "The full qualified name of a specific configuration setting to reset (e.g., \u0027dbatools.Connection.EncryptConnection\u0027).\r\nUse this when you know the exact setting name and want to reset just that one item, providing the most precise targeting of configuration changes.", "", false, "true (ByValue)", "", "" ], [ "Module", "The name of the module whose configuration settings should be reset (e.g., \u0027dbatools\u0027, \u0027sql\u0027, \u0027connection\u0027).\r\nUse this when you want to reset all settings within a specific functional area, such as resetting all connection-related settings after environment changes.", "", true, "false", "", "" ], [ "Name", "A wildcard pattern to match configuration setting names within the specified module (defaults to \"*\" for all settings).\r\nUse this with the -Module parameter to selectively reset settings, such as using \"Encrypt*\" to reset only encryption-related settings within a module.", "", 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": [ "Network", "Connection", "Resolve" ], "CommandName": "Resolve-DbaNetworkName", "Name": "Resolve-DbaNetworkName", "Author": "Klaas Vandenberghe (@PowerDBAKlaas) | Simone Bizzotto (@niphold)", "Syntax": "Resolve-DbaNetworkName [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-Turbo] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one network information object per input computer name. Each object contains comprehensive network resolution details with the following properties:\n- InputName (string): The original input value as provided by the user (computer name, IP address, or instance name)\r\n- ComputerName (string): The hostname only, in uppercase (e.g., \"SERVER01\")\r\n- IPAddress (string): The IP address that responded to connectivity tests, either IPv4 or IPv6\r\n- DNSHostname (string): The hostname portion from DNS resolution (lowercase), coming from DNS as reported by the local system\r\n- DNSDomain (string): The domain suffix from DNS resolution, as reported by the local system\u0027s DNS configuration\r\n- Domain (string): The domain name from Active Directory, representing the domain the computer is joined to\r\n- DNSHostEntry (string): The fully qualified domain name as returned by [System.Net.Dns]::GetHostEntry()\r\n- FQDN (string): Legacy notation combining ComputerName and Domain with a dot separator (e.g., \"SERVER01.CONTOSO.COM\")\r\n- FullComputerName (string): The full computer name as configured within the operating system, matching the DNSHostName property in Active Directory\nWhen -Turbo is specified, the same object structure is returned but with results based on DNS resolution only, without connecting to the target computer or performing ICMP ping tests. This provides \r\nfaster results but may be less accurate in disjoint-domain environments.\nNote: FullComputerName is the most reliable property across all network configurations as it matches between AD and DNS in both standard and disjoint-domain environments.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eResolve-DbaNetworkName -ComputerName sql2014\nReturns a custom object displaying InputName, ComputerName, IPAddress, DNSHostName, DNSDomain, Domain, DNSHostEntry, FQDN, DNSHostEntry for sql2014\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eResolve-DbaNetworkName -ComputerName sql2016, sql2014\nReturns a custom object displaying InputName, ComputerName, IPAddress, DNSHostName, DNSDomain, Domain, DNSHostEntry, FQDN, DNSHostEntry for sql2016 and sql2014\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaRegServer -SqlInstance sql2014 | Resolve-DbaNetworkName\nReturns a custom object displaying InputName, ComputerName, IPAddress, DNSHostName, DNSDomain, Domain, DNSHostEntry, FQDN, DNSHostEntry for all SQL Servers returned by Get-DbaRegServer\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaRegServer -SqlInstance sql2014, sql2016\\sqlexpress | Resolve-DbaNetworkName\nReturns a custom object displaying InputName, ComputerName, IPAddress, DNSHostName, DNSDomain, Domain, DNSHostEntry, FQDN, DNSHostEntry for all SQL Servers returned by Get-DbaRegServer", "Description": "Performs comprehensive network name resolution to gather detailed connection information for SQL Server instances and computers.\nThis function is essential when you need to verify connectivity, troubleshoot connection issues, or validate network configurations before connecting to SQL Server.\n\nUses multiple resolution methods including DNS lookups, ICMP ping tests, and WMI/CIM queries to ensure accurate results across different network configurations.\nFirst tests connectivity using ICMP to identify the responding IP address, then gathers comprehensive network details through various protocols.\n\nImportant: Remember that FQDN doesn\u0027t always match \"ComputerName dot Domain\" as AD intends.\nThere are network setup (google \"disjoint domain\") where AD and DNS do not match.\n\"Full computer name\" (as reported by sysdm.cpl) is the only match between the two,\nand it matches the \"DNSHostName\" property of the computer object stored in AD.\nThis means that the notation of FQDN that matches \"ComputerName dot Domain\" is incorrect\nin those scenarios.\nIn other words, the \"suffix\" of the FQDN CAN be different from the AD Domain.\n\nThis cmdlet has been providing good results since its inception but for lack of useful\nnames some doubts may arise.\nLet this clear the doubts:\n- InputName: whatever has been passed in\n- ComputerName: hostname only\n- IPAddress: IP Address\n- DNSHostName: hostname only, coming strictly from DNS (as reported from the calling computer)\n- DNSDomain: domain only, coming strictly from DNS (as reported from the calling computer)\n- Domain: domain only, coming strictly from AD (i.e. the domain the ComputerName is joined to)\n- DNSHostEntry: Fully name as returned by DNS [System.Net.Dns]::GetHostEntry\n- FQDN: \"legacy\" notation of ComputerName \"dot\" Domain (coming from AD)\n- FullComputerName: Full name as configured from within the Computer (i.e. the only secure match between AD and DNS)\n\nSo, if you need to use something, go with FullComputerName, always, as it is the most correct in every scenario.", "Links": "https://dbatools.io/Resolve-DbaNetworkName", "Synopsis": "Resolves network names and returns detailed network information for SQL Server connection troubleshooting and validation.", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the target computer name, IP address, or SQL Server instance to resolve network information for.\r\nUse this when troubleshooting connectivity issues or validating network configurations before connecting to SQL Server.\r\nAccepts computer names (SERVER01), IP addresses (192.168.1.100), SQL Server instances (SERVER01\\INSTANCE), or SMO objects from Get-DbaRegServer.", "", 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", "", "" ], [ "Turbo", "Enables DNS-only resolution mode for faster network name resolution without connecting to the target computer.\r\nUse this when you need quick DNS lookups but don\u0027t require comprehensive network details or WMI/CIM information.\r\nResults may be less accurate in disjoint-domain environments where AD and DNS configurations don\u0027t align, and may vary depending on your local DNS configuration.", "FastParrot", 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": [ "Path", "Resolve", "Utility" ], "CommandName": "Resolve-DbaPath", "Name": "Resolve-DbaPath", "Author": "Friedrich Weinmann (@FredWeinmann)", "Syntax": "Resolve-DbaPath [-Path] \u003cString[]\u003e [[-Provider] \u003cString\u003e] [-SingleItem] [-NewChild] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.String\nReturns one or more resolved file system paths as strings. Each input path that resolves successfully is output as a separate string value.\r\nWhen processing multiple paths via pipeline or array, each path is returned individually to the pipeline, enabling pipeline chaining with other commands like Copy-Item or Remove-Item.\nThe returned paths are fully qualified file system paths in the format expected by PowerShell cmdlets and .NET APIs.\r\nWhen using -NewChild, returns the constructed path for the new file even if it does not yet exist, but the parent directory must be accessible.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eResolve-DbaPath -Path report.log -Provider FileSystem -NewChild -SingleItem\nEnsures the resolved path is a FileSystem path.\r\nThis will resolve to the current folder and the file report.log.\r\nWill not ensure the file exists or doesn\u0027t exist.\r\nIf the current path is in a different provider, it will throw an exception.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eResolve-DbaPath -Path ..\\*\nThis will resolve all items in the parent folder, whatever the current path or drive might be.", "Description": "Validates and resolves file system paths with additional safety checks beyond PowerShell\u0027s built-in Resolve-Path cmdlet. This function ensures paths exist and are accessible before performing database operations like backups, restores, or log file management. It provides enhanced error handling, provider validation (FileSystem, Registry, etc.), and supports both existing paths and parent directories for new file creation. DBAs can use this to validate backup destinations, database file locations, and script paths before running maintenance operations, preventing failures due to invalid or inaccessible paths.", "Links": "https://dbatools.io/Resolve-DbaPath", "Synopsis": "Validates and resolves file system paths with enhanced error handling and provider verification.", "Availability": "Windows, Linux, macOS", "Params": [ [ "Path", "Specifies the file system path to validate and resolve, supporting both absolute and relative paths.\r\nUse this to verify backup destinations, database file locations, or script paths before database operations.\r\nAccepts wildcards for pattern matching and can validate multiple paths when passed as an array.", "", true, "true (ByValue)", "", "" ], [ "Provider", "Validates that the resolved path belongs to the specified PowerShell provider type.\r\nUse \u0027FileSystem\u0027 to ensure database backup paths or data file locations are on disk storage, not registry or other providers.\r\nPrevents accidental operations on wrong provider types like \u0027Registry\u0027, \u0027Certificate\u0027, or \u0027ActiveDirectory\u0027.", "", false, "false", "", "" ], [ "SingleItem", "Requires the path to resolve to exactly one location, preventing wildcard expansion.\r\nUse when specifying a unique backup file destination or single database file path where multiple matches would cause errors.\r\nWill throw an error if wildcards or patterns resolve to multiple paths.", "", false, "false", "False", "" ], [ "NewChild", "Validates the parent directory exists for creating new files, without requiring the target file to exist.\r\nUse when specifying backup file destinations, new database file paths, or log file locations that will be created.\r\nThe parent folder must be accessible, but the final filename can be new.", "", false, "false", "False", "" ] ] }, { "Tags": [ "Service", "Instance", "Restart" ], "CommandName": "Restart-DbaService", "Name": "Restart-DbaService", "Author": "Kirill Kravtsov (@nvarscar)", "Syntax": "Restart-DbaService [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [-InstanceName \u003cString[]\u003e] [-SqlInstance \u003cDbaInstanceParameter[]\u003e] [-Type \u003cString[]\u003e] [-Timeout \u003cInt32\u003e] [-Credential \u003cPSCredential\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nRestart-DbaService [-InstanceName \u003cString[]\u003e] [-Type \u003cString[]\u003e] -InputObject \u003cObject[]\u003e [-Timeout \u003cInt32\u003e] [-Credential \u003cPSCredential\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per service that was processed with the following properties:\r\n- ComputerName: The name of the computer where the service is running\r\n- InstanceName: The SQL Server instance name the service belongs to\r\n- ServiceName: The Windows service name (MSSQLSERVER, MSSQL$NAMED, SQLSERVERAGENT, etc.)\r\n- ServiceType: The type of service (Engine, Agent, Browser, FullText, SSAS, SSIS, SSRS, PolyBase, Launchpad)\r\n- Status: The result of the restart operation (Successful, Failed, or other status values)\nServices that failed to stop are returned before services that successfully restarted. This allows you to identify which services encountered issues during the restart process.\nIf -Force is specified with Engine services, dependent services (Agent, PolyBase, Launchpad) are automatically included and restarted as part of the operation.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRestart-DbaService -ComputerName sqlserver2014a\nRestarts the SQL Server related services on computer sqlserver2014a.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027sql1\u0027,\u0027sql2\u0027,\u0027sql3\u0027| Get-DbaService | Restart-DbaService\nGets the SQL Server related services on computers sql1, sql2 and sql3 and restarts them.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eRestart-DbaService -ComputerName sql1,sql2 -InstanceName MSSQLSERVER\nRestarts the SQL Server services related to the default instance MSSQLSERVER on computers sql1 and sql2.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eRestart-DbaService -ComputerName $MyServers -Type SSRS\nRestarts the SQL Server related services of type \"SSRS\" (Reporting Services) on computers in the variable MyServers.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eRestart-DbaService -ComputerName sql1 -Type Engine -Force\nRestarts SQL Server database engine services on sql1 forcing dependent SQL Server Agent services to restart as well.", "Description": "Restarts SQL Server services across multiple computers while automatically managing service dependencies and restart order. This function performs a controlled stop-then-restart sequence, ensuring that dependent services like SQL Agent are properly handled when restarting the Database Engine. You can target specific service types (Engine, Agent, SSRS, SSAS, etc.) or restart all SQL Server services on a system, making it ideal for maintenance windows or applying configuration changes that require service restarts.\n\nRequires Local Admin rights on destination computer(s).", "Links": "https://dbatools.io/Restart-DbaService", "Synopsis": "Restarts SQL Server services with proper dependency handling and service ordering.", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the computer names where SQL Server services will be restarted. Accepts multiple computer names for batch operations.\r\nUse this when you need to restart services across multiple SQL Server hosts during maintenance windows or after configuration changes.", "cn,host,Server", false, "false", "$env:COMPUTERNAME", "" ], [ "InstanceName", "Restricts the restart operation to services belonging to specific SQL Server instances (like MSSQLSERVER, SQLEXPRESS, or named instances).\r\nUse this when you have multiple instances on a server but only need to restart services for specific instances, avoiding unnecessary downtime for other instances.", "Instance", false, "false", "", "" ], [ "SqlInstance", "Use a combination of computername and instancename to get the SQL Server related services for specific instances on specific computers.\nParameters ComputerName and InstanceName will be ignored if SqlInstance is used.", "", false, "false", "", "" ], [ "Type", "Specifies which SQL Server service types to restart: Agent, Browser, Engine, FullText, SSAS, SSIS, SSRS, PolyBase, or Launchpad.\r\nUse this when you need to restart only specific services rather than all SQL Server services, such as restarting just SQL Agent after job configuration changes or only SSRS after report deployment.", "", false, "false", "", "Agent,Browser,Engine,FullText,SSAS,SSIS,SSRS,PolyBase,Launchpad" ], [ "InputObject", "Accepts service objects from Get-DbaService to restart specific services that have already been filtered or identified.\r\nUse this when you need to restart a predefined set of services, typically by piping results from Get-DbaService with custom filtering or from previously saved service collections.", "ServiceCollection", true, "true (ByValue)", "", "" ], [ "Timeout", "Sets the maximum time in seconds to wait for each service stop/start operation to complete before timing out. Defaults to 60 seconds.\r\nIncrease this value for busy systems or when restarting services with large databases that may take longer to shut down gracefully. Set to 0 for infinite wait.", "", false, "false", "60", "" ], [ "Credential", "Credential object used to connect to the computer as a different user.", "", false, "false", "", "" ], [ "Force", "Automatically includes dependent services (SQL Agent, PolyBase, Launchpad) when restarting Database Engine services to ensure proper shutdown sequence.\r\nUse this when restarting Engine services to avoid dependency conflicts and ensure all related services restart cleanly, particularly important during major configuration changes or patches.", "", 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 cmdlet runs. The cmdlet is not run.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before running the cmdlet.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "DisasterRecovery", "Backup", "Restore" ], "CommandName": "Restore-DbaDatabase", "Name": "Restore-DbaDatabase", "Author": "Stuart Moore (@napalmgram), stuart-moore.com", "Syntax": "Restore-DbaDatabase -SqlInstance \u003cDbaInstanceParameter\u003e [-SqlCredential \u003cPSCredential\u003e] -Path \u003cObject[]\u003e [-DatabaseName \u003cObject[]\u003e] [-DestinationDataDirectory \u003cString\u003e] [-DestinationLogDirectory \u003cString\u003e] [-DestinationFileStreamDirectory \u003cString\u003e] [-RestoreTime \u003cDateTime\u003e] [-NoRecovery] [-WithReplace] [-KeepReplication] [-XpDirTree] [-NoXpDirRecurse] [-OutputScriptOnly] [-VerifyOnly] [-MaintenanceSolutionBackup] [-FileMapping \u003cHashtable\u003e] [-IgnoreLogBackup] [-IgnoreDiffBackup] [-UseDestinationDefaultDirectories] [-ReuseSourceFolderStructure] [-DestinationFilePrefix \u003cString\u003e] \r\n[-RestoredDatabaseNamePrefix \u003cString\u003e] [-TrustDbBackupHistory] [-MaxTransferSize \u003cInt32\u003e] [-BlockSize \u003cInt32\u003e] [-BufferCount \u003cInt32\u003e] [-DirectoryRecurse] [-EnableException] [-StandbyDirectory \u003cString\u003e] [-Continue] [-ExecuteAs \u003cString\u003e] [-StorageCredential \u003cString\u003e] [-ReplaceDbNameInFile] [-DestinationFileSuffix \u003cString\u003e] [-KeepCDC] [-GetBackupInformation \u003cString\u003e] [-StopAfterGetBackupInformation] [-SelectBackupInformation \u003cString\u003e] [-StopAfterSelectBackupInformation] [-FormatBackupInformation \u003cString\u003e] [-StopAfterFormatBackupInformation] [-TestBackupInformation \u003cString\u003e] \r\n[-StopAfterTestBackupInformation] [-StopBefore] [-StopMark \u003cString\u003e] [-StopAfterDate \u003cDateTime\u003e] [-StatementTimeout \u003cInt32\u003e] [-Checksum] [-Restart] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nRestore-DbaDatabase -SqlInstance \u003cDbaInstanceParameter\u003e [-SqlCredential \u003cPSCredential\u003e] -Path \u003cObject[]\u003e [-DatabaseName \u003cObject[]\u003e] [-OutputScriptOnly] [-TrustDbBackupHistory] [-MaxTransferSize \u003cInt32\u003e] [-BlockSize \u003cInt32\u003e] [-BufferCount \u003cInt32\u003e] [-EnableException] [-StorageCredential \u003cString\u003e] [-GetBackupInformation \u003cString\u003e] [-StopAfterGetBackupInformation] [-SelectBackupInformation \u003cString\u003e] [-StopAfterSelectBackupInformation] [-FormatBackupInformation \u003cString\u003e] [-StopAfterFormatBackupInformation] [-TestBackupInformation \u003cString\u003e] [-StopAfterTestBackupInformation] -PageRestore \u003cObject\u003e \r\n-PageRestoreTailFolder \u003cString\u003e [-StopBefore] [-StopMark \u003cString\u003e] [-StopAfterDate \u003cDateTime\u003e] [-StatementTimeout \u003cInt32\u003e] [-Checksum] [-Restart] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nRestore-DbaDatabase -SqlInstance \u003cDbaInstanceParameter\u003e [-SqlCredential \u003cPSCredential\u003e] [-DatabaseName \u003cObject[]\u003e] [-OutputScriptOnly] [-EnableException] [-StorageCredential \u003cString\u003e] [-Recover] [-GetBackupInformation \u003cString\u003e] [-StopAfterGetBackupInformation] [-SelectBackupInformation \u003cString\u003e] [-StopAfterSelectBackupInformation] [-FormatBackupInformation \u003cString\u003e] [-StopAfterFormatBackupInformation] [-TestBackupInformation \u003cString\u003e] [-StopAfterTestBackupInformation] [-StopBefore] [-StopMark \u003cString\u003e] [-StopAfterDate \u003cDateTime\u003e] [-StatementTimeout \u003cInt32\u003e] [-WhatIf] [-Confirm] \r\n[\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.String (when -OutputScriptOnly is specified)\nReturns the T-SQL RESTORE statements as strings without executing them. This allows the scripts to be reviewed, modified, or executed later.\nPSCustomObject (for -Recover parameter set only)\nWhen using the -Recover parameter to bring databases online, returns one object per database recovered with the following properties:\r\n- SqlInstance: The target SQL Server instance\r\n- DatabaseName: The name of the database that was recovered\r\n- RestoreComplete: Boolean indicating if recovery succeeded\r\n- Scripts: The T-SQL RESTORE statement that was executed\nNo direct output (for standard restore operations)\nWhen performing standard restore operations (without OutputScriptOnly or Recover), the function delegates to Invoke-DbaAdvancedRestore which handles database restoration. The function may also create \r\nglobal variables if any of the following parameters are specified:\r\n- GetBackupInformation: Creates global variable containing backup information\r\n- SelectBackupInformation: Creates global variable containing selected backup history\r\n- FormatBackupInformation: Creates global variable containing formatted backup information\r\n- TestBackupInformation: Creates global variable containing tested backup information\nUse these variables to inspect the backup chain analysis, file mappings, and restore validation results without executing the restore operation.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRestore-DbaDatabase -SqlInstance server1\\instance1 -Path \\\\server2\\backups\nScans all the backup files in \\\\server2\\backups, filters them and restores the database to server1\\instance1\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRestore-DbaDatabase -SqlInstance server1\\instance1 -Path \\\\server2\\backups -MaintenanceSolutionBackup -DestinationDataDirectory c:\\restores\nScans all the backup files in \\\\server2\\backups$ stored in an Ola Hallengren style folder structure,\r\nfilters them and restores the database to the c:\\restores folder on server1\\instance1\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-ChildItem c:\\SQLbackups1\\, \\\\server\\sqlbackups2 | Restore-DbaDatabase -SqlInstance server1\\instance1\nTakes the provided files from multiple directories and restores them on server1\\instance1\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$RestoreTime = Get-Date(\u002711:19 23/12/2016\u0027)\nPS C:\\\u003e Restore-DbaDatabase -SqlInstance server1\\instance1 -Path \\\\server2\\backups -MaintenanceSolutionBackup -DestinationDataDirectory c:\\restores -RestoreTime $RestoreTime\nScans all the backup files in \\\\server2\\backups stored in an Ola Hallengren style folder structure,\r\nfilters them and restores the database to the c:\\restores folder on server1\\instance1 up to 11:19 23/12/2016\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$result = Restore-DbaDatabase -SqlInstance server1\\instance1 -Path \\\\server2\\backups -DestinationDataDirectory c:\\restores -OutputScriptOnly\nPS C:\\\u003e $result | Out-File -Filepath c:\\scripts\\restore.sql\nScans all the backup files in \\\\server2\\backups, filters them and generate the T-SQL Scripts to restore the database to the latest point in time, and then stores the output in a file for later \r\nretrieval\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eRestore-DbaDatabase -SqlInstance server1\\instance1 -Path c:\\backups -DestinationDataDirectory c:\\DataFiles -DestinationLogDirectory c:\\LogFile\nScans all the files in c:\\backups and then restores them onto the SQL Server Instance server1\\instance1, placing data files\r\nc:\\DataFiles and all the log files into c:\\LogFiles\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eRestore-DbaDatabase -SqlInstance server1\\instance1 -Path http://demo.blob.core.windows.net/backups/dbbackup.bak -StorageCredential MyAzureCredential\nWill restore the backup held at http://demo.blob.core.windows.net/backups/dbbackup.bak to server1\\instance1. The connection to Azure will be made using the\r\ncredential MyAzureCredential held on instance Server1\\instance1\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eRestore-DbaDatabase -SqlInstance server1\\instance1 -Path http://demo.blob.core.windows.net/backups/dbbackup.bak\nWill attempt to restore the backups from http://demo.blob.core.windows.net/backups/dbbackup.bak if a SAS credential with the name http://demo.blob.core.windows.net/backups exists on server1\\instance1\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003eRestore-DbaDatabase -SqlInstance sql2022 -Path s3://s3.us-west-2.amazonaws.com/mybucket/backups/dbbackup.bak -StorageCredential MyS3Credential\nWill restore the backup from S3-compatible storage to sql2022. Requires SQL Server 2022 or higher. The credential must be configured with Identity = \u0027S3 Access Key\u0027 and Secret containing the access \r\nkey and secret key.\n-------------------------- EXAMPLE 10 --------------------------\nPS C:\\\u003e$File = Get-ChildItem c:\\backups, \\\\server1\\backups\nPS C:\\\u003e $File | Restore-DbaDatabase -SqlInstance Server1\\Instance -UseDestinationDefaultDirectories\nThis will take all of the files found under the folders c:\\backups and \\\\server1\\backups, and pipeline them into\r\nRestore-DbaDatabase. Restore-DbaDatabase will then scan all of the files, and restore all of the databases included\r\nto the latest point in time covered by their backups. All data and log files will be moved to the default SQL Server\r\nfolder for those file types as defined on the target instance.\n-------------------------- EXAMPLE 11 --------------------------\nPS C:\\\u003e$files = Get-ChildItem C:\\dbatools\\db1\nPS C:\\\u003e $params = @{\r\n\u003e\u003e SqlInstance = \u0027server\\instance1\u0027\r\n\u003e\u003e DestinationFilePrefix = \u0027prefix\u0027\r\n\u003e\u003e DatabaseName =\u0027Restored\u0027\r\n\u003e\u003e RestoreTime = (get-date \"14:58:30 22/05/2017\")\r\n\u003e\u003e NoRecovery = $true\r\n\u003e\u003e WithReplace = $true\r\n\u003e\u003e StandbyDirectory = \u0027C:\\dbatools\\standby\u0027\r\n\u003e\u003e }\r\n\u003e\u003e\r\nPS C:\\\u003e $files | Restore-DbaDatabase @params\r\nPS C:\\\u003e Invoke-DbaQuery -SQLInstance server\\instance1 -Query \"select top 1 * from Restored.dbo.steps order by dt desc\"\r\nPS C:\\\u003e $params.RestoreTime = (get-date \"15:09:30 22/05/2017\")\r\nPS C:\\\u003e $params.NoRecovery = $false\r\nPS C:\\\u003e $params.Add(\"Continue\",$true)\r\nPS C:\\\u003e $files | Restore-DbaDatabase @params\r\nPS C:\\\u003e Invoke-DbaQuery -SQLInstance server\\instance1 -Query \"select top 1 * from Restored.dbo.steps order by dt desc\"\r\nPS C:\\\u003e Restore-DbaDatabase -SqlInstance server\\instance1 -DestinationFilePrefix prefix -DatabaseName Restored -Continue -WithReplace\nIn this example we step through the backup files held in c:\\dbatools\\db1 folder.\r\nFirst we restore the database to a point in time in standby mode. This means we can check some details in the databases\r\nWe then roll it on a further 9 minutes to perform some more checks\r\nAnd finally we continue by rolling it all the way forward to the latest point in the backup.\r\nAt each step, only the log files needed to roll the database forward are restored.\n-------------------------- EXAMPLE 12 --------------------------\nPS C:\\\u003eRestore-DbaDatabase -SqlInstance server\\instance1 -Path c:\\backups -DatabaseName example1 -NoRecovery\nPS C:\\\u003e Restore-DbaDatabase -SqlInstance server\\instance1 -Recover -DatabaseName example1\nIn this example we restore example1 database with no recovery, and then the second call is to set the database to recovery.\n-------------------------- EXAMPLE 13 --------------------------\nPS C:\\\u003e$SuspectPage = Get-DbaSuspectPage -SqlInstance server\\instance1 -Database ProdFinance\nPS C:\\\u003e Get-DbaDbBackupHistory -SqlInstance server\\instance1 -Database ProdFinance -Last | Restore-DbaDatabase -PageRestore $SuspectPage -PageRestoreTailFolder c:\\temp -TrustDbBackupHistory\nGets a list of Suspect Pages using Get-DbaSuspectPage. Then uses Get-DbaDbBackupHistory and Restore-DbaDatabase to perform a restore of the suspect pages and bring them up to date\r\nIf server\\instance1 is Enterprise edition this will be done online, if not it will be performed offline\n-------------------------- EXAMPLE 14 --------------------------\nPS C:\\\u003e$BackupHistory = Get-DbaBackupInformation -SqlInstance sql2005 -Path \\\\backups\\sql2000\\ProdDb\nPS C:\\\u003e $BackupHistory | Restore-DbaDatabase -SqlInstance sql2000 -TrustDbBackupHistory\nDue to SQL Server 2000 not returning all the backup headers we cannot restore directly. As this is an issues with the SQL engine all we can offer is the following workaround\r\nThis will use a SQL Server instance \u003e 2000 to read the headers, and then pass them in to Restore-DbaDatabase as a BackupHistory object.\n-------------------------- EXAMPLE 15 --------------------------\nPS C:\\\u003eRestore-DbaDatabase -SqlInstance server1\\instance1 -Path \"C:\\Temp\\devops_prod_full.bak\" -DatabaseName \"DevOps_DEV\" -ReplaceDbNameInFile\nPS C:\\\u003e Rename-DbaDatabase -SqlInstance server1\\instance1 -Database \"DevOps_DEV\" -LogicalName \"\u003cDBN\u003e_\u003cFT\u003e\"\nThis will restore the database from the \"C:\\Temp\\devops_prod_full.bak\" file, with the new name \"DevOps_DEV\" and store the different physical files with the new name. It will use the system default \r\nconfigured data and log locations.\r\nAfter the restore the logical names of the database files will be renamed with the \"DevOps_DEV_ROWS\" for MDF/NDF and \"DevOps_DEV_LOG\" for LDF\n-------------------------- EXAMPLE 16 --------------------------\nPS C:\\\u003e$FileStructure = @{\n\u003e\u003e \u0027database_data\u0027 = \u0027C:\\Data\\database_data.mdf\u0027\r\n\u003e\u003e \u0027database_log\u0027 = \u0027C:\\Log\\database_log.ldf\u0027\r\n\u003e\u003e }\r\n\u003e\u003e\r\nPS C:\\\u003e Restore-DbaDatabase -SqlInstance server1 -Path \\\\ServerName\\ShareName\\File -DatabaseName database -FileMapping $FileStructure\nRestores \u0027database\u0027 to \u0027server1\u0027 and moves the files to new locations. The format for the $FileStructure HashTable is the file logical name as the Key, and the new location as the Value.\n-------------------------- EXAMPLE 17 --------------------------\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\n-------------------------- EXAMPLE 18 --------------------------\nPS C:\\\u003eRestore-DbaDatabase -SqlInstance server1 -Path \\\\ServerName\\ShareName\\File -DatabaseName database -StopMark OvernightStart -StopBefore -StopAfterDate Get-Date(\u002721:00 10/05/2020\u0027)\nRestores the backups from \\\\ServerName\\ShareName\\File as database, stops before the first \u0027OvernightStart\u0027 mark that occurs after \u002721:00 10/05/2020\u0027.\nNote that Date time needs to be specified in your local SQL Server culture", "Description": "Scans backup files and automatically selects the optimal restore sequence to recover databases to a specific point in time.\nThis function handles the complex task of building complete backup chains from full, differential, and transaction log backups,\nso you don\u0027t have to manually determine which files are needed or in what order to restore them.\n\nThe function excels at disaster recovery scenarios where you need to quickly restore from a collection of backup files.\nIt validates backup headers, ensures restore chains are complete, and can recover to any point in time within your backup coverage.\nWhether restoring from local files, network shares, or Azure blob storage, it automatically handles file discovery and validation.\n\nBy default, all file paths must be accessible to the target SQL Server instance. The function uses xp_dirtree for remote file scanning\nand supports various input methods including direct file lists, folder scanning, and pipeline input from other dbatools commands.\nIt integrates seamlessly with Ola Hallengren\u0027s maintenance solution backup structures for faster processing.", "Links": "https://dbatools.io/Restore-DbaDatabase", "Synopsis": "Restores SQL Server databases from backup files with intelligent backup chain selection and point-in-time recovery.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance.", "", 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 location of backup files to restore from, supporting local drives, UNC paths, or Azure blob storage URLs.\r\nUse this when you need to restore from a specific backup location or when piping backup files from Get-ChildItem.\r\nAccepts multiple comma-separated paths for complex restore scenarios spanning multiple locations.", "", true, "true (ByValue)", "", "" ], [ "DatabaseName", "Defines the target database name for the restored database when different from the original name.\r\nUse this when creating a copy of a production database for testing or when restoring to avoid name conflicts.\r\nRequired when restoring a single database to a different name than what\u0027s stored in the backup files.", "Name", false, "true (ByValue)", "", "" ], [ "DestinationDataDirectory", "Sets the target directory path where data files (.mdf, .ndf) will be restored on the destination instance.\r\nUse this when you need to restore to a different drive or storage location than the original database.\r\nWhen specified alone, log files will also be placed here unless DestinationLogDirectory is provided.", "", false, "false", "", "" ], [ "DestinationLogDirectory", "Defines the target directory for transaction log files (.ldf) separate from data files.\r\nUse this to follow best practices by placing log files on different drives for performance and disaster recovery.\r\nMust be used together with DestinationDataDirectory for proper file separation.", "", false, "false", "", "" ], [ "DestinationFileStreamDirectory", "Specifies where FILESTREAM data containers will be restored, separate from regular database files.\r\nUse this when your database contains FILESTREAM data and you need to place it on specific storage.\r\nRequires DestinationDataDirectory to be specified and the target instance to have FILESTREAM enabled.", "", false, "false", "", "" ], [ "RestoreTime", "Sets the point-in-time recovery target for restoring the database to a specific moment.\r\nUse this for recovering from logical errors, unwanted changes, or data corruption that occurred at a known time.\r\nRequires a complete backup chain including transaction logs covering the specified time period.", "", false, "false", "(Get-Date).AddYears(1)", "" ], [ "NoRecovery", "Leaves the database in a restoring state to allow additional transaction log restores or log shipping setup.\r\nUse this when you need to apply additional log backups, set up availability groups, or prepare for continuous log shipping.\r\nThe database will remain inaccessible until recovered with the RESTORE WITH RECOVERY statement.", "", false, "false", "False", "" ], [ "WithReplace", "Allows overwriting an existing database with the same name during the restore operation.\r\nUse this when you need to refresh a test environment or replace a corrupted database with a backup.\r\nEssential for disaster recovery scenarios where you\u0027re restoring over a damaged database.", "", false, "false", "False", "" ], [ "KeepReplication", "Maintains replication settings and objects when restoring databases involved in replication topologies.\r\nUse this when restoring publisher or subscriber databases where you need to preserve replication configuration.\r\nEssential for disaster recovery scenarios involving replicated databases to avoid reconfiguring publications and subscriptions.", "", false, "false", "False", "" ], [ "XpDirTree", "Forces backup file discovery to use SQL Server\u0027s xp_dirtree instead of PowerShell file system access.\r\nUse this when backup files are on network shares that PowerShell cannot access but SQL Server can.\r\nRequires sysadmin privileges and may be needed for environments with strict network security policies.", "", false, "false", "False", "" ], [ "NoXpDirRecurse", "If specified, prevents the XpDirTree process from recursing (its default behaviour).", "", false, "false", "False", "" ], [ "OutputScriptOnly", "Generates the T-SQL RESTORE statements without executing them, allowing for script review or manual execution.\r\nUse this to validate restore commands, create deployment scripts, or when you need approval before running restores.\r\nHelpful for compliance environments where all database changes must be reviewed before execution.", "", false, "false", "False", "" ], [ "VerifyOnly", "Validates backup files and restore paths without performing the actual restore operation.\r\nUse this to test backup file integrity, verify backup chains are complete, and confirm restore feasibility.\r\nEssential for disaster recovery planning and backup validation routines without impacting production systems.", "", false, "false", "False", "" ], [ "MaintenanceSolutionBackup", "Optimizes backup file scanning for Ola Hallengren\u0027s Maintenance Solution folder structure.\r\nUse this when your backups follow the standard Ola Hallengren folder layout with separate FULL, DIFF, and LOG subdirectories.\r\nSignificantly improves performance by using predictable file locations rather than reading every backup header.", "", false, "false", "False", "" ], [ "FileMapping", "Provides precise control over where individual database files are restored using logical file names.\r\nUse this when you need granular file placement, such as putting specific filegroups on different drives for performance.\r\nCreate a hashtable mapping logical names to physical paths: @{\u0027DataFile1\u0027=\u0027C:\\Data\\File1.mdf\u0027; \u0027LogFile1\u0027=\u0027D:\\Logs\\File1.ldf\u0027}", "", false, "true (ByPropertyName)", "", "" ], [ "IgnoreLogBackup", "Excludes transaction log backups from the restore operation, stopping at the latest full or differential backup.\r\nUse this when you only need to restore to a recent backup checkpoint rather than the latest point in time.\r\nUseful for creating a baseline copy of a database without applying the most recent transactions.", "", false, "false", "False", "" ], [ "IgnoreDiffBackup", "Skips differential backups and restores using only full backups plus transaction logs.\r\nUse this when differential backups are corrupted or when you need to restore using a specific full backup as the baseline.\r\nResults in longer restore times as all transaction log backups since the full backup must be applied.", "", false, "false", "False", "" ], [ "UseDestinationDefaultDirectories", "Places restored database files in the SQL Server instance\u0027s default data and log directories.\r\nUse this when you want to follow the target instance\u0027s standard file location configuration.\r\nThe function will attempt to create directories if they don\u0027t exist, ensuring consistent file placement.", "", false, "false", "False", "" ], [ "ReuseSourceFolderStructure", "Maintains the original database file directory structure from the source server during restore.\r\nUse this when migrating between servers that share similar drive layouts or when preserving application-specific paths.\r\nConsider version differences in SQL Server default paths (MSSQL12, MSSQL13, etc.) when restoring between versions.", "", false, "false", "False", "" ], [ "DestinationFilePrefix", "This value will be prefixed to ALL restored files (log and data). This is just a simple string prefix.\r\nIf you want to perform more complex rename operations then please use the FileMapping parameter.\r\nThis will apply to all file move options, except for FileMapping.", "", false, "false", "", "" ], [ "RestoredDatabaseNamePrefix", "A string which will be prefixed to the start of the restore Database\u0027s Name.\r\nUseful if restoring a copy to the same sql server for testing.", "", false, "false", "", "" ], [ "TrustDbBackupHistory", "Bypasses backup header validation when using piped input from Get-DbaDbBackupHistory or similar commands.\r\nUse this to significantly speed up restores when you\u0027re confident in the backup chain integrity.\r\nTrades verification safety for performance - backup file issues won\u0027t be detected until the restore attempt.", "", false, "false", "False", "" ], [ "MaxTransferSize", "Controls the size of each data transfer between storage and SQL Server during restore operations.\r\nUse this to optimize restore performance based on your storage subsystem characteristics.\r\nMust be a multiple of 64KB with higher values potentially improving performance on high-speed storage.", "", false, "false", "0", "" ], [ "BlockSize", "Defines the physical block size used for backup file reading during restore operations.\r\nUse this to match the block size used during backup creation for optimal performance.\r\nValid values: 0.5KB, 1KB, 2KB, 4KB, 8KB, 16KB, 32KB, or 64KB, with larger blocks typically faster on modern storage.", "", false, "false", "0", "" ], [ "BufferCount", "Sets the number of I/O buffers SQL Server uses for the restore operation to improve throughput.\r\nUse this to optimize restore performance by allowing more parallel I/O operations.\r\nHigher values can improve performance but consume more memory - typically set between 2-64 based on available RAM.", "", false, "false", "0", "" ], [ "DirectoryRecurse", "If specified the specified directory will be recursed into (overriding the default behaviour).", "", 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", "" ], [ "StandbyDirectory", "Places restored databases in STANDBY mode with undo files created in the specified directory.\r\nUse this for log shipping secondary servers or when you need read-only access during restore operations.\r\nThe directory must exist and be writable by the SQL Server service account for undo file creation.", "", false, "false", "", "" ], [ "Continue", "Resumes log restore operations on databases currently in RESTORING or STANDBY states.\r\nUse this to apply additional transaction log backups to advance the recovery point of an existing restore chain.\r\nEssential for log shipping scenarios or when performing point-in-time recovery in multiple steps.", "", false, "false", "False", "" ], [ "ExecuteAs", "If value provided the restore will be executed under this login\u0027s context. The login must exist, and have the relevant permissions to perform the restore.", "", false, "false", "", "" ], [ "StorageCredential", "Specifies the SQL Server credential name for authenticating to Azure blob storage or S3-compatible object storage during restore operations.\r\nUse this when restoring from Azure blob storage or S3 backups that require authentication.\r\nFor Azure: The credential must contain valid Azure storage account keys or SAS tokens.\r\nFor S3: The credential must use Identity = \u0027S3 Access Key\u0027 and Secret = \u0027AccessKeyID:SecretKeyID\u0027. Requires SQL Server 2022 or higher.", "AzureCredential,S3Credential", false, "false", "", "" ], [ "ReplaceDbNameInFile", "Substitutes the original database name with the new DatabaseName in physical file names during restore.\r\nUse this when restoring databases with descriptive file names to maintain naming consistency.\r\nRequires DatabaseName parameter and helps avoid confusing file names like \"Production_Data.mdf\" in test environments.", "", false, "false", "False", "" ], [ "DestinationFileSuffix", "This value will be suffixed to ALL restored files (log and data). This is just a simple string suffix.\r\nIf you want to perform more complex rename operations then please use the FileMapping parameter.\r\nThis will apply to all file move options, except for FileMapping.", "", false, "false", "", "" ], [ "Recover", "Brings databases currently in RESTORING state online by executing RESTORE WITH RECOVERY.\r\nUse this to complete restore operations that were left in NoRecovery state or to finalize standby databases.\r\nMakes previously inaccessible databases available for normal read/write operations.", "", false, "false", "False", "" ], [ "KeepCDC", "Preserves Change Data Capture (CDC) configuration and data during the restore operation.\r\nUse this when restoring databases with CDC enabled and you need to maintain change tracking functionality.\r\nCannot be combined with NoRecovery or Standby modes as CDC requires the database to be fully recovered.", "", false, "false", "False", "" ], [ "GetBackupInformation", "Passing a string value into this parameter will cause a global variable to be created holding the output of Get-DbaBackupInformation.", "", false, "false", "", "" ], [ "StopAfterGetBackupInformation", "Switch which will cause the function to exit after returning GetBackupInformation.", "", false, "false", "False", "" ], [ "SelectBackupInformation", "Passing a string value into this parameter will cause a global variable to be created holding the output of Select-DbaBackupInformation.", "", false, "false", "", "" ], [ "StopAfterSelectBackupInformation", "Switch which will cause the function to exit after returning SelectBackupInformation.", "", false, "false", "False", "" ], [ "FormatBackupInformation", "Passing a string value into this parameter will cause a global variable to be created holding the output of Format-DbaBackupInformation.", "", false, "false", "", "" ], [ "StopAfterFormatBackupInformation", "Switch which will cause the function to exit after returning FormatBackupInformation.", "", false, "false", "False", "" ], [ "TestBackupInformation", "Passing a string value into this parameter will cause a global variable to be created holding the output of Test-DbaBackupInformation.", "", false, "false", "", "" ], [ "StopAfterTestBackupInformation", "Switch which will cause the function to exit after returning TestBackupInformation.", "", false, "false", "False", "" ], [ "PageRestore", "Performs targeted restoration of specific damaged pages using output from Get-DbaSuspectPages.\r\nUse this for repairing isolated page corruption without restoring the entire database.\r\nEnterprise Edition enables online page restore while Standard Edition requires the database offline during repair.", "", true, "false", "", "" ], [ "PageRestoreTailFolder", "Specifies where to create the tail log backup required for page restore operations.\r\nUse this to designate a safe location for the automatic tail log backup that page restore creates.\r\nThe folder must be accessible to the SQL Server service account and have sufficient space for the tail log backup.", "", true, "false", "", "" ], [ "StopBefore", "Switch to indicate the restore should stop before StopMark occurs, default is to stop when mark is created.", "", false, "false", "False", "" ], [ "StopMark", "Marked point in the transaction log to stop the restore at (Mark is created via BEGIN TRANSACTION \r\n(https://docs.microsoft.com/en-us/sql/t-sql/language-elements/begin-transaction-transact-sql?view=sql-server-ver15)).", "", false, "false", "", "" ], [ "StopAfterDate", "By default the restore will stop at the first occurence of StopMark found in the chain, passing a datetime where will cause it to stop the first StopMark atfer that datetime.", "", false, "false", "(Get-Date \u002701/01/1971\u0027)", "" ], [ "StatementTimeout", "Sets the maximum time in minutes to wait for restore operations before timing out.\r\nUse this to prevent extremely long-running restores from hanging indefinitely in automated scripts.\r\nDefaults to unlimited since large database restores can take hours depending on size and storage speed.", "", false, "false", "0", "" ], [ "Checksum", "Enables backup checksum verification during restore operations. Forces the restore to verify backup checksums and fail if checksums are not present.\r\nUse this to ensure backup files contain checksums and validate them during restore, following backup best practices.\r\nWithout this parameter, SQL Server verifies checksums if present but doesn\u0027t fail if checksums are missing. With this parameter, the operation fails if checksums are not present in the backup.", "", false, "false", "False", "" ], [ "Restart", "Instructs the restore operation to restart an interrupted restore sequence.\r\nUse this when a previous restore operation was interrupted due to a reboot, service failure, or other system event.\r\nAllows resuming large transaction log restores that were partially completed before interruption.", "", false, "false", "False", "" ], [ "WhatIf", "Shows what would happen if the command would execute, but does not actually perform the command.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts to confirm certain actions.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "CertBackup", "Certificate", "Backup" ], "CommandName": "Restore-DbaDbCertificate", "Name": "Restore-DbaDbCertificate", "Author": "Jess Pomfret (@jpomfret), jesspomfret.com", "Syntax": "Restore-DbaDbCertificate [-SqlInstance] \u003cDbaInstanceParameter\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Path] \u003cString[]\u003e [[-KeyFilePath] \u003cString[]\u003e] [[-EncryptionPassword] \u003cSecureString\u003e] [[-Database] \u003cString\u003e] [[-Name] \u003cString\u003e] [[-DecryptionPassword] \u003cSecureString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Certificate\nReturns one Certificate object per certificate successfully restored to the database. For example, restoring 3 certificates results in 3 objects being 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 where the certificate was restored\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, or MasterKey)\r\n- Serial: The serial number of the certificate\nAdditional properties available from the SMO Certificate object (via Select-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", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$securepass = Get-Credential usernamedoesntmatter | Select-Object -ExpandProperty Password\nPS C:\\\u003e Restore-DbaDbCertificate -SqlInstance Server1 -Path \\\\Server1\\Certificates -DecryptionPassword $securepass\nRestores all the certificates in the specified path, password is used to both decrypt and encrypt the private key.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRestore-DbaDbCertificate -SqlInstance Server1 -Path \\\\Server1\\Certificates\\DatabaseTDE.cer -DecryptionPassword (Get-Credential usernamedoesntmatter).Password\nRestores the DatabaseTDE certificate to Server1 and uses the MasterKey to encrypt the private key.", "Description": "Restores database certificates and their associated private keys from backup files into SQL Server databases. This function is essential for recovering certificates used in TDE (Transparent Data Encryption), backup encryption, Always Encrypted, and other SQL Server security features after database migrations, disaster recovery, or server rebuilds.\n\nThe function automatically locates matching private key files (.pvk) for each certificate (.cer) when processing directories, or you can specify key file paths explicitly. Handles password-protected private keys with secure credential management, and allows you to re-encrypt keys during the restore process if needed.", "Links": "https://dbatools.io/Restore-DbaDbCertificate", "Synopsis": "Restores database certificates from .cer and .pvk files into SQL Server databases.", "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", "", "" ], [ "Path", "Specifies the file system path to certificate files (.cer) or a directory containing multiple certificates. When pointing to a directory, the function processes all .cer files found within it.\r\nUse this to restore certificates from your certificate backup location after disaster recovery or server migrations.", "FullName,ExportPath", true, "true (ByPropertyName)", "", "" ], [ "KeyFilePath", "Specifies the path to the private key file (.pvk) associated with the certificate. If not provided, the function automatically searches for a matching .pvk file in the same directory as the \r\ncertificate.\r\nOnly specify this when your private key files are stored in a different location from your certificate files.", "Key", false, "true (ByPropertyName)", "", "" ], [ "EncryptionPassword", "Sets a new password to encrypt the private key after restoration to SQL Server. If not specified, the restored certificate will be encrypted with the database master key.\r\nUse this when you want to change the private key encryption method or set a specific password for the restored certificate.", "", false, "false", "", "" ], [ "Database", "Specifies the target database where the certificate will be restored. Defaults to the master database if not specified.\r\nUse this when restoring certificates for specific database features like TDE, Always Encrypted, or application-specific encryption within user databases.", "", false, "false", "master", "" ], [ "Name", "Specifies a custom name for the restored certificate in SQL Server. If not provided, the function derives the name from the certificate file name, removing instance and database prefixes.\r\nUse this when you need the certificate to have a specific name that differs from the backup file naming convention.", "", false, "false", "", "" ], [ "DecryptionPassword", "Provides the password required to decrypt the private key file (.pvk) during certificate restoration. This password was set when the certificate was originally backed up.\r\nRequired for all certificate restores since private keys are encrypted by default when exported from SQL Server.", "Password,SecurePassword", false, "false", "(Read-Host \"Decryption password\" -AsSecureString)", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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": [ "Snapshot", "Backup", "Restore", "Database" ], "CommandName": "Restore-DbaDbSnapshot", "Name": "Restore-DbaDbSnapshot", "Author": "Simone Bizzotto (@niphold)", "Syntax": "Restore-DbaDbSnapshot [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-Snapshot] \u003cObject[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Database\nReturns one Database object for each database that was successfully restored from a snapshot. The returned object represents the state of the database after the restore operation completed and log \r\nfile growth settings were restored to their pre-snapshot values.\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 (Normal, Suspect, Offline, etc.)\r\n- IsAccessible: Boolean indicating if the database is currently accessible\r\n- RecoveryModel: Database recovery model (Full, Simple, BulkLogged)\r\n- Owner: Database owner login name\nAdditional properties available from the SMO Database object:\r\n- Size: Current size of the database in megabytes\r\n- CreateDate: DateTime when the database was created\r\n- LastBackupDate: DateTime of the most recent backup\r\n- LastDiffBackup: DateTime of the most recent differential backup\r\n- LastLogBackup: DateTime of the most recent transaction log backup\r\n- Collation: Database collation setting\r\n- CompatibilityLevel: Database compatibility level\nAll properties from the base SMO Database object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRestore-DbaDbSnapshot -SqlInstance sql2014 -Database HR, Accounting\nRestores HR and Accounting databases using the latest snapshot available\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRestore-DbaDbSnapshot -SqlInstance sql2014 -Database HR -Force\nRestores HR database from latest snapshot and kills any active connections in the database on sql2014.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbSnapshot -SqlInstance sql2016 -Database HR | Restore-DbaDbSnapshot -Force\nRestores HR database from latest snapshot and kills any active connections in the database on sql2016.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDbSnapshot -SqlInstance sql2016 | Out-GridView -PassThru | Restore-DbaDbSnapshot\nAllows the selection of snapshots on sql2016 to restore\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eRestore-DbaDbSnapshot -SqlInstance sql2014 -Snapshot HR_snap_20161201, Accounting_snap_20161101\nRestores databases from snapshots named HR_snap_20161201 and Accounting_snap_20161101", "Description": "Restores SQL Server databases to their exact state when a database snapshot was created, discarding all changes made since that point. This is particularly useful for quickly reverting development databases after testing, rolling back problematic changes, or returning to a known good state without restoring from backup files.\n\nThe function uses SQL Server\u0027s RESTORE DATABASE FROM DATABASE_SNAPSHOT command and automatically handles SQL Server\u0027s requirement that all other snapshots of the same database be dropped before restoration. It also fixes a SQL Server bug where log file growth settings get reset to their defaults during snapshot restoration.\n\nWhen Force is specified, the command will terminate active connections to both the target database and snapshot to ensure the restore operation completes successfully.", "Links": "https://dbatools.io/Restore-DbaDbSnapshot", "Synopsis": "Restores SQL Server databases from database snapshots, reverting to the snapshot\u0027s point-in-time state", "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 restore from their most recent snapshots. Accepts multiple database names and wildcards for pattern matching.\r\nUse this when you want to restore specific databases to their snapshot state rather than working with snapshot names directly.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific databases from being restored when using wildcard patterns or restoring multiple databases.\r\nHelpful when you want to restore most databases from snapshots but skip certain critical production databases.", "", false, "false", "", "" ], [ "Snapshot", "Specifies the exact snapshot names to restore from, giving you precise control over which snapshot is used for each database.\r\nUse this when you need to restore from specific snapshots rather than automatically using the most recent ones.", "", false, "false", "", "" ], [ "InputObject", "Accepts snapshot objects from other dbatools commands like Get-DbaDbSnapshot through the PowerShell pipeline.\r\nThis enables you to filter and select specific snapshots before restoring, such as using Out-GridView for interactive selection.", "", false, "true (ByValue)", "", "" ], [ "Force", "Automatically drops other snapshots of the same database that would prevent the restore operation, as required by SQL Server.\r\nAlso terminates active connections to both the target database and snapshot to ensure the restore completes successfully.\r\nRequired when multiple snapshots exist for the database being restored or when active sessions could block the operation.", "", 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", "wi", false, "false", "", "" ], [ "Confirm", "Prompts for confirmation of every step.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "AG", "HA" ], "CommandName": "Resume-DbaAgDbDataMovement", "Name": "Resume-DbaAgDbDataMovement", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Resume-DbaAgDbDataMovement [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-AvailabilityGroup] \u003cString\u003e] [[-Database] \u003cString[]\u003e] [[-InputObject] \u003cAvailabilityDatabase[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.AvailabilityDatabase\nReturns one AvailabilityDatabase object per database that had data movement successfully resumed. The object is modified in-place by the ResumeDataMovement() method call, which reconnects the \r\nsecondary replica to the primary\u0027s transaction log stream.\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 (should be False after ResumeDataMovement succeeds)\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- LastCommitTime: Timestamp of last committed transaction\r\n- LogSendQueue: Size of log send queue in KB\r\n- RedoRate: Rate of redo operations (bytes/sec)\r\n- State: SMO object state (Existing, Creating, Pending, etc.)\nAll properties from the base SMO object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eResume-DbaAgDbDataMovement -SqlInstance sql2017a -AvailabilityGroup ag1 -Database db1, db2\nResumes data movement on db1 and db2 to ag1 on sql2017a. Prompts for confirmation.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgDatabase -SqlInstance sql2017a, sql2019 | Out-GridView -Passthru | Resume-DbaAgDbDataMovement -Confirm:$false\nResumes data movement on the selected availability group databases. Does not prompt for confirmation.", "Description": "Resumes data movement for availability group databases that have been suspended due to errors, maintenance, or storage issues. When data movement is suspended, secondary replicas stop receiving transaction log records from the primary, causing synchronization lag. This function reconnects the synchronization process so secondary replicas can catch up to the primary replica.", "Links": "https://dbatools.io/Resume-DbaAgDbDataMovement", "Synopsis": "Resumes suspended data synchronization for availability group databases.", "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 the name of the availability group containing the databases with suspended data movement.\r\nRequired when using the SqlInstance parameter to identify which AG context to work within.", "", false, "false", "", "" ], [ "Database", "Specifies which availability group databases to resume data movement for. Accepts multiple database names.\r\nUse this to target specific databases when you don\u0027t want to resume movement for all databases in the availability group.", "", false, "false", "", "" ], [ "InputObject", "Accepts availability group database objects from Get-DbaAgDatabase for pipeline operations.\r\nUse this when you want to filter or select specific AG databases before resuming data movement.", "", 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": "Revoke-DbaAgPermission", "Name": "Revoke-DbaAgPermission", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Revoke-DbaAgPermission [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Login] \u003cString[]\u003e] [[-AvailabilityGroup] \u003cString[]\u003e] [-Type] \u003cString[]\u003e [[-Permission] \u003cString[]\u003e] [[-InputObject] \u003cLogin[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per permission successfully revoked from each login. When revoking multiple permissions on multiple logins, the total objects returned equals the product of successful operations.\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 login name from which the permission was revoked\r\n- Permission: The permission that was revoked (Connect, Alter, Control, etc.)\r\n- Type: Always \"Revoke\" indicating the operation type\r\n- Status: \"Success\" when the revocation completes successfully", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eRevoke-DbaAgPermission -SqlInstance sql2017a -Type AvailabilityGroup -AvailabilityGroup SharePoint -Login ad\\spservice -Permission CreateAnyDatabase\nRemoves CreateAnyDatabase permissions from ad\\spservice on the SharePoint availability group on sql2017a. Does not prompt for confirmation.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eRevoke-DbaAgPermission -SqlInstance sql2017a -Type AvailabilityGroup -AvailabilityGroup ag1, ag2 -Login ad\\spservice -Permission CreateAnyDatabase -Confirm\nRemoves CreateAnyDatabase permissions from ad\\spservice on the ag1 and ag2 availability groups on sql2017a. Prompts for confirmation.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaLogin -SqlInstance sql2017a | Out-GridView -Passthru | Revoke-DbaAgPermission -Type EndPoint\nRevokes the selected logins Connect permissions on the DatabaseMirroring endpoint for sql2017a.", "Description": "Removes specific permissions from SQL Server logins on either database mirroring endpoints or availability groups. This is commonly needed when service accounts change roles, security policies require permission reductions, or during availability group maintenance and troubleshooting. For endpoints, you can revoke most standard permissions like Connect, Alter, and Control. For availability groups, only Alter, Control, TakeOwnership, and ViewDefinition permissions can be revoked.", "Links": "https://dbatools.io/Revoke-DbaAgPermission", "Synopsis": "Revokes permissions from SQL Server logins on database mirroring endpoints or availability groups.", "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", "", "" ], [ "Login", "Specifies the SQL Server logins or Windows accounts to remove permissions from. Required when using the SqlInstance parameter.\r\nUse this when you need to revoke access from service accounts, developers, or other principals that no longer need endpoint or availability group permissions.\r\nIf the specified login doesn\u0027t exist, the function will attempt to create it first.", "", false, "false", "", "" ], [ "AvailabilityGroup", "Specifies which availability groups to target for permission revocation. Required when using Type \u0027AvailabilityGroup\u0027.\r\nUse this to limit the scope when you only want to revoke permissions on specific AGs rather than all availability groups in the instance.\r\nAccepts multiple availability group names for bulk operations.", "", false, "false", "", "" ], [ "Type", "Determines whether to revoke permissions on database mirroring endpoints or availability groups. This parameter is mandatory.\r\nUse \u0027Endpoint\u0027 to revoke permissions on the DatabaseMirroring endpoint, typically needed for Always On setup or mirroring configurations.\r\nUse \u0027AvailabilityGroup\u0027 to revoke permissions directly on specific availability group objects for more granular security control.", "", true, "false", "", "Endpoint,AvailabilityGroup" ], [ "Permission", "Specifies which permissions to revoke from the targeted logins. Defaults to \u0027Connect\u0027 if not specified.\r\nFor endpoints, most permissions are valid including Connect, Alter, and Control. CreateAnyDatabase is not supported for endpoints.\r\nFor availability groups, only Alter, Control, TakeOwnership, and ViewDefinition are supported.\r\nUse Connect for basic endpoint access, Alter for configuration changes, Control for full permissions, or ViewDefinition for read-only metadata access.", "", false, "false", "Connect", "Alter,Connect,Control,CreateAnyDatabase,CreateSequence,Delete,Execute,Impersonate,Insert,Receive,References,Select,Send,TakeOwnership,Update,ViewChangeTracking,ViewDefinition" ], [ "InputObject", "Accepts SQL Server login objects from the pipeline, typically from Get-DbaLogin.\r\nUse this approach when you want to filter or select specific logins before revoking permissions, or when combining with other dbatools commands.\r\nThis parameter provides an alternative to specifying SqlInstance and Login parameters 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": "Community", "CommandName": "Save-DbaCommunitySoftware", "Name": "Save-DbaCommunitySoftware", "Author": "Andreas Jordan, @JordanOrdix", "Syntax": "Save-DbaCommunitySoftware [[-Software] \u003cString\u003e] [[-Branch] \u003cString\u003e] [[-LocalFile] \u003cString\u003e] [[-Url] \u003cString\u003e] [[-LocalDirectory] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "None\nThis command does not output any objects to the pipeline. It performs file operations to download and extract community software tools to the local cache directory. To verify successful operation, \r\ncheck the exit code or use ErrorAction/ErrorVariable parameters.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSave-DbaCommunitySoftware -Software MaintenanceSolution\nUpdates the local cache of Ola Hallengren\u0027s Solution objects.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSave-DbaCommunitySoftware -Software FirstResponderKit -LocalFile \\\\fileserver\\Software\\SQL-Server-First-Responder-Kit-20211106.zip\nUpdates the local cache of the First Responder Kit based on the given file.", "Description": "Downloads and extracts popular SQL Server community tools from GitHub repositories to maintain a local cache used by dbatools installation commands.\nThis function automatically manages the acquisition and versioning of essential DBA script collections, eliminating the need to manually download and organize multiple tool repositories.\nIt\u0027s called internally by Install-Dba*, Update-Dba*, and Invoke-DbaAzSqlDbTip commands when they need to access the latest versions of community tools.\n\nSupports both online downloads directly from GitHub and offline installations using local zip files, making it suitable for restricted network environments.\nThe function handles version detection, directory structure normalization, and maintains consistent file organization across different tool repositories.\n\nFor environments without internet access, you can download zip files from the following URLs on another computer, transfer them to the target system, and use -LocalFile to update the local cache:\n* MaintenanceSolution: https://github.com/olahallengren/sql-server-maintenance-solution\n* FirstResponderKit: https://github.com/BrentOzarULTD/SQL-Server-First-Responder-Kit/releases\n* DarlingData: https://github.com/erikdarlingdata/DarlingData\n* SQLWATCH: https://github.com/marcingminski/sqlwatch/releases\n* WhoIsActive: https://github.com/amachanic/sp_whoisactive/releases\n* DbaMultiTool: https://github.com/LowlyDBA/dba-multitool/releases\n* AzSqlTips: https://github.com/microsoft/azure-sql-tips/releases/", "Links": "https://dbatools.io/Save-DbaCommunitySoftware", "Synopsis": "Downloads and caches popular SQL Server community tools from GitHub for use by dbatools installation commands", "Availability": "Windows, Linux, macOS", "Params": [ [ "Software", "Name of the software to download.\r\nOptions include:\r\n* MaintenanceSolution: SQL Server Maintenance Solution created by Ola Hallengren (https://ola.hallengren.com)\r\n* FirstResponderKit: First Responder Kit created by Brent Ozar (http://FirstResponderKit.org)\r\n* DarlingData: Erik Darling\u0027s stored procedures (https://www.erikdarlingdata.com)\r\n* SQLWATCH: SQL Server Monitoring Solution created by Marcin Gminski (https://sqlwatch.io/)\r\n* WhoIsActive: Adam Machanic\u0027s comprehensive activity monitoring stored procedure sp_WhoIsActive (https://github.com/amachanic/sp_whoisactive)\r\n* DbaMultiTool: John McCall\u0027s T-SQL scripts for the long haul: optimizing storage, on-the-fly documentation, and general administrative needs (https://dba-multitool.org)\r\n* AzSqlTips: Azure SQL PM team scripts to review Azure SQL Database design, health and performance.", "", false, "false", "", "MaintenanceSolution,FirstResponderKit,DarlingData,SQLWATCH,WhoIsActive,DbaMultiTool,AzSqlTips" ], [ "Branch", "Specifies which branch or version to download from the GitHub repository. Defaults to master or main depending on the repository.\r\nUse this when you need a specific development branch or to override default versioning. Only applies to branch-based downloads like MaintenanceSolution, FirstResponderKit, DarlingData, and \r\nDbaMultiTool.\r\nFor SQLWATCH, use \u0027prerelease\u0027 or \u0027pre-release\u0027 to get preview versions instead of stable releases.", "", false, "false", "", "" ], [ "LocalFile", "Specifies the path to a local zip file or SQL script to install from instead of downloading from GitHub.\r\nUse this for offline environments or when you have a specific version already downloaded. Accepts zip archives for all tools, plus individual SQL files for WhoIsActive (sp_WhoIsActive.sql) and \r\nAzSqlTips (get-sqldb-tips.sql).\r\nEssential for air-gapped systems where direct internet access is not available.", "", false, "false", "", "" ], [ "Url", "Specifies a custom URL to download the software archive from instead of using the automatic GitHub URLs.\r\nUse this when you need to download from a forked repository, specific release, or alternative hosting location. Overrides the default URL generation that occurs when using the Software parameter.\r\nMust point to a downloadable zip file containing the community tools.", "", false, "false", "", "" ], [ "LocalDirectory", "Specifies a custom directory path where the community software will be extracted and cached.\r\nUse this when you need to store the tools in a non-standard location instead of the default dbatools data directory. Overrides the automatic path generation based on the Software parameter.\r\nUseful for custom cache locations or when working with multiple versions of the same tool.", "", 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": [ "Community", "GlennBerry" ], "CommandName": "Save-DbaDiagnosticQueryScript", "Name": "Save-DbaDiagnosticQueryScript", "Author": "Andre Kamman (@AndreKamman), andrekamman.com", "Syntax": "Save-DbaDiagnosticQueryScript [[-Path] \u003cFileInfo\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.IO.FileInfo\nReturns one file information object for each diagnostic script downloaded. Each object represents a downloaded SQL script file containing Glenn Berry\u0027s diagnostic queries.\nProperties:\r\n- FullName: Full file path of the downloaded diagnostic query script (e.g., C:\\Users\\UserName\\Documents\\SQLServerDiagnosticQueries_2022.sql)\r\n- Name: The filename of the script (e.g., SQLServerDiagnosticQueries_2022.sql)\r\n- Extension: File extension (.sql)\r\n- Length: File size in bytes\r\n- CreationTime: DateTime when the file was created\r\n- LastWriteTime: DateTime when the file was last modified\r\n- Directory: The directory object containing the file\r\n- Attributes: File attributes (Archive, etc.)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSave-DbaDiagnosticQueryScript -Path c:\\temp\nDownloads the most recent version of all Glenn Berry DMV scripts to the specified location.\r\nIf Path is not specified, the \"My Documents\" location will be used.", "Description": "Downloads the latest versions of Glenn Berry\u0027s renowned SQL Server Diagnostic Information Queries from his website. These DMV-based scripts are essential tools for DBAs to assess SQL Server health, identify performance bottlenecks, and gather comprehensive system information across all SQL Server versions including Azure SQL Database and Managed Instance.\n\nThe dbatools module includes diagnostic queries pre-installed, but this function lets you update to more recent versions or download specific versions for your environment. This is particularly valuable since Glenn Berry regularly updates these scripts with new insights and compatibility improvements.\n\nThis function is primarily used by Invoke-DbaDiagnosticQuery, but can also be used independently to download the scripts. Use this to pre-download scripts from a device with internet connection for later use on systems without internet access.\n\nThe function automatically detects and downloads scripts for all available SQL Server versions found on Glenn Berry\u0027s resources page, saving them with version-specific filenames for easy identification.", "Links": "https://dbatools.io/Save-DbaDiagnosticQueryScript", "Synopsis": "Downloads Glenn Berry\u0027s SQL Server Diagnostic Information Queries for performance monitoring and troubleshooting", "Availability": "Windows, Linux, macOS", "Params": [ [ "Path", "Specifies the directory path where Glenn Berry\u0027s diagnostic query scripts will be downloaded. Defaults to the current user\u0027s Documents folder.\r\nUse this when you need to organize scripts in a specific location, such as a shared network drive for team access or a local folder structure for different environments.", "", false, "false", "[Environment]::GetFolderPath(\"mydocuments\")", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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", "Patching" ], "CommandName": "Save-DbaKbUpdate", "Name": "Save-DbaKbUpdate", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Save-DbaKbUpdate [[-Name] \u003cString[]\u003e] [[-Path] \u003cString\u003e] [[-FilePath] \u003cString\u003e] [[-Architecture] \u003cString\u003e] [[-Language] \u003cString\u003e] [[-InputObject] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.IO.FileInfo\nReturns one FileInfo object for each successfully downloaded KB file. The objects represent the downloaded files saved to the local file system.\nProperties:\r\n- Name: The filename of the downloaded KB file\r\n- FullName: The complete file path where the file was saved\r\n- Length: The file size in bytes\r\n- Directory: The directory where the file was saved\r\n- CreationTime: DateTime when the file was created\r\n- LastWriteTime: DateTime when the file was last modified\r\n- Attributes: File attributes (Archive, ReadOnly, Hidden, etc.)\r\n- Mode: File permissions string (e.g., -a--- for archive)\nOnly files that successfully download and exist on disk are returned. If download fails or the file is not found after download, no object is returned for that file.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSave-DbaKbUpdate -Name KB4057119\nDownloads KB4057119 to the current directory. This works for SQL Server or any other KB.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaKbUpdate -Name KB4057119 -Simple | Out-GridView -Passthru | Save-DbaKbUpdate\nDownloads the selected files from KB4057119 to the current directory.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSave-DbaKbUpdate -Name KB4057119, 4057114 -Path C:\\temp\nDownloads KB4057119 and the x64 version of KB4057114 to C:\\temp. This works for SQL Server or any other KB.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eSave-DbaKbUpdate -Name KB4057114 -Architecture All -Path C:\\temp\nDownloads the x64 version of KB4057114 and the x86 version of KB4057114 to C:\\temp. This works for SQL Server or any other KB.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eSave-DbaKbUpdate -Name KB5003279 -Language enu -Path C:\\temp\nDownloads only the english version of KB5003279, which is the Service Pack 3 for SQL Server 2016, to C:\\temp.", "Description": "Downloads Microsoft KB updates, cumulative updates, and service packs from Microsoft\u0027s servers to your local file system. This function handles SQL Server patches as well as any other Microsoft KB updates, making it easy to stage patches for installation across multiple servers. Supports filtering by architecture (x86, x64, ia64) and language, and can download multiple KBs in a single operation. Use this to build a local patch repository or download specific updates for offline installation scenarios.", "Links": "https://dbatools.io/Save-DbaKbUpdate", "Synopsis": "Downloads Microsoft Knowledge Base updates and patches to local storage", "Availability": "Windows, Linux, macOS", "Params": [ [ "Name", "Specifies the Microsoft Knowledge Base article number to download. Accepts KB prefix or just the numeric value (e.g., \u0027KB4057119\u0027 or \u00274057119\u0027).\r\nUse this to target specific patches, cumulative updates, or service packs for SQL Server or other Microsoft products.\r\nSupports multiple KB numbers in a single command for batch downloading.", "", false, "false", "", "" ], [ "Path", "Specifies the directory where downloaded KB files will be saved. Defaults to the current working directory.\r\nUse this to organize patches into specific folders or network locations for easier deployment across multiple servers.\r\nThe directory will be created if it doesn\u0027t exist.", "", false, "false", ".", "" ], [ "FilePath", "Specifies the exact filename and path for the downloaded file, overriding the server-provided filename.\r\nUse this when you need custom naming conventions or want to save to a specific location with a particular name.\r\nCannot be used when downloading multiple KBs or when Architecture is set to \u0027All\u0027.", "", false, "false", "", "" ], [ "Architecture", "Specifies the CPU architecture for the downloaded files. Valid values are \u0027x64\u0027, \u0027x86\u0027, \u0027ia64\u0027, or \u0027All\u0027.\r\nUse \u0027All\u0027 to download files for all available architectures when you need to support mixed environments.\r\nMost modern SQL Server deployments use \u0027x64\u0027, which is the default.", "", false, "false", "x64", "x64,x86,ia64,All" ], [ "Language", "Filters downloads to a specific language version using three-letter language codes (e.g., \u0027enu\u0027 for English, \u0027deu\u0027 for German).\r\nPrimarily useful for SQL Server Service Packs which have separate files per language, unlike Cumulative Updates which are language-neutral.\r\nOnly downloads files matching the specified language code when multiple language versions are available.", "", false, "false", "", "" ], [ "InputObject", "Accepts pipeline input from Get-DbaKbUpdate, allowing you to filter and select specific files before downloading.\r\nUse this workflow to preview available downloads with Get-DbaKbUpdate, then pipe selected results for download.\r\nParticularly useful when working with KBs that have multiple file options.", "", 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", "Restore" ], "CommandName": "Select-DbaBackupInformation", "Name": "Select-DbaBackupInformation", "Author": "Stuart Moore (@napalmgram), stuart-moore.com", "Syntax": "Select-DbaBackupInformation [-BackupHistory] \u003cObject\u003e [[-RestoreTime] \u003cDateTime\u003e] [-IgnoreLogs] [-IgnoreDiffs] [[-DatabaseName] \u003cString[]\u003e] [[-ServerName] \u003cString[]\u003e] [[-ContinuePoints] \u003cObject\u003e] [[-LastRestoreType] \u003cObject\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Backup objects from Get-DbaBackupInformation\nReturns the filtered backup history objects from the input BackupHistory parameter that represent the minimum backup chain needed to restore the database to the specified RestoreTime. Each object \r\nincludes the original properties from Get-DbaBackupInformation plus an added RestoreTime property.\nThe returned objects represent:\r\n- One full or differential backup (the most recent full backup before RestoreTime, or the most recent differential backup)\r\n- Zero or more transaction log backups (the sequence of log backups from the most recent full/diff to the RestoreTime)\nOutput properties vary based on the input backup history objects, but typically include:\r\n- Database: The database name\r\n- Type: Backup type (Full, Differential, Log, Transaction Log, etc.)\r\n- BackupSetID: Unique identifier for the backup set\r\n- Start: DateTime when the backup started\r\n- End: DateTime when the backup completed\r\n- FirstLsn: First log sequence number in the backup\r\n- LastLsn: Last log sequence number in the backup\r\n- CheckpointLsn: Checkpoint LSN (for full backups)\r\n- DatabaseBackupLsn: LSN of the most recent full backup (for diff/log backups)\r\n- FullName: File path(s) to the backup file(s)\r\n- RestoreTime: The target restore time (added by this function)\nWhen -IgnoreLogs is specified, transaction log backups are excluded from the output.\r\nWhen -IgnoreDiffs is specified, differential backups are excluded from the output.\r\nWhen -ContinuePoints is specified with an interrupted restore, LSN-based filtering ensures continuity.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$Backups = Get-DbaBackupInformation -SqlInstance Server1 -Path \\\\server1\\backups$\nPS C:\\\u003e $FilteredBackups = $Backups | Select-DbaBackupInformation -RestoreTime (Get-Date).AddHours(-1)\nReturns all backups needed to restore all the backups in \\\\server1\\backups$ to 1 hour ago\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$Backups = Get-DbaBackupInformation -SqlInstance Server1 -Path \\\\server1\\backups$\nPS C:\\\u003e $FilteredBackups = $Backups | Select-DbaBackupInformation -RestoreTime (Get-Date).AddHours(-1) -DatabaseName ProdFinance\nReturns all the backups needed to restore Database ProdFinance to an hour ago\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$Backups = Get-DbaBackupInformation -SqlInstance Server1 -Path \\\\server1\\backups$\nPS C:\\\u003e $FilteredBackups = $Backups | Select-DbaBackupInformation -RestoreTime (Get-Date).AddHours(-1) -IgnoreLogs\nReturns all the backups in \\\\server1\\backups$ to restore to as close prior to 1 hour ago as can be managed with only full and differential backups\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$Backups = Get-DbaBackupInformation -SqlInstance Server1 -Path \\\\server1\\backups$\nPS C:\\\u003e $FilteredBackups = $Backups | Select-DbaBackupInformation -RestoreTime (Get-Date).AddHours(-1) -IgnoreDiffs\nReturns all the backups in \\\\server1\\backups$ to restore to 1 hour ago using only Full and Log backups.", "Description": "Analyzes backup history objects and determines the exact sequence of backups required to restore a database to a specific point in time. This function handles the complex LSN logic to identify which full, differential, and log backups are needed, eliminating the guesswork of manual restore planning. It supports continuing interrupted restores, filtering by database or server names, and accommodating different restore strategies by optionally ignoring differential or log backups. Perfect for automating disaster recovery procedures or when you need to restore to a precise moment without restoring unnecessary backup files.", "Links": "https://dbatools.io/Select-DbaBackupInformation", "Synopsis": "Filters backup history to identify the minimum backup chain needed for point-in-time database recovery", "Availability": "Windows, Linux, macOS", "Params": [ [ "BackupHistory", "Backup history records from Get-DbaBackupInformation containing backup metadata and file paths.\r\nThis function analyzes these records to determine the minimum backup chain needed for point-in-time recovery.", "", true, "true (ByValue)", "", "" ], [ "RestoreTime", "The specific point in time to restore the database to. Defaults to one month in the future if not specified.\r\nUse this when you need to recover to a specific moment, such as just before a data corruption incident occurred.", "", false, "false", "(Get-Date).addmonths(1)", "" ], [ "IgnoreLogs", "Excludes transaction log backups from the restore chain, limiting recovery to the most recent full or differential backup.\r\nUse this when you don\u0027t need point-in-time recovery or when log backups are unavailable or corrupted.", "", false, "false", "False", "" ], [ "IgnoreDiffs", "Excludes differential backups from the restore chain, using only full backups and transaction logs.\r\nUse this when differential backups are corrupted or when you want to test a restore strategy using only full and log backups.", "", false, "false", "False", "" ], [ "DatabaseName", "Filters results to only include backup chains for the specified database names. Accepts wildcards.\r\nUse this when you only need to restore specific databases from a backup set containing multiple databases.", "", false, "false", "", "" ], [ "ServerName", "Filters results to only include backups from the specified server or availability group names.\r\nFor Availability Groups, this filters by the AG name rather than individual replica server names.", "", false, "false", "", "" ], [ "ContinuePoints", "Output from Get-RestoreContinuableDatabase containing LSN and fork information for resuming interrupted restores.\r\nUse this when continuing a partial restore operation on a database that\u0027s already in a restoring state.", "", false, "false", "", "" ], [ "LastRestoreType", "Output from Get-DbaDbRestoreHistory -Last showing the most recent restore operation performed on the target database.\r\nThis determines whether differential backups can be applied based on the last restore type performed.", "", 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": [ "Data", "Sequence", "Table" ], "CommandName": "Select-DbaDbSequenceNextValue", "Name": "Select-DbaDbSequenceNextValue", "Author": "Adam Lancaster, github.com/lancasteradam", "Syntax": "Select-DbaDbSequenceNextValue [[-SqlInstance] \u003cDbaInstanceParameter\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString\u003e] [-Sequence] \u003cString[]\u003e [[-Schema] \u003cString\u003e] [[-InputObject] \u003cDatabase\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.Int64\nReturns the next value from the specified sequence object as a 64-bit integer. Each call to this function increments the sequence\u0027s internal counter and returns the next value in the sequence series.\nWhen multiple sequences are specified via the -Sequence parameter, one integer value is returned per sequence in the order specified. The returned value is the SQL Server sequence value (typically a \r\nbigint data type).\nExample values: 1, 2, 3, 100, 1000, etc., depending on the sequence\u0027s start value, increment, and current state.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSelect-DbaDbSequenceNextValue -SqlInstance sqldev01 -Database TestDB -Sequence TestSequence\nSelects the next value from the sequence TestSequence in the TestDB database on the sqldev01 instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sqldev01 -Database TestDB | Select-DbaDbSequenceNextValue -Sequence TestSequence -Schema TestSchema\nUsing a pipeline this command selects the next value from the sequence TestSchema.TestSequence in the TestDB database on the sqldev01 instance.", "Description": "Executes a SELECT NEXT VALUE FOR statement against the specified sequence, which increments the sequence counter and returns the next value in the series.\nThis is useful for testing sequence behavior, troubleshooting sequence issues, or retrieving sequence values for application logic.\nNote that calling this function will permanently increment the sequence counter, so it\u0027s not just a read operation.", "Links": "https://dbatools.io/Select-DbaDbSequenceNextValue", "Synopsis": "Retrieves and increments the next value from a SQL Server sequence object.", "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 containing the sequence object you want to increment.\r\nRequired when using SqlInstance parameter to identify which database contains the target sequence.", "", false, "false", "", "" ], [ "Sequence", "Specifies the name of the sequence object to increment and retrieve the next value from.\r\nAccepts multiple sequence names when you need to get next values from several sequences in the same operation.\r\nThis will permanently increment each sequence\u0027s internal counter.", "Name", true, "false", "", "" ], [ "Schema", "Specifies the schema that contains the sequence object. Defaults to \u0027dbo\u0027 if not specified.\r\nUse this when your sequence is created in a custom schema other than the default dbo schema.", "", false, "false", "dbo", "" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase via pipeline input.\r\nUse this to chain database selection with sequence operations when working with multiple databases or 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", "" ], [ "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", "", "" ] ] }, { "Description": "Wrapper around Select-Object, extends property parameter.\r\n\r\n This function allows specifying in-line transformation of the properties specified without needing to use complex hashtables.\r\n For example, renaming a property becomes as simple as \u0027Length as Size\u0027\r\n\r\n Also supported:\r\n\r\n - Specifying a typename\r\n\r\n - Picking the default display properties\r\n\r\n - Adding to an existing object without destroying its type\r\n\r\n See the description of the Property parameter for an exhaustive list of legal notations for in-line transformations.", "CommandName": "Select-DbaObject", "Synopsis": "Wrapper around Select-Object, extends property parameter.", "Author": "Friedrich Weinmann (@FredWeinmann)", "Syntax": "Select-DbaObject [-Property \u003cDbaSelectParameter[]\u003e] [-Alias \u003cSelectAliasParameter[]\u003e] [-ScriptProperty \u003cSelectScriptPropertyParameter[]\u003e] [-ScriptMethod \u003cSelectScriptMethodParameter[]\u003e] [-InputObject ] [-ExcludeProperty \u003cstring[]\u003e] [-ExpandProperty ] -Unique [-Last ] [-First ] [-Skip ] -Wait [-ShowProperty \u003cstring[]\u003e] [-ShowExcludeProperty \u003cstring[]\u003e] [-TypeName ] -KeepInputObject []\r\n\r\n Select-DbaObject [-Property \u003cDbaSelectParameter[]\u003e] [-Alias \u003cSelectAliasParameter[]\u003e] [-ScriptProperty \u003cSelectScriptPropertyParameter[]\u003e] [-ScriptMethod \u003cSelectScriptMethodParameter[]\u003e] [-InputObject ] [-ExcludeProperty \u003cstring[]\u003e] [-ExpandProperty ] -Unique [-SkipLast ] [-ShowProperty \u003cstring[]\u003e] [-ShowExcludeProperty \u003cstring[]\u003e] [-TypeName ] -KeepInputObject []\r\n\r\n Select-DbaObject [-InputObject ] -Unique -Wait [-Index \u003cint[]\u003e] [-ShowProperty \u003cstring[]\u003e] [-ShowExcludeProperty \u003cstring[]\u003e] [-TypeName ] -KeepInputObject []", "Alias": "", "Outputs": "returnValue\r\n-----------\r\n@{type=}", "Examples": " ---------------- Example 1: Renaming a property ----------------\r\n Get-ChildItem | Select-DbaObject Name, \"Length as Size\"\r\n\r\n Selects the properties Name and Length, renaming Length to Size in the process.\r\n\r\n ------------------ Example 2: Converting type ------------------\r\n\r\n Import-Csv .\\file.csv | Select-DbaObject Name, \"Length as Size to DbaSize\"\r\n\r\n Selects the properties Name and Length, renaming Length to Size and converting it to [DbaSize] (a userfriendly representation of\r\n size numbers contained in the dbatools module)\r\n\r\n ---------- Example 3: Selecting from another object 1 ----------\r\n\r\n $obj = [PSCustomObject]@{ Name = \"Foo\" }\r\n Get-ChildItem | Select-DbaObject FullName, Length, \"Name from obj\"\r\n\r\n Selects the properties FullName and Length from the input and the Name property from the object stored in $obj\r\n\r\n ---------- Example 4: Selecting from another object 2 ----------\r\n\r\n $list = @()\r\n $list += [PSCustomObject]@{ Type = \"Foo\"; ID = 1 }\r\n $list += [PSCustomObject]@{ Type = \"Bar\"; ID = 2 }\r\n $obj | Select-DbaObject Name, \"ID from list WHERE Type = Name\"\r\n\r\n This allows you to LEFT JOIN contents of another variable. Note that it can only do simple property-matching at this point.\r\n\r\n It will select Name from the objects stored in $obj, and for each of those the ID Property on any object in $list that has a\r\n Type property of equal value as Name on the input.\r\n\r\n ---------------- Example 5: Naming and styling ----------------\r\n\r\n Get-ChildItem | Select-DbaObject Name, Length, FullName, Used, LastWriteTime, Mode -TypeName MyType -ShowExcludeProperty Mode,\r\n Used\r\n\r\n Lists all items in the current path, selects the properties specified (whether they exist or not) , then ...\r\n\r\n - Sets the name to \"MyType\"\r\n\r\n - Hides the properties \"Mode\" and \"Used\" from the default display set, causing them to be hidden from default view", "Name": "Select-DbaObject", "Params": [ [ "Alias", "", "", false, "false", null, "" ], [ "ExcludeProperty", "", "", false, "false", null, "" ], [ "ExpandProperty", "", "", false, "false", null, "" ], [ "First", "", "", false, "false", null, "" ], [ "Index", "", "", false, "false", null, "" ], [ "InputObject", "", "", false, "true (ByValue)", null, "" ], [ "KeepInputObject", "", "", false, "false", null, "" ], [ "Last", "", "", false, "false", null, "" ], [ "Property", "", "", false, "false", null, "" ], [ "ScriptMethod", "", "", false, "false", null, "" ], [ "ScriptProperty", "", "", false, "false", null, "" ], [ "ShowExcludeProperty", "", "", false, "false", null, "" ], [ "ShowProperty", "", "", false, "false", null, "" ], [ "Skip", "", "", false, "false", null, "" ], [ "SkipLast", "", "", false, "false", null, "" ], [ "TypeName", "", "", false, "false", null, "" ], [ "Unique", "", "", false, "false", null, "" ], [ "Wait", "", "", false, "false", null, "" ] ], "Links": null, "Availability": "Windows, Linux, macOS" }, { "Tags": [ "Agent", "Alert" ], "CommandName": "Set-DbaAgentAlert", "Name": "Set-DbaAgentAlert", "Author": "Garry Bargsley (@gbargsley), garrybargsley.com", "Syntax": "Set-DbaAgentAlert [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Alert] \u003cObject[]\u003e] [[-NewName] \u003cString\u003e] [-Enabled] [-Disabled] [-Force] [[-InputObject] \u003cAlert[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Agent.Alert\nReturns one Alert object for each alert that was modified. The returned objects include all properties from the Alert object with added connection context 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: The name of the alert\r\n- IsEnabled: Boolean indicating if the alert is currently enabled\r\n- NotificationMessage: The message sent when the alert fires\r\n- AlertType: Type of alert (EventAlert, PerformanceConditionAlert, or TransactionLogAlert)\r\n- Severity: The severity level that triggers this alert (if alert type is EventAlert)\r\n- DatabaseName: The database name the alert applies to (if applicable)\r\n- EventDescriptionKeyword: Keywords in the error message that trigger the alert\r\n- LastOccurrenceDate: DateTime of the last time this alert was triggered\r\n- OccurrenceCount: Number of times this alert has been triggered\nAdditional properties available (from SMO Alert object):\r\n- ID: Unique identifier for the alert\r\n- CreateDate: DateTime when the alert was created\r\n- DateLastModified: DateTime when the alert was last modified\r\n- JobName: The SQL Agent job to execute when the alert fires\r\n- PerformanceCondition: The performance condition that triggers the alert\r\n- HasNotification: Boolean indicating if notification methods are configured\nAll properties from the base SMO Alert object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaAgentAlert -SqlInstance sql1 -Alert \u0027Severity 025: Fatal Error\u0027 -Disabled\nChanges the alert to disabled.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaAgentAlert -SqlInstance sql1 -Alert \u0027Severity 025: Fatal Error\u0027, \u0027Error Number 825\u0027, \u0027Error Number 824\u0027 -Enabled\nChanges multiple alerts to enabled.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-DbaAgentAlert -SqlInstance sql1, sql2, sql3 -Alert \u0027Severity 025: Fatal Error\u0027, \u0027Error Number 825\u0027, \u0027Error Number 824\u0027 -Enabled\nChanges multiple alerts to enabled on multiple servers.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eSet-DbaAgentAlert -SqlInstance sql1 -Alert \u0027Severity 025: Fatal Error\u0027 -Disabled -WhatIf\nDoesn\u0027t Change the alert but shows what would happen.", "Description": "Modifies existing SQL Agent alerts on one or more SQL Server instances, allowing you to enable, disable, or rename alerts without using SQL Server Management Studio. This function is particularly useful for bulk operations across multiple servers, standardizing alert configurations between environments, or temporarily disabling noisy alerts during maintenance windows. The function works with the JobServer.Alerts collection and uses the SMO Alter() method to commit changes to existing alerts. You can specify alerts by name or pipe in alert objects from other dbatools commands like Get-DbaAgentAlert.", "Links": "https://dbatools.io/Set-DbaAgentAlert", "Synopsis": "Modifies properties of existing SQL Agent alerts including enabled status and name.", "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.", "", 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", "", "" ], [ "Alert", "Specifies the name(s) of the SQL Agent alerts to modify. Accepts multiple alert names for bulk operations.\r\nUse this when you need to update specific alerts by name across one or more instances.", "", false, "false", "", "" ], [ "NewName", "Sets a new name for the alert being modified. Only works when modifying a single alert.\r\nUse this when standardizing alert names across environments or fixing naming conventions.", "", false, "false", "", "" ], [ "Enabled", "Enables the specified SQL Agent alert(s) by setting IsEnabled to true.\r\nUse this to reactivate alerts after maintenance or to ensure critical alerts are active across all instances.", "", false, "false", "False", "" ], [ "Disabled", "Disables the specified SQL Agent alert(s) by setting IsEnabled to false.\r\nUse this during maintenance windows or to silence noisy alerts that are firing incorrectly.", "", false, "false", "False", "" ], [ "Force", "Bypasses confirmation prompts by setting ConfirmPreference to \u0027none\u0027.\r\nUse this in automated scripts where you want to suppress interactive prompts.", "", false, "false", "False", "" ], [ "InputObject", "Accepts SQL Agent alert objects from the pipeline, typically from Get-DbaAgentAlert.\r\nUse this when you want to filter alerts first, then modify the results in a 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", "" ], [ "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": [ "Agent", "Job" ], "CommandName": "Set-DbaAgentJob", "Name": "Set-DbaAgentJob", "Author": "Sander Stad (@sqlstad), sqlstad.nl", "Syntax": "Set-DbaAgentJob [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Job] \u003cObject[]\u003e] [[-Schedule] \u003cObject[]\u003e] [[-ScheduleId] \u003cInt32[]\u003e] [[-NewName] \u003cString\u003e] [-Enabled] [-Disabled] [[-Description] \u003cString\u003e] [[-StartStepId] \u003cInt32\u003e] [[-Category] \u003cString\u003e] [[-OwnerLogin] \u003cString\u003e] [[-EventLogLevel] \u003cObject\u003e] [[-EmailLevel] \u003cObject\u003e] [[-NetsendLevel] \u003cObject\u003e] [[-PageLevel] \u003cObject\u003e] [[-EmailOperator] \u003cString\u003e] [[-NetsendOperator] \u003cString\u003e] [[-PageOperator] \u003cString\u003e] [[-DeleteLevel] \u003cObject\u003e] [-Force] [[-InputObject] \u003cJob[]\u003e] [-EnableException] [-WhatIf] [-Confirm] \r\n[\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Agent.Job\nReturns one modified SQL Server Agent job object per job that was successfully updated. The returned object reflects all changes applied during the modification 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 (computer\\instance)\r\n- Name: The name of the SQL Server Agent job\r\n- Enabled: Boolean indicating if the job is enabled for execution\r\n- Description: Description of the job\u0027s purpose\r\n- Owner: SQL Server login that owns the job\r\n- Category: The job category name for organizational grouping\r\n- CurrentRunStatus: Current execution status of the job (Idle, Running, Succeeded, Failed, etc.)\r\n- LastRunDate: DateTime of the most recent job execution attempt\r\n- LastRunOutcome: Outcome of the last execution (Succeeded, Failed, Retry, Cancelled)\r\n- NextRunDate: DateTime when the job is scheduled to run next\r\n- EventLogLevel: Setting for Windows event log notifications (Never, OnSuccess, OnFailure, Always)\nAdditional properties available (from SMO Job object):\r\n- ID: Unique identifier for the job\r\n- JobID: The globally unique identifier (GUID) for the job\r\n- StartStepID: The ID of the step that executes first\r\n- OwnerLoginName: Login name of the job owner\r\n- OperatorToEmail: Email operator for notifications\r\n- OperatorToNetSend: Net send operator for notifications\r\n- OperatorToPage: Pager operator for notifications\r\n- EmailLevel: Email notification setting (0-3 or string equivalent)\r\n- NetSendLevel: Net send notification setting (0-3 or string equivalent)\r\n- PageLevel: Pager notification setting (0-3 or string equivalent)\r\n- DeleteLevel: Auto-delete setting after execution (0-3 or string equivalent)\r\n- DatabaseName: Default database for job steps\r\n- IsSystemObject: Boolean indicating if this is a system-created job\r\n- CreatedDate: DateTime when the job was created\r\n- CreateByLogin: Login that created the job\r\n- DateLastModified: DateTime of the most recent modification\r\n- ModifiedByLogin: Login that made the last modification\r\n- JobSteps: Collection of job steps in this job\r\n- Schedules: Collection of schedules assigned to this job\nAll properties from the base SMO Job object are accessible using Select-Object * even though only default properties are displayed by default.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaAgentJob sql1 -Job Job1 -Disabled\nChanges the job to disabled\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaAgentJob sql1 -Job Job1 -OwnerLogin user1\nChanges the owner of the job\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-DbaAgentJob -SqlInstance sql1 -Job Job1 -EventLogLevel OnSuccess\nChanges the job and sets the notification to write to the Windows Application event log on success\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eSet-DbaAgentJob -SqlInstance sql1 -Job Job1 -EmailLevel OnFailure -EmailOperator dba\nChanges the job and sets the notification to send an e-mail to the e-mail operator\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eSet-DbaAgentJob -SqlInstance sql1 -Job Job1, Job2, Job3 -Enabled\nChanges multiple jobs to enabled\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eSet-DbaAgentJob -SqlInstance sql1, sql2, sql3 -Job Job1, Job2, Job3 -Enabled\nChanges multiple jobs to enabled on multiple servers\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eSet-DbaAgentJob -SqlInstance sql1 -Job Job1 -Description \u0027Just another job\u0027 -Whatif\nDoesn\u0027t Change the job but shows what would happen.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eSet-DbaAgentJob -SqlInstance sql1, sql2, sql3 -Job \u0027Job One\u0027 -Description \u0027Job One\u0027\nChanges a job with the name \"Job1\" on multiple servers to have another description\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003esql1, sql2, sql3 | Set-DbaAgentJob -Job Job1 -Description \u0027Job One\u0027\nChanges a job with the name \"Job1\" on multiple servers to have another description using pipe line", "Description": "Updates various properties of SQL Server Agent jobs including job name, description, owner, enabled/disabled status, notification settings, and schedule assignments. This function lets you modify jobs without using SQL Server Management Studio, making it useful for standardizing job configurations across multiple instances or automating job maintenance tasks. You can update individual jobs or perform bulk changes across multiple jobs and SQL Server instances simultaneously.", "Links": "https://dbatools.io/Set-DbaAgentJob", "Synopsis": "Modifies existing SQL Server Agent job properties and notification settings.", "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.", "", 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", "", "" ], [ "Job", "Specifies the name of the SQL Server Agent job to modify. Accepts wildcards and multiple job names.\r\nUse this to target specific jobs for configuration changes rather than modifying all jobs on an instance.", "", false, "false", "", "" ], [ "Schedule", "Attaches existing shared schedules to the job by name. Accepts multiple schedule names.\r\nUse this when you need to assign predefined schedules to jobs without recreating scheduling logic.", "", false, "false", "", "" ], [ "ScheduleId", "Attaches existing shared schedules to the job by their numeric ID. Accepts multiple schedule IDs.\r\nUse this when you know the specific schedule ID numbers and want to avoid potential name conflicts.", "", false, "false", "", "" ], [ "NewName", "Renames the job to the specified name. The new name must be unique within the SQL Server instance.\r\nUse this when standardizing job names across environments or fixing naming conventions.", "", false, "false", "", "" ], [ "Enabled", "Enables the job so it can be executed by SQL Server Agent schedules or manual execution.\r\nUse this when reactivating disabled jobs or deploying jobs that should run immediately.", "", false, "false", "False", "" ], [ "Disabled", "Disables the job to prevent it from running on schedule or manual execution.\r\nUse this when temporarily stopping jobs during maintenance windows or permanently deactivating obsolete jobs.", "", false, "false", "False", "" ], [ "Description", "Updates the job\u0027s description field with explanatory text about the job\u0027s purpose or functionality.\r\nUse this to document what the job does, when it should run, or special requirements for maintenance teams.", "", false, "false", "", "" ], [ "StartStepId", "Sets which job step should execute first when the job runs. Must correspond to an existing step ID within the job.\r\nUse this when you need to change the job\u0027s execution flow or skip initial steps during testing or maintenance.", "", false, "false", "0", "" ], [ "Category", "Assigns the job to a specific job category for organizational purposes. Creates the category if it doesn\u0027t exist when used with -Force.\r\nUse this to group related jobs together for easier management and reporting in SQL Server Management Studio.", "", false, "false", "", "" ], [ "OwnerLogin", "Changes the job owner to the specified SQL Server login. The login must already exist on the instance.\r\nUse this when reassigning job ownership for security compliance or when the current owner login is being removed.", "", false, "false", "", "" ], [ "EventLogLevel", "Controls when job execution results are logged to the Windows Application Event Log. Values: Never, OnSuccess, OnFailure, Always (or 0-3).\r\nUse this to integrate job monitoring with Windows event log monitoring systems or reduce log noise by only logging failures.", "", false, "false", "", "0,Never,1,OnSuccess,2,OnFailure,3,Always" ], [ "EmailLevel", "Determines when to send email notifications about job completion. Values: Never, OnSuccess, OnFailure, Always (or 0-3).\r\nMust be used with EmailOperator parameter. Use this to set up automated job failure notifications to the DBA team.", "", false, "false", "", "0,Never,1,OnSuccess,2,OnFailure,3,Always" ], [ "NetsendLevel", "Controls when to send network messages (net send) about job completion. Values: Never, OnSuccess, OnFailure, Always (or 0-3).\r\nMust be used with NetsendOperator parameter. Note that net send is deprecated and rarely used in modern environments.", "", false, "false", "", "0,Never,1,OnSuccess,2,OnFailure,3,Always" ], [ "PageLevel", "Determines when to send pager notifications about job completion. Values: Never, OnSuccess, OnFailure, Always (or 0-3).\r\nMust be used with PageOperator parameter. Use this for critical jobs requiring immediate attention when they fail.", "", false, "false", "", "0,Never,1,OnSuccess,2,OnFailure,3,Always" ], [ "EmailOperator", "Specifies which SQL Server Agent operator receives email notifications when EmailLevel conditions are met. The operator must already exist.\r\nUse this to assign job failure notifications to specific DBA team members or distribution lists.", "", false, "false", "", "" ], [ "NetsendOperator", "Specifies which SQL Server Agent operator receives network messages when NetsendLevel conditions are met. The operator must already exist.\r\nRarely used in modern environments due to the deprecation of the net send functionality.", "", false, "false", "", "" ], [ "PageOperator", "Specifies which SQL Server Agent operator receives pager notifications when PageLevel conditions are met. The operator must already exist.\r\nUse this for high-priority jobs where immediate mobile notification is required for on-call DBAs.", "", false, "false", "", "" ], [ "DeleteLevel", "Controls when the job should automatically delete itself after execution. Values: Never, OnSuccess, OnFailure, Always (or 0-3).\r\nUse this for one-time jobs like data migrations or temporary maintenance tasks that should clean up after completion.", "", false, "false", "", "0,Never,1,OnSuccess,2,OnFailure,3,Always" ], [ "Force", "Bypasses validation checks and creates missing job categories when specified with the Category parameter.\r\nUse this when you want to create new categories during job updates without having to pre-create them separately.", "", false, "false", "False", "" ], [ "InputObject", "Accepts SQL Server Agent job objects from the pipeline, typically from Get-DbaAgentJob output.\r\nUse this to chain job operations together or when working with job objects retrieved from other dbatools 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", "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": [ "Agent", "Job", "JobCategory" ], "CommandName": "Set-DbaAgentJobCategory", "Name": "Set-DbaAgentJobCategory", "Author": "Sander Stad (@sqlstad), sqlstad.nl", "Syntax": "Set-DbaAgentJobCategory [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Category] \u003cString[]\u003e] [[-NewName] \u003cString[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Agent.JobCategory\nReturns one job category object per successfully renamed category. The returned object represents the renamed SQL Server Agent job category with updated 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: The name of the job category\r\n- ID: The unique identifier for the job category\r\n- CategoryType: The type of category (LocalJob, MultiServerJob, or DatabaseMaintenance)\nAdditional properties available (from SMO JobCategory object):\r\n- Urn: The Uniform Resource Name of the job category object\r\n- State: The current state of the SMO object (Existing, Creating, Pending, Dropping)\nAll properties from the base SMO JobCategory object are accessible using Select-Object * even though only default properties are displayed by default.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaAgentJobCategory -SqlInstance sql1 -Category \u0027Category 1\u0027 -NewName \u0027Category 2\u0027\nChange the name of the category from \u0027Category 1\u0027 to \u0027Category 2\u0027.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaAgentJobCategory -SqlInstance sql1, sql2 -Category Category1, Category2 -NewName cat1, cat2\nRename multiple jobs in one go on multiple servers.", "Description": "Renames existing SQL Server Agent job categories by updating their names in the msdb database. This is particularly useful for standardizing job category naming conventions across multiple environments or correcting categories that were created with inconsistent names. The function validates that source categories exist and prevents renaming to names that already exist, helping maintain clean job organization within SQL Server Agent.", "Links": "https://dbatools.io/Set-DbaAgentJobCategory", "Synopsis": "Renames SQL Server Agent job categories to standardize naming conventions across 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 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", "", "" ], [ "Category", "Specifies the existing job category name(s) to rename. The category must already exist in the SQL Server Agent on the target instance.\r\nUse this to identify which job categories need standardized naming across your environment.", "", false, "false", "", "" ], [ "NewName", "Specifies the new name(s) for the job category. The new name cannot already exist on the target instance.\r\nWhen renaming multiple categories, provide names in the same order as the Category parameter values.", "", false, "false", "", "" ], [ "Force", "Bypasses confirmation prompts and performs the rename operation without asking for user confirmation.\r\nUse this when scripting bulk category renames where manual confirmation would be impractical.", "", 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": [ "Agent", "Job", "SqlAgent" ], "CommandName": "Set-DbaAgentJobOutputFile", "Name": "Set-DbaAgentJobOutputFile", "Author": "Rob Sewell, sqldbawithabeard.com", "Syntax": "Set-DbaAgentJobOutputFile [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Job \u003cObject[]\u003e] [-Step \u003cObject[]\u003e] -OutputFile \u003cString\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per job step that was successfully updated with the new output file configuration. No output is returned if the operation fails or is cancelled via -WhatIf.\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- Job: The SQL Agent job name containing the step\r\n- JobStep: The name of the job step that was updated\r\n- OutputFileName: The new output file path that was set\r\n- OldOutputFileName: The previous output file path before the change", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaAgentJobOutputFile -SqlInstance SERVERNAME -Job \u0027The Agent Job\u0027 -OutPutFile E:\\Logs\\AgentJobStepOutput.txt\nSets the Job step for The Agent job on SERVERNAME to E:\\Logs\\AgentJobStepOutput.txt", "Description": "Modifies the output file location where SQL Server Agent writes job step execution details, error messages, and command output. This centralizes logging for troubleshooting failed jobs, monitoring step execution, and maintaining audit trails without manually editing each job step through SQL Server Management Studio. When no specific step is provided, an interactive selection interface appears for jobs with multiple steps.", "Links": "https://dbatools.io/Set-DbaAgentJobOutputFile", "Synopsis": "Configures the output file path for SQL Server Agent job steps to capture step execution logs.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or 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 (ByValue, ByPropertyName)", "", "" ], [ "Job", "Specifies the SQL Server Agent job name whose step output files you want to configure.\nUse this to target specific jobs that need centralized logging or troubleshooting. This parameter is not officially mandatory, but you will always be asked to provide a job if you have not.", "", false, "false", "", "" ], [ "Step", "Specifies which job step(s) within the target job should have their output file configured.\nUse this when you only want to set output files for specific steps in multi-step jobs. Step names are unique within each job, making this a reliable way to target individual steps. If omitted and the \r\njob has multiple steps, an interactive GUI will appear for step selection.", "", false, "true (ByValue, ByPropertyName)", "", "" ], [ "OutputFile", "Specifies the complete file path where SQL Agent should write job step execution output and error messages.\nUse this to centralize job logging in a location accessible for troubleshooting and monitoring. The path must be accessible by the SQL Server service account and should include the filename with \r\nextension.", "", true, "true (ByValue, ByPropertyName)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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": [ "Agent", "Job" ], "CommandName": "Set-DbaAgentJobOwner", "Name": "Set-DbaAgentJobOwner", "Author": "Michael Fal (@Mike_Fal), mikefal.net", "Syntax": "Set-DbaAgentJobOwner [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Job] \u003cObject[]\u003e] [[-ExcludeJob] \u003cObject[]\u003e] [[-InputObject] \u003cJob[]\u003e] [[-Login] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Agent.Job\nReturns one Job object per SQL Agent job processed, with added connection context and operation 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 SQL Agent job name\r\n- Category: The job category\r\n- OwnerLoginName: The login name that owns the job (updated if operation was successful)\r\n- Status: Operation result status (Skipped, Failed, or Successful)\r\n- Notes: Additional information about the operation result (reason for skip/failure, empty on success)\nAll properties from the base SMO Job object are accessible using Select-Object *. The output includes all original SMO Job properties plus the added connection context properties and status \r\ninformation.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaAgentJobOwner -SqlInstance localhost\nSets SQL Agent Job owner to sa on all jobs where the owner does not match sa.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaAgentJobOwner -SqlInstance localhost -Login DOMAIN\\account\nSets SQL Agent Job owner to \u0027DOMAIN\\account\u0027 on all jobs where the owner does not match \u0027DOMAIN\\account\u0027. Note\r\nthat Login must be a valid security principal that exists on the target server.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-DbaAgentJobOwner -SqlInstance localhost -Job job1, job2\nSets SQL Agent Job owner to \u0027sa\u0027 on the job1 and job2 jobs if their current owner does not match \u0027sa\u0027.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e\u0027sqlserver\u0027,\u0027sql2016\u0027 | Set-DbaAgentJobOwner\nSets SQL Agent Job owner to sa on all jobs where the owner does not match sa on both sqlserver and sql2016.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaAgentJob -SqlInstance vmsql | Where-Object OwnerLoginName -eq login1 | Set-DbaAgentJobOwner -TargetLogin login2 | Out-Gridview\nSets SQL Agent Job owner to login2 where their current owner is login1 on instance vmsql. Send result to gridview.", "Description": "This function standardizes SQL Agent job ownership by updating jobs that don\u0027t match a specified owner login. It\u0027s commonly used for security compliance, post-migration cleanup, and environment standardization where consistent job ownership is required.\n\nBy default, jobs are reassigned to the \u0027sa\u0027 account (or the renamed sysadmin account if \u0027sa\u0027 was renamed), but you can specify any valid login. The function automatically detects renamed \u0027sa\u0027 accounts by finding the login with ID 1.\n\nOnly local (non-MultiServer) jobs are processed by default, though you can target specific jobs or exclude certain ones. The function validates that the target login exists and prevents assignment to Windows groups, which cannot own SQL Agent jobs.\n\nJobs already owned by the target login are skipped, and detailed status information is returned for each job processed.\n\nBest practice reference: https://www.itprotoday.com/sql-server-tip-assign-ownership-jobs-sysadmin-account", "Links": "https://dbatools.io/Set-DbaAgentJobOwner", "Synopsis": "Updates SQL Server Agent job ownership to ensure jobs are owned by a specific login", "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", "", "" ], [ "Job", "Specifies which SQL Agent jobs to update ownership for. Accepts job names as strings and supports tab completion from the target server.\r\nUse this when you need to update ownership for specific jobs rather than processing all jobs on the instance.", "Jobs", false, "false", "", "" ], [ "ExcludeJob", "Specifies SQL Agent jobs to skip during the ownership update process. Accepts job names as strings with tab completion.\r\nUseful for excluding critical jobs or jobs that must retain their current ownership for security or operational reasons.", "", false, "false", "", "" ], [ "InputObject", "Accepts SQL Agent job objects from the pipeline, typically from Get-DbaAgentJob output.\r\nUse this for advanced filtering scenarios where you need to process jobs based on complex criteria like owner, category, or schedule properties.", "", false, "true (ByValue)", "", "" ], [ "Login", "Specifies the target login account that should own the SQL Agent jobs. Defaults to \u0027sa\u0027 or automatically detects the renamed sysadmin account (login ID 1).\r\nMust be a valid SQL login or Windows account that exists on the server. Cannot be a Windows group as they cannot own SQL Agent jobs.", "TargetLogin", 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": [ "Agent", "Job", "JobStep" ], "CommandName": "Set-DbaAgentJobStep", "Name": "Set-DbaAgentJobStep", "Author": "Sander Stad (@sqlstad), sqlstad.nl", "Syntax": "Set-DbaAgentJobStep [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Job] \u003cObject[]\u003e] [[-StepName] \u003cString\u003e] [[-NewName] \u003cString\u003e] [[-Subsystem] \u003cString\u003e] [[-SubsystemServer] \u003cString\u003e] [[-Command] \u003cString\u003e] [[-CmdExecSuccessCode] \u003cInt32\u003e] [[-OnSuccessAction] \u003cString\u003e] [[-OnSuccessStepId] \u003cInt32\u003e] [[-OnFailAction] \u003cString\u003e] [[-OnFailStepId] \u003cInt32\u003e] [[-Database] \u003cString\u003e] [[-DatabaseUser] \u003cString\u003e] [[-RetryAttempts] \u003cInt32\u003e] [[-RetryInterval] \u003cInt32\u003e] [[-OutputFileName] \u003cString\u003e] [[-Flag] \u003cString[]\u003e] [[-ProxyName] \u003cString\u003e] [[-InputObject] \u003cServer[]\u003e] \r\n[-EnableException] [-Force] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Agent.JobStep\nReturns one modified JobStep object for each job step updated or created. The object is returned after all changes have been committed to the SQL Server instance.\nWhen using -Force, creates new job steps if they don\u0027t exist. When updating existing steps, returns the modified JobStep with all changes applied.\nAll SMO JobStep object properties are accessible and reflect the modifications made by this function, including:\r\n- Name: Job step name\r\n- ID: Job step ID within the job\r\n- Subsystem: Type of subsystem used (TransactSql, CmdExec, PowerShell, Ssis, etc.)\r\n- Command: Command or script to execute\r\n- DatabaseName: Database context for T-SQL steps\r\n- DatabaseUserName: User account for T-SQL step execution\r\n- CommandExecutionSuccessCode: Expected return code for success (CmdExec subsystem)\r\n- OnSuccessAction: Action to perform if step succeeds (QuitWithSuccess, QuitWithFailure, GoToNextStep, GoToStep)\r\n- OnSuccessStep: Target step ID for GoToStep success action\r\n- OnFailAction: Action to perform if step fails (QuitWithFailure, QuitWithSuccess, GoToNextStep, GoToStep)\r\n- OnFailStep: Target step ID for GoToStep failure action\r\n- RetryAttempts: Number of retry attempts on failure\r\n- RetryInterval: Minutes between retry attempts\r\n- OutputFileName: File path for step output\r\n- ProxyName: SQL Agent proxy account name\r\n- JobStepFlags: Output flags (AppendToJobHistory, AppendToLogFile, etc.)\r\n- CreateDate: DateTime when step was created\r\n- LastModifiedDate: DateTime when step was last modified", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaAgentJobStep -SqlInstance sql1 -Job Job1 -StepName Step1 -NewName Step2\nChanges the name of the step in \"Job1\" with the name Step1 to Step2\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaAgentJobStep -SqlInstance sql1 -Job Job1 -StepName Step1 -Database msdb\nChanges the database of the step in \"Job1\" with the name Step1 to msdb\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-DbaAgentJobStep -SqlInstance sql1 -Job Job1, Job2 -StepName Step1 -Database msdb\nChanges job steps in multiple jobs with the name Step1 to msdb\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eSet-DbaAgentJobStep -SqlInstance sql1, sql2, sql3 -Job Job1, Job2 -StepName Step1 -Database msdb\nChanges job steps in multiple jobs on multiple servers with the name Step1 to msdb\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eSet-DbaAgentJobStep -SqlInstance sql1, sql2, sql3 -Job Job1 -StepName Step1 -Database msdb\nChanges the database of the step in \"Job1\" with the name Step1 to msdb for multiple servers\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003esql1, sql2, sql3 | Set-DbaAgentJobStep -Job Job1 -StepName Step1 -Database msdb\nChanges the database of the step in \"Job1\" with the name Step1 to msdb for multiple servers using pipeline\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003e$jobStep = @{\nSqlInstance = sqldev01\r\n Job = dbatools1\r\n StepName = \"Step 2\"\r\n Subsystem = \"CmdExec\"\r\n Command = \"enter command text here\"\r\n CmdExecSuccessCode = 0\r\n OnSuccessAction = \"GoToStep\"\r\n OnSuccessStepId = 1\r\n OnFailAction = \"GoToStep\"\r\n OnFailStepId = 1\r\n Database = TestDB\r\n RetryAttempts = 2\r\n RetryInterval = 5\r\n OutputFileName = \"logCmdExec.txt\"\r\n Flag = [Microsoft.SqlServer.Management.Smo.Agent.JobStepFlags]::AppendAllCmdExecOutputToJobHistory\r\n ProxyName = \"dbatoolsci_proxy_1\"\r\n Force = $true\r\n }\nPS C:\\\u003e$newJobStep = Set-DbaAgentJobStep @jobStep\nUpdates or creates a new job step named Step 2 in the dbatools1 job on the sqldev01 instance. The subsystem is set to CmdExec and uses a proxy.", "Description": "Modifies SQL Agent job step properties including commands, subsystems, retry logic, success/failure actions, and execution context. Updates existing job steps by name or creates new steps when using the -Force parameter, eliminating the need to manually edit job steps through SSMS.\n\nCommon use cases include changing job step commands during deployments, updating database contexts when moving jobs between environments, modifying retry settings for intermittent failures, and adjusting success/failure flow logic. The function supports all major subsystems including T-SQL, PowerShell, SSIS, CmdExec, and Analysis Services commands.\n\nNote: ActiveScripting (ActiveX scripting) was discontinued in SQL Server 2016: https://docs.microsoft.com/en-us/sql/database-engine/discontinued-database-engine-functionality-in-sql-server", "Links": "https://dbatools.io/Set-DbaAgentJobStep", "Synopsis": "Modifies properties of existing SQL Agent job steps or creates new ones with Force parameter.", "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.", "", 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", "", "" ], [ "Job", "The name of the job or the job object itself.", "", false, "false", "", "" ], [ "StepName", "The name of the step.", "", false, "false", "", "" ], [ "NewName", "The new name for the step in case it needs to be renamed.", "", false, "false", "", "" ], [ "Subsystem", "The subsystem used by the SQL Server Agent service to execute command.\r\nAllowed values \u0027ActiveScripting\u0027,\u0027AnalysisCommand\u0027,\u0027AnalysisQuery\u0027,\u0027CmdExec\u0027,\u0027Distribution\u0027,\u0027LogReader\u0027,\u0027Merge\u0027,\u0027PowerShell\u0027,\u0027QueueReader\u0027,\u0027Snapshot\u0027,\u0027Ssis\u0027,\u0027TransactSql\u0027", "", false, "false", "", "ActiveScripting,AnalysisCommand,AnalysisQuery,CmdExec,Distribution,LogReader,Merge,PowerShell,QueueReader,Snapshot,Ssis,TransactSql" ], [ "SubsystemServer", "The subsystems AnalysisScripting, AnalysisCommand, AnalysisQuery require a server.", "", false, "false", "", "" ], [ "Command", "The commands to be executed by the SQLServerAgent service through the subsystem.", "", false, "false", "", "" ], [ "CmdExecSuccessCode", "The value returned by a CmdExec subsystem command to indicate that command executed successfully.", "", false, "false", "0", "" ], [ "OnSuccessAction", "The action to perform if the step succeeds.\r\nAllowed values \"QuitWithSuccess\" (default), \"QuitWithFailure\", \"GoToNextStep\", \"GoToStep\".\r\nThe text value van either be lowercase, uppercase or something in between as long as the text is correct.", "", false, "false", "", "QuitWithSuccess,QuitWithFailure,GoToNextStep,GoToStep" ], [ "OnSuccessStepId", "The ID of the step in this job to execute if the step succeeds and OnSuccessAction is \"GoToNextStep\".", "", false, "false", "0", "" ], [ "OnFailAction", "The action to perform if the step fails.\r\nAllowed values \"QuitWithFailure\" (default), \"QuitWithSuccess\", \"GoToNextStep\", \"GoToStep\".\r\nThe text value van either be lowercase, uppercase or something in between as long as the text is correct.", "", false, "false", "", "QuitWithSuccess,QuitWithFailure,GoToNextStep,GoToStep" ], [ "OnFailStepId", "The ID of the step in this job to execute if the step fails and OnFailAction is \"GoToNextStep\".", "", false, "false", "0", "" ], [ "Database", "The name of the database in which to execute a Transact-SQL step.", "", false, "false", "", "" ], [ "DatabaseUser", "The name of the user account to use when executing a Transact-SQL step.", "", false, "false", "", "" ], [ "RetryAttempts", "The number of retry attempts to use if this step fails.", "", false, "false", "0", "" ], [ "RetryInterval", "The amount of time in minutes between retry attempts.", "", false, "false", "0", "" ], [ "OutputFileName", "The name of the file in which the output of this step is saved.", "", false, "false", "", "" ], [ "Flag", "Sets the flag(s) for the job step.\nFlag Description\r\n----------------------------------------------------------------------------\r\nAppendAllCmdExecOutputToJobHistory Job history, including command output, is appended to the job history file.\r\nAppendToJobHistory Job history is appended to the job history file.\r\nAppendToLogFile Job history is appended to the SQL Server log file.\r\nAppendToTableLog Job history is appended to a log table.\r\nLogToTableWithOverwrite Job history is written to a log table, overwriting previous contents.\r\nNone Job history is not appended to a file.\r\nProvideStopProcessEvent Job processing is stopped.", "", false, "false", "", "AppendAllCmdExecOutputToJobHistory,AppendToJobHistory,AppendToLogFile,AppendToTableLog,LogToTableWithOverwrite,None,ProvideStopProcessEvent" ], [ "ProxyName", "The name of the proxy that the job step runs as.", "", false, "false", "", "" ], [ "InputObject", "Allows pipeline input from Connect-DbaInstance.", "", 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", "" ], [ "Force", "The force parameter will ignore some errors in the parameters and assume defaults.", "", 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": [ "Agent", "Operator" ], "CommandName": "Set-DbaAgentOperator", "Name": "Set-DbaAgentOperator", "Author": "Tracy Boggiano (@TracyBoggiano), databasesuperhero.com", "Syntax": "Set-DbaAgentOperator [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Operator] \u003cString[]\u003e] [[-Name] \u003cString\u003e] [[-EmailAddress] \u003cString\u003e] [[-NetSendAddress] \u003cString\u003e] [[-PagerAddress] \u003cString\u003e] [[-PagerDay] \u003cString\u003e] [[-SaturdayStartTime] \u003cString\u003e] [[-SaturdayEndTime] \u003cString\u003e] [[-SundayStartTime] \u003cString\u003e] [[-SundayEndTime] \u003cString\u003e] [[-WeekdayStartTime] \u003cString\u003e] [[-WeekdayEndTime] \u003cString\u003e] [-IsFailsafeOperator] [[-FailsafeNotificationMethod] \u003cString[]\u003e] [[-InputObject] \u003cOperator[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Agent.Operator\nReturns one modified Operator object for each operator updated. The object is returned after all changes have been committed to the SQL Server instance.\nAll SMO Operator object properties are accessible and reflect the modifications made by this function, including:\r\n- EmailAddress: Email address for notifications\r\n- NetSendAddress: Network computer name for net send notifications\r\n- PagerAddress: Pager email address for urgent notifications\r\n- PagerDays: Bitmask value indicating days pager is active\r\n- SaturdayPagerStartTime: Time when Saturday pager notifications begin (HH:MM:SS format)\r\n- SaturdayPagerEndTime: Time when Saturday pager notifications end (HH:MM:SS format)\r\n- SundayPagerStartTime: Time when Sunday pager notifications begin (HH:MM:SS format)\r\n- SundayPagerEndTime: Time when Sunday pager notifications end (HH:MM:SS format)\r\n- WeekdayPagerStartTime: Time when weekday pager notifications begin (HH:MM:SS format)\r\n- WeekdayPagerEndTime: Time when weekday pager notifications end (HH:MM:SS format)\r\n- Name: Operator name\r\n- LastNotificationTime: DateTime of last operator notification\r\n- ID: Unique operator identifier", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaAgentOperator -SqlInstance sql01 -Operator DBA -EmailAddress operator@operator.com -PagerDay Everyday\nThis sets the operator named DBA with the above email address with default values to alerts everyday for all hours of the day.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaAgentOperator -SqlInstance sql01 -Operator DBA -EmailAddress operator@operator.com `\n\u003e\u003e -NetSendAddress dbauser1 -PagerAddress dbauser1@pager.dbatools.io -PagerDay Everyday `\r\n\u003e\u003e -SaturdayStartTime 070000 -SaturdayEndTime 180000 -SundayStartTime 080000 `\r\n\u003e\u003e -SundayEndTime 170000 -WeekdayStartTime 060000 -WeekdayEndTime 190000\nCreates a new operator named DBA on the sql01 instance with email address operator@operator.com, net send address of dbauser1, pager address of dbauser1@pager.dbatools.io, page day as every day, \r\nSaturday start time of 7am, Saturday end time of 6pm, Sunday start time of 8am, Sunday end time of 5pm, Weekday start time of 6am, and Weekday end time of 7pm.", "Description": "Modifies existing SQL Agent operators by updating their contact information, pager notification schedules, and failsafe operator configuration. This lets you change email addresses, pager contacts, net send addresses, and specify when pager notifications should be active without having to manually update operators through SQL Server Management Studio. You can also designate an operator as the failsafe operator that receives notifications when the primary assigned operators are unavailable.", "Links": "https://dbatools.io/Set-DbaAgentOperator", "Synopsis": "Modifies existing SQL Agent operator contact details, pager schedules, and failsafe settings.", "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", "", "" ], [ "Operator", "Specifies the name of the existing SQL Agent operator to modify. Use this when targeting a specific operator by name instead of piping operator objects.", "", false, "false", "", "" ], [ "Name", "Renames the operator to the specified value. Use this when you need to change an operator\u0027s name while preserving all other settings and alert assignments.", "", false, "false", "", "" ], [ "EmailAddress", "Sets the email address where SQL Agent will send email notifications for this operator. This is the primary contact method for most alert notifications and job failure messages.", "", false, "false", "", "" ], [ "NetSendAddress", "Specifies the network computer name for net send notifications. This legacy notification method sends popup messages to Windows computers on the same network domain.", "", false, "false", "", "" ], [ "PagerAddress", "Sets the pager email address for urgent notifications. Typically used for SMS gateways or mobile email addresses when immediate notification is required outside normal business hours.", "", false, "false", "", "" ], [ "PagerDay", "Controls which days pager notifications are active for this operator. Use \u0027Weekdays\u0027 for business hours coverage, \u0027Weekend\u0027 for off-hours support, or specific days for rotating on-call schedules.\r\nValid values are \u0027EveryDay\u0027, \u0027Weekdays\u0027, \u0027Weekend\u0027, \u0027Sunday\u0027, \u0027Monday\u0027, \u0027Tuesday\u0027, \u0027Wednesday\u0027, \u0027Thursday\u0027, \u0027Friday\u0027, and \u0027Saturday\u0027.", "", false, "false", "", "EveryDay,Weekdays,Weekend,Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday" ], [ "SaturdayStartTime", "Sets when pager notifications begin on Saturday in HHMMSS format (e.g., \u0027080000\u0027 for 8:00 AM). Use this to define weekend on-call coverage hours for the operator.", "", false, "false", "", "" ], [ "SaturdayEndTime", "Sets when pager notifications end on Saturday in HHMMSS format (e.g., \u0027180000\u0027 for 6:00 PM). Notifications outside this window will use email instead of pager for the operator.", "", false, "false", "", "" ], [ "SundayStartTime", "Sets when pager notifications begin on Sunday in HHMMSS format (e.g., \u0027080000\u0027 for 8:00 AM). Use this to define weekend on-call coverage hours for the operator.", "", false, "false", "", "" ], [ "SundayEndTime", "Sets when pager notifications end on Sunday in HHMMSS format (e.g., \u0027170000\u0027 for 5:00 PM). Notifications outside this window will use email instead of pager for the operator.", "", false, "false", "", "" ], [ "WeekdayStartTime", "Sets when pager notifications begin on weekdays (Monday-Friday) in HHMMSS format (e.g., \u0027060000\u0027 for 6:00 AM). Use this to define business hours pager coverage for the operator.", "", false, "false", "", "" ], [ "WeekdayEndTime", "Sets when pager notifications end on weekdays (Monday-Friday) in HHMMSS format (e.g., \u0027190000\u0027 for 7:00 PM). Notifications outside this window will use email instead of pager for the operator.", "", false, "false", "", "" ], [ "IsFailsafeOperator", "Designates this operator as the failsafe operator who receives notifications when primary operators are unavailable. Only one failsafe operator can exist per SQL Server instance, so this replaces any \r\nexisting failsafe operator.", "", false, "false", "False", "" ], [ "FailsafeNotificationMethod", "Specifies how the failsafe operator receives notifications when primary operators cannot be reached. Use \u0027NotifyEmail\u0027 for standard alerts, \u0027Pager\u0027 for urgent notifications, or \u0027NotifyAll\u0027 for \r\nmaximum coverage.\r\nValid values are \u0027None\u0027, \u0027NotifyEmail\u0027, \u0027Pager\u0027, \u0027NetSend\u0027, \u0027NotifyAll\u0027. Multiple methods can be combined except \u0027None\u0027 and \u0027NotifyAll\u0027 which must be used alone.", "", false, "false", "NotifyEmail", "None,NotifyEmail,Pager,NetSend,NotifyAll" ], [ "InputObject", "Accepts SQL Agent operator objects from the pipeline, typically from Get-DbaAgentOperator. Use this to modify multiple operators or when working with operator objects 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", "" ], [ "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": [ "Agent", "Job", "JobStep" ], "CommandName": "Set-DbaAgentSchedule", "Name": "Set-DbaAgentSchedule", "Author": "Sander Stad (@sqlstad, sqlstad.nl)", "Syntax": "Set-DbaAgentSchedule [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Job] \u003cObject[]\u003e [-Schedule] \u003cString\u003e [[-NewName] \u003cString\u003e] [-Enabled] [-Disabled] [[-FrequencyType] \u003cObject\u003e] [[-FrequencyInterval] \u003cObject[]\u003e] [[-FrequencySubdayType] \u003cObject\u003e] [[-FrequencySubdayInterval] \u003cInt32\u003e] [[-FrequencyRelativeInterval] \u003cObject\u003e] [[-FrequencyRecurrenceFactor] \u003cInt32\u003e] [[-StartDate] \u003cString\u003e] [[-EndDate] \u003cString\u003e] [[-StartTime] \u003cString\u003e] [[-EndTime] \u003cString\u003e] [-EnableException] [-Force] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Agent.JobSchedule\nReturns the updated JobSchedule object(s) for the modified schedule(s). When multiple jobs or multiple instances are modified, one object is returned per modified schedule.\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 schedule\r\n- Enabled/IsEnabled: Boolean indicating if the schedule is active\r\n- FrequencyTypes: Schedule frequency type (Once, Daily, Weekly, Monthly, MonthlyRelative, AgentStart, OnIdle)\r\n- FrequencyInterval: The interval at which the schedule runs based on frequency type\r\n- FrequencySubDayTypes: Sub-daily frequency unit (Once, Seconds, Minutes, Hours)\r\n- FrequencySubDayInterval: Number of sub-daily frequency units between executions\r\n- ActiveStartDate: The date when the schedule becomes active\r\n- ActiveEndDate: The date when the schedule stops being active\r\n- ActiveStartTimeOfDay: The daily start time for job execution\r\n- ActiveEndTimeOfDay: The daily end time for job execution\nAdditional properties available (from SMO JobSchedule object):\r\n- ScheduleUid: Unique identifier for the schedule\r\n- FrequencyRelativeIntervals: Relative frequency interval for monthly schedules (First, Second, Third, Fourth, Last)\r\n- FrequencyRecurrenceFactor: Number of weeks or months between schedule occurrences\r\n- JobCount: Number of jobs using this schedule\r\n- Parent: Reference to the parent JobServer object\r\n- Urn: The Uniform Resource Name of the schedule object\r\n- CreateDate: DateTime when the schedule was created\r\n- DateLastModified: DateTime when the schedule was last modified\nAll properties from the base SMO JobSchedule object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaAgentSchedule -SqlInstance sql1 -Job Job1 -Schedule daily -Enabled\nChanges the schedule for Job1 with the name \u0027daily\u0027 to enabled\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaAgentSchedule -SqlInstance sql1 -Job Job1 -Schedule daily -NewName weekly -FrequencyType Weekly -FrequencyInterval Monday, Wednesday, Friday\nChanges the schedule for Job1 with the name daily to have a new name weekly\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-DbaAgentSchedule -SqlInstance sql1 -Job Job1, Job2, Job3 -Schedule daily -StartTime \u0027230000\u0027\nChanges the start time of the schedule for Job1 to 11 PM for multiple jobs\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eSet-DbaAgentSchedule -SqlInstance sql1, sql2, sql3 -Job Job1 -Schedule daily -Enabled\nChanges the schedule for Job1 with the name daily to enabled on multiple servers\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003esql1, sql2, sql3 | Set-DbaAgentSchedule -Job Job1 -Schedule daily -Enabled\nChanges the schedule for Job1 with the name \u0027daily\u0027 to enabled on multiple servers using pipe line", "Description": "Modifies the timing, frequency, and other properties of existing SQL Agent job schedules without recreating them. You can update schedule frequency (daily, weekly, monthly), change start/end times and dates, enable or disable schedules, and rename them. The function works with schedules already attached to jobs and validates all timing parameters to prevent invalid configurations.", "Links": "https://dbatools.io/Set-DbaAgentSchedule", "Synopsis": "Modifies properties of existing SQL Agent job schedules", "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", "", "" ], [ "Job", "Specifies the name of the SQL Agent job that contains the schedule to modify. You can provide multiple job names to update schedules across different jobs.\r\nUse this when you need to change schedule properties for specific jobs without affecting other jobs that might share the same schedule name.", "", true, "true (ByValue)", "", "" ], [ "Schedule", "Specifies the name of the existing schedule to modify within the specified job. Schedule names are case-sensitive.\r\nUse this to target the specific schedule when a job has multiple schedules attached to it.", "ScheduleName", true, "true (ByValue)", "", "" ], [ "NewName", "Renames the schedule to the specified new name. The new name must be unique within the job\u0027s schedules.\r\nUse this when you need to rename schedules for better organization or to follow naming conventions.", "", false, "false", "", "" ], [ "Enabled", "Activates the schedule so the job will run according to its configured timing. This overrides any disabled state.\r\nUse this to reactivate schedules that were previously disabled without changing their timing configuration.", "", false, "false", "False", "" ], [ "Disabled", "Deactivates the schedule so the job will not run, even if it meets the timing criteria. The schedule configuration remains unchanged.\r\nUse this to temporarily stop jobs without deleting their schedules during maintenance windows or troubleshooting.", "", false, "false", "False", "" ], [ "FrequencyType", "Sets the overall pattern for when the job should execute. This is the primary schedule type that determines how often the job runs.\r\nUse \u0027Daily\u0027 for jobs that run every day or every few days, \u0027Weekly\u0027 for jobs on specific weekdays, \u0027Monthly\u0027 for jobs on specific dates, \u0027MonthlyRelative\u0027 for jobs like \"first Monday of the month\", \r\n\u0027Once\u0027 for one-time execution, \u0027AgentStart\u0027 to run when SQL Agent starts, or \u0027OnIdle\u0027 when server is idle.\r\nThis parameter works with FrequencyInterval to create the complete schedule pattern.", "", false, "false", "", "Once,OneTime,Daily,Weekly,Monthly,MonthlyRelative,AgentStart,AutoStart,IdleComputer,OnIdle,1,4,8,16,32,64,128" ], [ "FrequencyInterval", "Specifies which days or intervals the job should run based on the FrequencyType. The values depend on the schedule type you choose.\r\nFor \u0027Daily\u0027: Use a number (1-365) for every N days or \u0027EveryDay\u0027. For \u0027Weekly\u0027: Use day names like Monday, Tuesday or shortcuts like \u0027Weekdays\u0027, \u0027Weekend\u0027. For \u0027Monthly\u0027: Use day numbers 1-31. For \r\n\u0027MonthlyRelative\u0027: Use day names for \"first Monday\" type schedules.\r\nThis parameter works together with FrequencyType to define the exact timing pattern for your job schedule.", "", false, "false", "", "" ], [ "FrequencySubdayType", "Defines the unit of time for running jobs multiple times within a single day. This controls what the FrequencySubdayInterval value represents.\r\nUse \u0027Once\u0027 for jobs that run only once per day, \u0027Hours\u0027 for jobs that repeat every few hours, \u0027Minutes\u0027 for jobs that run every few minutes, or \u0027Seconds\u0027 for very frequent execution.\r\nThis parameter is only relevant when you need jobs to execute more than once per day at regular intervals.", "", false, "false", "", "1,Once,Time,2,Seconds,Second,4,Minutes,Minute,8,Hours,Hour" ], [ "FrequencySubdayInterval", "Specifies how many units of the FrequencySubdayType to wait between job executions within a day. For example, 2 with \u0027Hours\u0027 means every 2 hours.\r\nUse this to control the frequency of recurring jobs throughout the day, such as every 15 minutes for monitoring jobs or every 4 hours for maintenance tasks.\r\nValid ranges are 1-59 for seconds/minutes and 1-23 for hours.", "", false, "false", "0", "" ], [ "FrequencyRelativeInterval", "Specifies which occurrence of the day within the month for MonthlyRelative schedules. Controls whether you want the first, second, third, fourth, or last occurrence.\r\nUse this for schedules like \"first Monday of every month\" (First + Monday) or \"last Friday of every month\" (Last + Friday). Only applies when FrequencyType is \u0027MonthlyRelative\u0027.\r\nCommon values are \u0027First\u0027, \u0027Second\u0027, \u0027Third\u0027, \u0027Fourth\u0027, or \u0027Last\u0027.", "", false, "false", "", "Unused,First,Second,Third,Fourth,Last" ], [ "FrequencyRecurrenceFactor", "Controls how often the schedule repeats by specifying the interval between occurrences. For weekly schedules, this is the number of weeks between runs; for monthly schedules, it\u0027s the number of \r\nmonths.\r\nUse this to create schedules like \"every 2 weeks on Monday\" (FrequencyRecurrenceFactor=2) or \"every 3 months on the 15th\" (FrequencyRecurrenceFactor=3). Only applies to Weekly, Monthly, and \r\nMonthlyRelative frequency types.\r\nMust be at least 1, and is commonly used for less frequent maintenance tasks or reports.", "", false, "false", "0", "" ], [ "StartDate", "Sets the earliest date when the schedule becomes active and the job can start running. Must be in yyyyMMdd format (e.g., \u002720240315\u0027).\r\nUse this to delay job execution until a future date or to replace an existing start date. The schedule will not run before this date even if other timing conditions are met.", "", false, "false", "", "" ], [ "EndDate", "Sets the last date when the schedule will be active and can execute the job. Must be in yyyyMMdd format and cannot be before StartDate.\r\nUse this to automatically disable schedules after a specific date, useful for temporary jobs or time-limited maintenance tasks. After this date, the schedule remains but will not execute.", "", false, "false", "", "" ], [ "StartTime", "Sets the daily start time when the job can begin executing, using 24-hour format HHMMSS (e.g., \u0027080000\u0027 for 8:00 AM, \u0027143000\u0027 for 2:30 PM).\r\nUse this to schedule jobs during specific maintenance windows or business hours. For jobs with subday frequency, this is when the recurring pattern starts each day.", "", false, "false", "", "" ], [ "EndTime", "Sets the daily end time when the job can no longer start executing, using 24-hour format HHMMSS (e.g., \u0027180000\u0027 for 6:00 PM, \u0027235959\u0027 for just before midnight).\r\nUse this to prevent jobs from starting during peak business hours or to ensure long-running jobs complete before critical operations begin. For recurring jobs, this stops new executions but doesn\u0027t \r\nkill running jobs.", "", 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", "" ], [ "Force", "Bypasses some parameter validation errors by applying sensible defaults and removes any existing schedules with the same name before creating new ones.\r\nUse this when you want to overwrite existing schedules or when working with edge cases where strict validation might prevent legitimate schedule modifications.\r\nBe cautious as this can remove existing schedules without prompting.", "", 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": [ "Agent", "Server" ], "CommandName": "Set-DbaAgentServer", "Name": "Set-DbaAgentServer", "Author": "Claudio Silva (@claudioessilva), claudioessilva.com", "Syntax": "Set-DbaAgentServer [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-InputObject] \u003cJobServer[]\u003e] [[-AgentLogLevel] \u003cObject\u003e] [[-AgentMailType] \u003cObject\u003e] [[-AgentShutdownWaitTime] \u003cInt32\u003e] [[-DatabaseMailProfile] \u003cString\u003e] [[-ErrorLogFile] \u003cString\u003e] [[-IdleCpuDuration] \u003cInt32\u003e] [[-IdleCpuPercentage] \u003cInt32\u003e] [[-CpuPolling] \u003cString\u003e] [[-LocalHostAlias] \u003cString\u003e] [[-LoginTimeout] \u003cInt32\u003e] [[-MaximumHistoryRows] \u003cInt32\u003e] [[-MaximumJobHistoryRows] \u003cInt32\u003e] [[-NetSendRecipient] \u003cString\u003e] [[-ReplaceAlertTokens] \u003cString\u003e] [[-SaveInSentFolder] \u003cString\u003e] \r\n[[-SqlAgentAutoStart] \u003cString\u003e] [[-SqlAgentMailProfile] \u003cString\u003e] [[-SqlAgentRestart] \u003cString\u003e] [[-SqlServerRestart] \u003cString\u003e] [[-WriteOemErrorLog] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Agent.JobServer\nReturns the updated JobServer object for the modified instance(s). Properties include all SQL Server Agent configuration settings that were modified, plus any existing settings.\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 SQL Server Agent service name\r\n- AgentLogLevel: Current logging level (Errors, Warnings, etc.)\r\n- DatabaseMailProfile: Active Database Mail profile for notifications\r\n- SqlAgentAutoStart: Boolean indicating if Agent auto-starts\r\n- SqlAgentRestart: Boolean indicating if Agent auto-restarts on failure\nAdditional properties available (from SMO JobServer object):\r\n- AgentMailType: Mail system type (DatabaseMail or SqlAgentMail)\r\n- AgentShutdownWaitTime: Seconds to wait for Agent shutdown\r\n- CpuPolling/IsCpuPollingEnabled: CPU idle monitoring enabled status\r\n- ErrorLogFile: Path to Agent error log\r\n- IdleCpuDuration: Seconds before considering CPU idle\r\n- IdleCpuPercentage: CPU percentage threshold for idle\r\n- LoginTimeout: Connection timeout in seconds\r\n- MaximumHistoryRows: Maximum job history rows retained\r\n- MaximumJobHistoryRows: Maximum history rows per job\r\n- NetSendRecipient: Legacy net send notification recipient\r\n- ReplaceAlertTokensEnabled: Token replacement in alerts enabled status\r\n- SaveInSentFolder: Save notification copies to mail sent items\r\n- SqlAgentMailProfile: Legacy SQL Agent Mail profile\r\n- SqlServerRestart: Agent can restart SQL Server\r\n- WriteOemErrorLog: Write errors to Windows Event Log\nAll properties from the base SMO JobServer object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaAgentServer -SqlInstance sql1 -MaximumHistoryRows 10000 -MaximumJobHistoryRows 100\nChanges the job history retention to 10000 rows with an maximum of 100 rows per job.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaAgentServer -SqlInstance sql1 -CpuPolling Enabled\nEnable the CPU Polling configurations.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-DbaAgentServer -SqlInstance sql1, sql2, sql3 -AgentLogLevel \u0027Errors, Warnings\u0027\nSet the agent log level to Errors and Warnings on multiple servers.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eSet-DbaAgentServer -SqlInstance sql1 -CpuPolling Disabled\nDisable the CPU Polling configurations.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eSet-DbaAgentServer -SqlInstance sql1 -MaximumJobHistoryRows 1000 -MaximumHistoryRows 10000\nSet the max history limitations. This is the equivalent to calling: EXEC msdb.dbo.sp_set_sqlagent_properties @jobhistory_max_rows=10000, @jobhistory_max_rows_per_job=1000\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eSet-DbaAgentServer -SqlInstance sql1 -MaximumJobHistoryRows 0 -MaximumHistoryRows -1\nDisable the max history limitations. This is the equivalent to calling: EXEC msdb.dbo.sp_set_sqlagent_properties @jobhistory_max_rows=-1, @jobhistory_max_rows_per_job=0", "Description": "Modifies SQL Server Agent configuration settings including logging levels, mail profiles, CPU monitoring thresholds, job history retention, and service restart behaviors. Use this to standardize agent configurations across multiple instances, set up proper alerting and monitoring thresholds, or configure job history retention policies to prevent MSDB bloat.", "Links": "https://dbatools.io/Set-DbaAgentServer", "Synopsis": "Configures SQL Server Agent service properties and operational settings", "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.", "", 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 SQL Server Agent JobServer objects from Get-DbaAgentServer for pipeline operations.\r\nUse this when you need to configure multiple agent servers from a filtered list or modify settings on specific instances already retrieved.", "", false, "true (ByValue)", "", "" ], [ "AgentLogLevel", "Controls the verbosity of SQL Server Agent logging in the agent error log.\r\nUse \u0027Errors\u0027 for production environments to minimize log size, \u0027Errors, Warnings\u0027 for standard monitoring, or \u0027All\u0027 when troubleshooting agent job failures.\r\nHigher logging levels help diagnose job execution issues but increase log file growth.", "", false, "false", "", "1,Errors,2,Warnings,3,Errors, Warnings,4,Informational,5,Errors, Informational,6,Warnings, Informational,7,All" ], [ "AgentMailType", "Specifies whether SQL Server Agent uses legacy SQL Agent Mail or the newer Database Mail for notifications.\r\nUse \u0027DatabaseMail\u0027 for modern installations as SQL Agent Mail is deprecated and requires MAPI configuration.\r\nDatabase Mail provides better security, reliability, and doesn\u0027t require Outlook or Exchange MAPI on the server.", "", false, "false", "", "0,SqlAgentMail,1,DatabaseMail" ], [ "AgentShutdownWaitTime", "Sets how long (in seconds) SQL Server waits for SQL Server Agent to shut down during service restart.\r\nIncrease this value if you have long-running jobs that need more time to complete gracefully during shutdown.\r\nDefault is typically 15 seconds; values between 5-600 seconds are supported.", "", false, "false", "0", "" ], [ "DatabaseMailProfile", "Specifies which Database Mail profile SQL Server Agent uses for sending job notifications and alerts.\r\nThe profile must already exist in the instance\u0027s Database Mail configuration before setting this value.\r\nUse this to ensure agent notifications use the correct SMTP settings and sender address for your environment.", "", false, "false", "", "" ], [ "ErrorLogFile", "Sets the file path where SQL Server Agent writes its error log.\r\nChange this when you need agent logs stored in a specific location for centralized monitoring or compliance requirements.\r\nEnsure the SQL Server Agent service account has write permissions to the specified path.", "", false, "false", "", "" ], [ "IdleCpuDuration", "Defines how long (in seconds) the CPU must remain below the idle threshold before SQL Server Agent considers the server idle.\r\nUse this with CpuPolling to schedule jobs only when the server isn\u0027t busy with other workloads.\r\nValues range from 20 seconds to 24 hours (86400 seconds); typical values are 600-1800 seconds for production servers.", "", false, "false", "0", "" ], [ "IdleCpuPercentage", "Sets the CPU usage percentage threshold below which SQL Server Agent considers the server idle.\r\nConfigure this to prevent resource-intensive maintenance jobs from running during peak usage periods.\r\nValues between 10-100 percent; commonly set to 10-25% for production servers to ensure adequate idle detection.", "", false, "false", "0", "" ], [ "CpuPolling", "Enables or disables CPU idle condition monitoring for job scheduling.\r\nEnable this to allow jobs with idle CPU conditions to run only when server CPU usage is low.\r\nUseful for scheduling maintenance tasks like index rebuilds or backups that should avoid peak usage periods.", "", false, "false", "", "Enabled,Disabled" ], [ "LocalHostAlias", "Specifies an alias that SQL Server Agent uses to refer to the local server in job steps and notifications.\r\nSet this when the server has multiple network names or when you want job notifications to reference a specific hostname.\r\nCommonly used in clustered environments or when the server is accessed by different DNS names.", "", false, "false", "", "" ], [ "LoginTimeout", "Sets the timeout (in seconds) for SQL Server Agent connections to SQL Server instances.\r\nIncrease this value if agent jobs frequently fail due to connection timeouts, especially in slow network environments.\r\nValues range from 5-45 seconds; default is typically 30 seconds.", "", false, "false", "0", "" ], [ "MaximumHistoryRows", "Controls the total number of job history rows retained in MSDB before old entries are purged.\r\nSet this to prevent MSDB growth from excessive job history; typical values are 10000-100000 rows depending on job frequency.\r\nUse -1 to disable limits (not recommended for production) or work with MaximumJobHistoryRows to control per-job retention.", "", false, "false", "0", "" ], [ "MaximumJobHistoryRows", "Sets the maximum number of history rows retained per individual job.\r\nPrevents any single job from consuming too much history space; typical values are 100-1000 rows per job.\r\nUse 0 to disable per-job limits when MaximumHistoryRows is set to -1, or set both parameters to control overall history retention.", "", false, "false", "0", "" ], [ "NetSendRecipient", "Specifies the network recipient for legacy net send notifications from SQL Server Agent.\r\nThis feature is deprecated and rarely used in modern environments; Database Mail is the preferred notification method.\r\nOnly configure this if you have legacy monitoring systems that still rely on net send messages.", "", false, "false", "", "" ], [ "ReplaceAlertTokens", "Controls whether SQL Server Agent replaces tokens in alert notification messages with actual values.\r\nEnable this to include dynamic information like error details, job names, or server information in alert emails.\r\nTokens like $(ESCAPE_SQUOTE(A-ERR)) get replaced with actual error text when notifications are sent.", "", false, "false", "", "Enabled,Disabled" ], [ "SaveInSentFolder", "Controls whether copies of agent notification emails are saved to the Database Mail sent items.\r\nEnable this for audit trails and troubleshooting notification delivery issues.\r\nDisable to reduce Database Mail storage usage if you don\u0027t need to track sent notifications.", "", false, "false", "", "Enabled,Disabled" ], [ "SqlAgentAutoStart", "Controls whether SQL Server Agent service starts automatically when SQL Server starts.\r\nEnable this on production servers to ensure scheduled jobs and monitoring continue after server restarts.\r\nDisable only in development environments where automatic job execution isn\u0027t desired.", "", false, "false", "", "Enabled,Disabled" ], [ "SqlAgentMailProfile", "Specifies the legacy SQL Agent Mail profile for notifications (deprecated feature).\r\nOnly used when AgentMailType is set to \u0027SqlAgentMail\u0027; DatabaseMailProfile is preferred for modern installations.\r\nThe profile must exist in the SQL Agent Mail configuration, which requires MAPI setup.", "", false, "false", "", "" ], [ "SqlAgentRestart", "Controls whether SQL Server Agent automatically restarts if it stops unexpectedly.\r\nEnable this on production servers to ensure continuous job scheduling and monitoring after agent failures.\r\nThe agent will attempt to restart itself if the service terminates abnormally.", "", false, "false", "", "Enabled,Disabled" ], [ "SqlServerRestart", "Controls whether SQL Server Agent can restart the SQL Server service if it stops unexpectedly.\r\nEnable this in environments where automatic SQL Server recovery is desired, but use caution on production systems.\r\nThis setting allows the agent to restart the database engine service automatically.", "", false, "false", "", "Enabled,Disabled" ], [ "WriteOemErrorLog", "Controls whether SQL Server Agent writes errors to the Windows Application Event Log.\r\nEnable this to integrate agent errors with centralized Windows event monitoring and alerting systems.\r\nUseful for environments that rely on Windows Event Log for monitoring and don\u0027t use SQL-specific monitoring tools.", "", false, "false", "", "Enabled,Disabled" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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": "Set-DbaAgListener", "Name": "Set-DbaAgListener", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Set-DbaAgListener [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-AvailabilityGroup] \u003cString[]\u003e] [[-Listener] \u003cString[]\u003e] [-Port] \u003cInt32\u003e [[-InputObject] \u003cAvailabilityGroupListener[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.AvailabilityGroupListener\nReturns the modified availability group listener object for each listener that was successfully updated. This is the same object type as returned by Get-DbaAgListener, but with the modified port \r\nnumber applied.\nProperties available on the returned object include:\r\n- Name: The name of the availability group listener\r\n- AvailabilityGroup: The name of the parent availability group\r\n- PortNumber: The port number for client connections (modified by this command)\r\n- IPAddress: The IP address for the listener\r\n- SubnetMask: The subnet mask for the listener\r\n- Parent: Reference to the parent AvailabilityGroup object\nAll properties from the base SMO AvailabilityGroupListener object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaAgListener -SqlInstance sql2017 -AvailabilityGroup SharePoint -Port 14333\nChanges the port for the SharePoint AG Listener on sql2017. Prompts for confirmation.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgListener -SqlInstance sql2017 | Out-GridView -Passthru | Set-DbaAgListener -Port 1433 -Confirm:$false\nChanges the port for selected AG listeners to 1433. Does not prompt for confirmation.", "Description": "Modifies the port number for Availability Group listeners, allowing you to change the network port that clients use to connect to the availability group. This is commonly needed when standardizing ports across environments, resolving port conflicts with other services, or implementing security policies that require non-default ports. The command works with existing listeners and requires the availability group to be online to complete the port change.", "Links": "https://dbatools.io/Set-DbaAgListener", "Synopsis": "Modifies the port number for Availability Group listeners on 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 the name of the availability group containing the listener to modify. Required when using SqlInstance parameter.\r\nUse this to target specific availability groups when multiple groups exist on the same instance.", "", false, "false", "", "" ], [ "Listener", "Specifies the name of specific listeners to modify within the availability group. Optional parameter to target only certain listeners.\r\nUse this when an availability group has multiple listeners and you only want to change the port for specific ones.", "", false, "false", "", "" ], [ "Port", "Sets the new port number for the availability group listener. This is the TCP port clients will use to connect to the availability group.\r\nCommonly changed to standardize ports across environments, resolve conflicts with other services, or meet security requirements.", "", true, "false", "0", "" ], [ "InputObject", "Accepts availability group listener objects from the pipeline, typically from Get-DbaAgListener. Allows you to chain commands together.\r\nUse this approach when you want to filter or select specific listeners before modifying their ports.", "", 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": "Set-DbaAgReplica", "Name": "Set-DbaAgReplica", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Set-DbaAgReplica [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-AvailabilityGroup] \u003cString\u003e] [[-Replica] \u003cString\u003e] [[-AvailabilityMode] \u003cString\u003e] [[-FailoverMode] \u003cString\u003e] [[-BackupPriority] \u003cInt32\u003e] [[-ConnectionModeInPrimaryRole] \u003cString\u003e] [[-ConnectionModeInSecondaryRole] \u003cString\u003e] [[-SeedingMode] \u003cString\u003e] [[-SessionTimeout] \u003cInt32\u003e] [[-EndpointUrl] \u003cString\u003e] [[-ReadonlyRoutingConnectionUrl] \u003cString\u003e] [[-ReadOnlyRoutingList] \u003cObject[]\u003e] [[-InputObject] \u003cAvailabilityReplica\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.AvailabilityReplica\nReturns the modified availability replica object for each replica that was successfully updated. This is the same object type as returned by Get-DbaAgReplica, but with the modified properties applied.\nProperties available on the returned object include:\r\n- Name: The name of the availability replica (server instance name)\r\n- AvailabilityGroup: The name of the parent availability group\r\n- AvailabilityMode: Current availability mode (SynchronousCommit or AsynchronousCommit)\r\n- FailoverMode: Current failover mode (Automatic, Manual, or External)\r\n- BackupPriority: Backup priority value (0-100)\r\n- ConnectionModeInPrimaryRole: Connection mode when this replica is primary\r\n- ConnectionModeInSecondaryRole: Connection mode when this replica is secondary\r\n- EndpointUrl: The endpoint URL for availability group communication\r\n- ReadonlyRoutingConnectionUrl: The URL used for read-only routing\r\n- SeedingMode: Database seeding mode (Automatic or Manual)\r\n- SessionTimeout: Session timeout value in seconds\r\n- Parent: Reference to the parent AvailabilityGroup object\nAll properties from the base SMO AvailabilityReplica object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaAgReplica -SqlInstance sql2016 -Replica sql2016 -AvailabilityGroup SharePoint -BackupPriority 5000\nSets the backup priority to 5000 for the sql2016 replica for the SharePoint availability group on sql2016\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgReplica -SqlInstance sql2016 | Out-GridView -Passthru | Set-DbaAgReplica -BackupPriority 5000\nSets the backup priority to 5000 for the selected availability groups.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaAgReplica -SqlInstance sql2016 -Replica Replica1 |\n\u003e\u003e Set-DbaAgReplica -ReadOnlyRoutingList Replica2, Replica3\nEquivalent to running \"ALTER AVAILABILITY GROUP... MODIFY REPLICA... (READ_ONLY_ROUTING_LIST = (\u0027Replica2\u0027, \u0027Replica3\u0027));\"\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaAgReplica -SqlInstance sql2016 -Replica Replica1 |\n\u003e\u003e Set-DbaAgReplica -ReadOnlyRoutingList @(,(\u0027Replica2\u0027,\u0027Replica3\u0027));\nEquivalent to running \"ALTER AVAILABILITY GROUP... MODIFY REPLICA... (READ_ONLY_ROUTING_LIST = ((\u0027Replica2\u0027, \u0027Replica3\u0027)));\" setting a load balanced routing list for when Replica1 is the primary \r\nreplica.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e# Complete read-only routing setup for a two-replica AG\nPS C:\\\u003e # Step 1: Configure secondary replica to accept read-only connections\r\nPS C:\\\u003e Set-DbaAgReplica -SqlInstance $primary -AvailabilityGroup MyAG -Replica Secondary1 -ConnectionModeInSecondaryRole AllowReadIntentConnectionsOnly\r\nPS C:\\\u003e\r\nPS C:\\\u003e # Step 2: Set the routing URL for each replica\r\nPS C:\\\u003e Set-DbaAgReplica -SqlInstance $primary -AvailabilityGroup MyAG -Replica Primary1 -ReadonlyRoutingConnectionUrl \"TCP://Primary1:1433\"\r\nPS C:\\\u003e Set-DbaAgReplica -SqlInstance $primary -AvailabilityGroup MyAG -Replica Secondary1 -ReadonlyRoutingConnectionUrl \"TCP://Secondary1:1433\"\r\nPS C:\\\u003e\r\nPS C:\\\u003e # Step 3: Set the routing list (which replicas receive read-only traffic when this replica is primary)\r\nPS C:\\\u003e Set-DbaAgReplica -SqlInstance $primary -AvailabilityGroup MyAG -Replica Primary1 -ReadOnlyRoutingList Secondary1, Primary1\nComplete example showing the prerequisites for read-only routing. The routing list specifies where to route\r\nread-intent connections when Primary1 is the primary replica. Note that all replicas in the routing list\r\nmust have their ReadonlyRoutingConnectionUrl configured first.", "Description": "Modifies configuration properties of existing availability group replicas such as availability mode, failover behavior, backup priority, and read-only routing settings. This function is used for ongoing management and tuning of availability groups after initial setup, allowing you to adjust replica behavior without recreating the availability group.\n\nCommon use cases include changing synchronous replicas to asynchronous for performance, adjusting backup priorities to control where backups run, configuring automatic failover settings, and setting up read-only routing for load balancing read workloads across secondary replicas.", "Links": "https://dbatools.io/Set-DbaAgReplica", "Synopsis": "Modifies configuration properties of existing availability group 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 the name of the availability group that contains the replica to modify.\r\nRequired when using SqlInstance parameter to identify which availability group the replica belongs to.", "", false, "false", "", "" ], [ "Replica", "Specifies the name of the availability group replica to modify. This is the server instance name that hosts the replica.\r\nUse this when targeting a specific replica within an availability group for configuration changes.", "", false, "false", "", "" ], [ "AvailabilityMode", "Controls the data synchronization mode between primary and secondary replicas. SynchronousCommit ensures zero data loss but may impact performance, while AsynchronousCommit prioritizes performance \r\nover guaranteed data protection.\r\nChange this when you need to balance performance requirements against data protection needs across different replicas.", "", false, "false", "", "AsynchronousCommit,SynchronousCommit" ], [ "FailoverMode", "Determines whether the replica can automatically failover when the primary becomes unavailable. Automatic failover requires SynchronousCommit availability mode and is typically used for high \r\navailability scenarios.\r\nSet to Manual when you want to control failover decisions or when using AsynchronousCommit replicas.", "", false, "false", "", "Automatic,Manual,External" ], [ "BackupPriority", "Sets the backup priority for this replica on a scale of 0-100, where higher values indicate higher priority for backup operations.\r\nUse this to control which replica should be preferred for automated backup jobs, with 0 excluding the replica from backup consideration entirely.", "", false, "false", "0", "" ], [ "ConnectionModeInPrimaryRole", "Controls what types of connections are allowed when this replica is the primary. AllowAllConnections permits both read-write and read-only connections, while AllowReadWriteConnections only allows \r\nread-write access.\r\nTypically left as AllowAllConnections unless you need to restrict read-only workloads from connecting to the primary.", "", false, "false", "", "AllowAllConnections,AllowReadWriteConnections" ], [ "ConnectionModeInSecondaryRole", "Determines connection access when this replica is secondary. Options include AllowNoConnections, AllowReadIntentConnectionsOnly (for read-only workloads), or AllowAllConnections.\r\nConfigure this to enable read-only workloads on secondary replicas for reporting or to completely block connections for backup-only replicas.", "", false, "false", "", "AllowAllConnections,AllowNoConnections,AllowReadIntentConnectionsOnly,No,Read-intent only,Yes" ], [ "SeedingMode", "Controls the database initialization method for new databases added to the availability group. Automatic performs direct seeding over the network without manual backup/restore steps, while Manual \r\nrequires traditional backup and restore operations.\r\nChoose Automatic for convenience and reduced administrative overhead, or Manual when you need control over backup/restore timing or have network bandwidth constraints.", "", false, "false", "", "Automatic,Manual" ], [ "SessionTimeout", "Sets the timeout period in seconds for detecting communication failures between availability replicas. Values below 10 seconds can cause false failure detection in busy environments.\r\nIncrease this value in high-latency network environments or decrease it when you need faster failure detection, keeping the 10-second minimum recommendation in mind.", "", false, "false", "0", "" ], [ "EndpointUrl", "Specifies the URL endpoint used for data mirroring communication between replicas, typically in the format \u0027TCP://servername:port\u0027.\r\nUpdate this when changing network configurations, server names, or port assignments for availability group communication.", "", false, "false", "", "" ], [ "ReadonlyRoutingConnectionUrl", "Specifies the connection string used by the availability group listener to route read-only connections to this secondary replica.\r\nRequired when setting up read-only routing to distribute read workloads across secondary replicas for load balancing.", "", false, "false", "", "" ], [ "ReadOnlyRoutingList", "Defines the ordered list of secondary replicas that should receive read-only connections when this replica is primary.\r\nAccepts arrays for priority-based routing or nested arrays for load-balanced routing.\nIMPORTANT: Read-only routing requires proper setup:\r\n1. The availability group must have at least two replicas (primary + secondary)\r\n2. Target replicas must exist in the availability group\r\n3. Secondary replicas must have ConnectionModeInSecondaryRole set to AllowReadIntentConnectionsOnly or AllowAllConnections\r\n4. Each replica in the routing list must have ReadonlyRoutingConnectionUrl configured\r\n5. An availability group listener is required for read-only routing to function\nFor more information, see: https://learn.microsoft.com/sql/database-engine/availability-groups/windows/configure-read-only-routing-for-an-availability-group-sql-server", "", false, "false", "", "" ], [ "InputObject", "Accepts availability group replica objects from Get-DbaAgReplica for pipeline operations.\r\nUse this to modify multiple replicas or when working with replica objects retrieved from previous 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", "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": "Set-DbaAvailabilityGroup", "Name": "Set-DbaAvailabilityGroup", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Set-DbaAvailabilityGroup [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-AvailabilityGroup] \u003cString[]\u003e] [-AllAvailabilityGroups] [-DtcSupportEnabled] [[-ClusterType] \u003cString\u003e] [[-AutomatedBackupPreference] \u003cString\u003e] [[-FailureConditionLevel] \u003cString\u003e] [[-HealthCheckTimeout] \u003cInt32\u003e] [-BasicAvailabilityGroup] [-DatabaseHealthTrigger] [-IsDistributedAvailabilityGroup] [[-ClusterConnectionOption] \u003cString\u003e] [[-InputObject] \u003cAvailabilityGroup[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.AvailabilityGroup\nReturns one AvailabilityGroup object per availability group that was modified. The object contains the updated configuration properties that were changed by this command.\nDefault display properties (via Select-DefaultView):\r\n- Name: Name of the availability group\r\n- AvailabilityReplicas: Collection of replica instances in the AG\r\n- AutomatedBackupPreference: Current backup preference (None, Primary, Secondary, SecondaryOnly)\r\n- BasicAvailabilityGroup: Boolean indicating if the AG is a Basic AG (Standard Edition)\r\n- ClusterType: Clustering technology used (Wsfc, External, None) - SQL Server 2017+\r\n- DatabaseHealthTrigger: Boolean indicating if database health triggers failover\r\n- DtcSupportEnabled: Boolean indicating if Distributed Transaction Coordinator support is enabled\r\n- FailureConditionLevel: Failover sensitivity level (OnServerDown, OnServerUnresponsive, OnCriticalServerErrors, OnModerateServerErrors, OnAnyQualifiedFailureCondition)\r\n- HealthCheckTimeout: Health check timeout in milliseconds\r\n- IsDistributedAvailabilityGroup: Boolean indicating if this is a Distributed AG (SQL Server 2016+)\nAdditional properties available (from SMO AvailabilityGroup object):\r\n- ClusterConnectionOptions: Connection options for WSFC communication (SQL Server 2025+)\r\n- Parent: Reference to the parent SQL Server object\r\n- Databases: Collection of databases in the AG\r\n- ListenerIPAddresses: Collection of listener IP addresses\r\n- AvailabilityGroupListeners: Collection of AG listeners\r\n- CreateDate: DateTime when the AG was created\r\n- LastModificationTime: DateTime when the AG was last modified\r\n- Urn: The Unified Resource Name for the AG\r\n- State: Current state of the SMO object (Existing, Creating, Pending, etc.)\nAll properties from the base SMO AvailabilityGroup object are accessible using Select-Object * even though only default properties are displayed without that cmdlet.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sql2016 | Set-DbaAvailabilityGroup -DtcSupportEnabled\nEnables DTC for all availability groups on sql2016\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sql2016 -AvailabilityGroup AG1 | Set-DbaAvailabilityGroup -DtcSupportEnabled:$false\nDisables DTC support for the availability group AG1\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-DbaAvailabilityGroup -SqlInstance sql2016 -AvailabilityGroup AG1 -DtcSupportEnabled:$false\nDisables DTC support for the availability group AG1", "Description": "Modifies configuration properties of existing availability groups without requiring you to script out and recreate the entire AG setup. Commonly used to enable DTC support for distributed transactions, adjust automated backup preferences across replicas, configure failure condition levels for automatic failover, and set health check timeouts for monitoring. This saves time compared to using SQL Server Management Studio or T-SQL ALTER AVAILABILITY GROUP statements for routine configuration changes.", "Links": "https://dbatools.io/Set-DbaAvailabilityGroup", "Synopsis": "Modifies availability group configuration settings including DTC support, backup preferences, and failover conditions", "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 the name(s) of specific availability groups to modify. Accepts multiple AG names as an array.\r\nUse this to target individual AGs instead of modifying all AGs on the instance.", "", false, "false", "", "" ], [ "AllAvailabilityGroups", "Modifies configuration settings for every availability group on the target SQL Server instance.\r\nUse this switch when you need to apply the same configuration changes across all AGs simultaneously.", "", false, "false", "False", "" ], [ "DtcSupportEnabled", "Enables or disables Distributed Transaction Coordinator (DTC) support for the availability group.\r\nRequired when applications use distributed transactions across multiple databases in the AG. Set to $false to disable DTC support.", "", false, "false", "False", "" ], [ "ClusterType", "Specifies the clustering technology used by the availability group. Only supported in SQL Server 2017 and above.\r\nUse \u0027Wsfc\u0027 for Windows Server Failover Clustering, \u0027External\u0027 for third-party cluster managers like Pacemaker on Linux, or \u0027None\u0027 for read-scale AGs without automatic failover.", "", false, "false", "", "External,Wsfc,None" ], [ "AutomatedBackupPreference", "Controls which replica should be preferred for automated backup operations within the availability group.\r\nUse \u0027Secondary\u0027 to offload backups from the primary, \u0027SecondaryOnly\u0027 to prevent backups on primary, \u0027Primary\u0027 to always backup on primary, or \u0027None\u0027 to disable preference-based backup routing.", "", false, "false", "", "None,Primary,Secondary,SecondaryOnly" ], [ "FailureConditionLevel", "Sets the sensitivity level for automatic failover conditions in the availability group.\r\nUse \u0027OnServerDown\u0027 for basic failover, \u0027OnServerUnresponsive\u0027 for SQL Service issues, \u0027OnCriticalServerErrors\u0027 for critical SQL errors, \u0027OnModerateServerErrors\u0027 for moderate SQL errors, or \r\n\u0027OnAnyQualifiedFailureCondition\u0027 for maximum sensitivity.", "", false, "false", "", "OnAnyQualifiedFailureCondition,OnCriticalServerErrors,OnModerateServerErrors,OnServerDown,OnServerUnresponsive" ], [ "HealthCheckTimeout", "Sets the timeout in milliseconds for health check responses from sp_server_diagnostics before marking the AG as unresponsive.\r\nIncrease this value for busy systems or slow storage to reduce false failovers. Decrease for faster failover detection in stable environments.\r\nDefault is 30000 (30 seconds). Changes take effect immediately without restart.", "", false, "false", "0", "" ], [ "BasicAvailabilityGroup", "Configures the availability group as a Basic AG with limited functionality for Standard Edition licensing.\r\nBasic AGs support only one database, two replicas, and no read-access to secondary replicas. Used when full AG features aren\u0027t needed or licensed.", "", false, "false", "False", "" ], [ "DatabaseHealthTrigger", "Enables database-level health monitoring that can trigger automatic failovers based on individual database health status.\r\nWhen enabled, databases that become offline or experience critical errors can initiate AG failover. Useful for comprehensive monitoring beyond SQL Server instance health.", "", false, "false", "False", "" ], [ "IsDistributedAvailabilityGroup", "Configures the availability group as a Distributed AG that spans multiple WSFC clusters or standalone instances.\r\nUsed for disaster recovery scenarios across geographic locations or different domains. Requires SQL Server 2016 or later.", "", false, "false", "False", "" ], [ "ClusterConnectionOption", "Specifies connection options for TDS 8.0 support in SQL Server 2025 and above.\r\nThis allows the Windows Server Failover Cluster (WSFC) to connect to SQL Server instances using ODBC with TLS 1.3 encryption.\r\nThe value is a string containing semicolon-delimited key-value pairs.\nAvailable keys:\r\n- Encrypt: Controls connection encryption\r\n- TrustServerCertificate: Whether to trust the server certificate\r\n- HostNameInCertificate: Expected hostname in the certificate\r\n- ServerCertificate: Path to server certificate\nThis setting is persisted by WSFC in the registry and used continuously for cluster-to-instance communication.\r\nNote: PowerShell does not validate these values - invalid combinations will be rejected by SMO or the ODBC driver.\nExample: \"Encrypt=Strict;TrustServerCertificate=False\"\nFor detailed documentation, see:\r\nhttps://learn.microsoft.com/en-us/sql/t-sql/statements/alter-availability-group-transact-sql", "", false, "false", "", "" ], [ "InputObject", "Accepts availability group objects from Get-DbaAvailabilityGroup for pipeline operations.\r\nUse this to pipe specific AG objects directly to the function instead of specifying SqlInstance and AG names separately.", "", 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": [ "ComputerManagement", "CIM" ], "CommandName": "Set-DbaCmConnection", "Name": "Set-DbaCmConnection", "Author": "Friedrich Weinmann (@FredWeinmann)", "Syntax": "Set-DbaCmConnection [-ComputerName \u003cDbaCmConnectionParameter[]\u003e] [-Credential \u003cPSCredential\u003e] [-OverrideExplicitCredential] [-OverrideConnectionPolicy] [-DisabledConnectionTypes {None | CimRM | CimDCOM | Wmi | PowerShellRemoting}] [-DisableBadCredentialCache] [-DisableCimPersistence] [-DisableCredentialAutoRegister] [-EnableCredentialFailover] [-WindowsCredentialsAreBad] [-CimWinRMOptions \u003cWSManSessionOptions\u003e] [-CimDCOMOptions \u003cDComSessionOptions\u003e] [-AddBadCredential \u003cPSCredential[]\u003e] [-RemoveBadCredential \u003cPSCredential[]\u003e] [-ClearBadCredential] [-ClearCredential] [-ResetCredential] \r\n[-ResetConnectionStatus] [-ResetConfiguration] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nSet-DbaCmConnection [-ComputerName \u003cDbaCmConnectionParameter[]\u003e] [-UseWindowsCredentials] [-OverrideExplicitCredential] [-OverrideConnectionPolicy] [-DisabledConnectionTypes {None | CimRM | CimDCOM | Wmi | PowerShellRemoting}] [-DisableBadCredentialCache] [-DisableCimPersistence] [-DisableCredentialAutoRegister] [-EnableCredentialFailover] [-CimWinRMOptions \u003cWSManSessionOptions\u003e] [-CimDCOMOptions \u003cDComSessionOptions\u003e] [-AddBadCredential \u003cPSCredential[]\u003e] [-RemoveBadCredential \u003cPSCredential[]\u003e] [-ClearBadCredential] [-ClearCredential] [-ResetCredential] [-ResetConnectionStatus] \r\n[-ResetConfiguration] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Dataplat.Dbatools.Connection.ManagementConnection\nReturns the modified connection object after applying the specified configuration changes. The object represents the remote computer connection settings used by dbatools for CIM, WMI, and PowerShell \r\nremoting operations.\nDefault display properties:\r\n- ComputerName: The name of the SQL Server host computer for which connection settings were configured\r\n- IsConnected: Boolean indicating whether a successful connection to the remote computer has been established\r\n- CimRM: Current status of CIM (WinRM) connectivity (Unknown, Connected, Failed, Untested)\r\n- CimDCOM: Current status of CIM (DCOM) connectivity (Unknown, Connected, Failed, Untested)\r\n- Wmi: Current status of WMI connectivity (Unknown, Connected, Failed, Untested)\r\n- PowerShellRemoting: Current status of PowerShell remoting connectivity (Unknown, Connected, Failed, Untested)\nAdditional properties available (from ManagementConnection object):\r\n- Credentials: Currently cached credentials for this connection\r\n- UseWindowsCredentials: Boolean indicating whether Windows credentials of the current user are configured\r\n- WindowsCredentialsAreBad: Boolean indicating whether Windows credentials have been marked as non-functional\r\n- KnownBadCredentials: Collection of credentials known to fail authentication\r\n- OverrideExplicitCredential: Boolean indicating whether cached credentials override explicit parameters\r\n- OverrideConnectionPolicy: Boolean indicating whether global connection policies are bypassed\r\n- DisabledConnectionTypes: Connection protocols disabled for this computer\r\n- DisableBadCredentialCache: Boolean indicating whether failed credentials are cached\r\n- DisableCimPersistence: Boolean indicating whether CIM sessions are recreated each time\r\n- DisableCredentialAutoRegister: Boolean indicating whether successful credentials are auto-cached\r\n- EnableCredentialFailover: Boolean indicating whether credential failover is enabled\r\n- CimWinRMOptions: WinRM session options for CIM connections\r\n- CimDCOMOptions: DCOM session options for CIM connections\r\n- LastCimRM: DateTime of last CIM (WinRM) connection attempt\r\n- LastCimDCOM: DateTime of last CIM (DCOM) connection attempt\r\n- LastWmi: DateTime of last WMI connection attempt\r\n- LastPowerShellRemoting: DateTime of last PowerShell remoting connection attempt", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaCmConnection sql2014 | Set-DbaCmConnection -ClearBadCredential -UseWindowsCredentials\nRetrieves the already existing connection to sql2014, removes the list of not working credentials and configures it to default to the credentials of the logged on user.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaCmConnection | Set-DbaCmConnection -RemoveBadCredential $cred\nRemoves the credentials stored in $cred from all connections\u0027 list of \"known to not work\" credentials.\r\nHandy to update changes in privilege.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaCmConnection | Export-Clixml .\\connections.xml\nPS C:\\\u003e Import-Clixml .\\connections.xml | Set-DbaCmConnection -ResetConfiguration\nAt first, the current cached connections are stored in an xml file. At a later time - possibly in the profile when starting the console again - those connections are imported again and applied again \r\nto the connection cache.\nIn this example, the configuration settings will also be reset, since after re-import those will be set to explicit, rather than deriving them from the global settings.\r\nIn many cases, using the default settings is desirable. For specific settings, use New-DbaCmConnection as part of the profile in order to explicitly configure a connection.", "Description": "Configures connection objects that dbatools uses to manage remote SQL Server host computers via CIM, WMI, and PowerShell remoting.\nThis function creates new connection records for computers not yet cached, or modifies existing connection settings for previously contacted hosts.\n\nUse this to bulk-configure connection behavior, manage credential caching, or troubleshoot remote connection issues when dbatools functions need to access SQL Server host systems for tasks like service management, file operations, or system information gathering.", "Links": "https://dbatools.io/Set-DbaCmConnection", "Synopsis": "Configures remote computer connection settings for SQL Server host management.", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the SQL Server host computer name to configure connection settings for. Accepts computer names, FQDNs, or IP addresses.\r\nUse this when you need to pre-configure how dbatools connects to specific SQL Server host machines for service management, file operations, or system administration tasks.", "", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "The credential to register.", "", false, "false", "", "" ], [ "UseWindowsCredentials", "Confirms that Windows credentials of the current user should be used for remote connections to the target computer.\r\nSet this when you know the current user account has sufficient privileges on the remote SQL Server host and want to avoid credential prompts.", "", false, "false", "False", "" ], [ "OverrideExplicitCredential", "Forces dbatools to use cached working credentials instead of explicitly provided credentials when available.\r\nEnable this when you want the connection system to automatically use known-good credentials rather than failing with explicitly provided but incorrect credentials.", "", false, "false", "False", "" ], [ "OverrideConnectionPolicy", "Allows this connection to bypass global connection type restrictions configured in dbatools settings.\r\nUse this when you need to enable specific connection methods (CIM, WMI, PowerShell remoting) for individual computers that are normally disabled globally.", "", false, "false", "False", "" ], [ "DisabledConnectionTypes", "Specifies which connection protocols to disable for this computer (CIM, WMI, PowerShell remoting, or combinations).\r\nUse this to block problematic connection methods on specific hosts while allowing others to work normally.", "", false, "false", "None", "" ], [ "DisableBadCredentialCache", "Prevents dbatools from remembering credentials that fail authentication for this computer.\r\nEnable this when you\u0027re frequently changing credentials or troubleshooting authentication issues and don\u0027t want failed attempts cached.", "", false, "false", "False", "" ], [ "DisableCimPersistence", "Forces dbatools to create new CIM sessions for each operation instead of reusing existing sessions.\r\nUse this when experiencing issues with persistent CIM connections or when you need fresh authentication for each operation.", "", false, "false", "False", "" ], [ "DisableCredentialAutoRegister", "Prevents successful credentials from being automatically saved to the connection cache for future use.\r\nEnable this for security-sensitive environments where you don\u0027t want credentials stored in memory between operations.", "", false, "false", "False", "" ], [ "EnableCredentialFailover", "Allows dbatools to automatically try previously successful credentials when the provided credentials fail.\r\nUse this to improve connection reliability by falling back to known working credentials when new ones don\u0027t authenticate properly.", "", false, "false", "False", "" ], [ "WindowsCredentialsAreBad", "Marks the current user\u0027s Windows credentials as non-functional for this remote computer.\r\nSet this when you know Windows authentication won\u0027t work for the target host and want to prevent automatic attempts with current user credentials.", "", false, "false", "False", "" ], [ "CimWinRMOptions", "Specifies advanced WinRM session options for CIM connections, such as authentication methods, timeouts, or proxy settings.\r\nCreate this object using New-CimSessionOption and use when you need custom WinRM configuration for challenging network environments.", "", false, "false", "", "" ], [ "CimDCOMOptions", "Specifies advanced DCOM session options for CIM connections, including authentication, impersonation levels, or DCOM-specific settings.\r\nCreate this object using New-CimSessionOption and use when connecting through firewalls or when WinRM isn\u0027t available.", "", false, "false", "", "" ], [ "AddBadCredential", "Adds specific credentials to the list of known non-working credentials for this computer.\r\nUse this to prevent dbatools from attempting credentials you know will fail, improving performance and avoiding account lockouts.", "", false, "false", "", "" ], [ "RemoveBadCredential", "Removes previously flagged credentials from the bad credential list for this computer.\r\nUse this when credentials that previously failed have been updated or permissions have been granted.", "", false, "false", "", "" ], [ "ClearBadCredential", "Removes all entries from the bad credential cache for this computer.\r\nUse this when troubleshooting authentication issues or after bulk credential updates that might affect previously failed credentials.", "", false, "false", "False", "" ], [ "ClearCredential", "Removes any cached working credentials for this computer, forcing fresh authentication on next connection.\r\nUse this when credentials have changed or when you need to ensure the next connection uses newly provided credentials.", "", false, "false", "False", "" ], [ "ResetCredential", "Performs a complete credential reset by clearing both working and failed credential caches and resetting Windows credential status.\r\nUse this for comprehensive credential troubleshooting or when starting fresh with connection authentication for a host.", "", false, "false", "False", "" ], [ "ResetConnectionStatus", "Clears all connection protocol test results, marking CIM, WMI, and PowerShell remoting as untested for this computer.\r\nUse this to force dbatools to re-test connection methods after network changes, firewall updates, or service configuration changes.", "", false, "false", "False", "" ], [ "ResetConfiguration", "Restores all connection behavior settings to system defaults, removing any computer-specific overrides.\r\nUse this to return a connection to standard behavior after testing custom settings or when troubleshooting connection issues.", "", 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": [ "Compatibility", "Database" ], "CommandName": "Set-DbaDbCompatibility", "Name": "Set-DbaDbCompatibility", "Author": "Garry Bargsley, blog.garrybargsley.com", "Syntax": "Set-DbaDbCompatibility [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-Compatibility] {Version60 | Version65 | Version70 | Version80 | Version90 | Version100 | Version110 | Version120 | Version130 | Version140 | Version150 | Version160 | Version170}] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database where the compatibility level was successfully changed. No output is generated for databases already at the target compatibility level.\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 whose compatibility level was changed\r\n- Compatibility: The new compatibility level applied to the database\r\n- PreviousCompatibility: The compatibility level the database had before the change", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaDbCompatibility -SqlInstance sql2017a\nChanges database compatibility level for all user databases on server sql2017a that have a Compatibility level that do not match\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaDbCompatibility -SqlInstance sql2019a -Compatibility Version150\nChanges database compatibility level for all user databases on server sql2019a to Version150\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-DbaDbCompatibility -SqlInstance sql2022b -Database Test -Compatibility Version160\nChanges database compatibility level for database Test on server sql2022b to Version160", "Description": "Updates database compatibility levels across one or more SQL Server instances. When no specific compatibility level is provided, automatically sets each database to match the SQL Server instance version it resides on. This is particularly useful after SQL Server upgrades when databases retain their original compatibility levels and need updating to take advantage of newer engine features and optimizations. The function processes only databases where the current compatibility level differs from the target level, making it safe to run repeatedly.", "Links": "https://dbatools.io/Set-DbaDbCompatibility", "Synopsis": "Changes database compatibility levels to match SQL Server instance version or specified target level.", "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 update compatibility levels for. Accepts wildcards for pattern matching.\r\nWhen omitted, processes all user databases on the target instance, excluding system databases.", "", false, "false", "", "" ], [ "Compatibility", "Sets a specific target compatibility level for all processed databases. Must be a valid CompatibilityLevel enum value like Version160, Version150, etc.\r\nWhen omitted, automatically updates each database to match its SQL Server instance version, which is typically desired after SQL Server upgrades.\r\nUse this parameter when you need databases to remain at a specific compatibility level rather than matching the current server version.", "", false, "false", "", "" ], [ "InputObject", "Accepts database objects from the pipeline, typically from Get-DbaDatabase or other dbatools functions.\r\nUse this when you need to apply compatibility level changes to a pre-filtered set of databases 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", "" ], [ "WhatIf", "Shows what would happen if the command were to run", "wi", false, "false", "", "" ], [ "Confirm", "Prompts for confirmation of every step. For example:\nAre you sure you want to perform this action?\r\nPerforming the operation \"Update database\" on target \"pubs on SQL2016\\VNEXT\".\r\n[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is \"Y\"):", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Compression", "Table", "Database" ], "CommandName": "Set-DbaDbCompression", "Name": "Set-DbaDbCompression", "Author": "Jason Squires (@js_0505), jstexasdba@gmail.com", "Syntax": "Set-DbaDbCompression [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-ExcludeDatabase] \u003cString[]\u003e] [[-Table] \u003cString[]\u003e] [[-CompressionType] \u003cString\u003e] [[-MaxRunTime] \u003cInt32\u003e] [[-PercentCompression] \u003cInt32\u003e] [-ForceOfflineRebuilds] [[-InputObject] \u003cObject\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per partition for each table or index that was compressed. When using Recommended compression mode, returns the original compression analysis object with an additional \r\nAlreadyProcessed property indicating whether the recommendation was applied.\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 database name\r\n- Schema: The schema name containing the table\r\n- TableName: The name of the table\r\n- IndexName: The name of the index; null for heap partitions, contains index name for indexed partitions\r\n- Partition: The partition number (1-based, or 1 for non-partitioned objects)\r\n- IndexID: The index ID number - 0 for heaps, greater than 0 for indexes\r\n- IndexType: The type of index structure (Heap, ClusteredIndex, or other SMO index type values)\r\n- CompressionTypeRecommendation: The compression type that was applied (ROW, PAGE, or NONE in uppercase)\r\n- AlreadyProcessed: A flag indicating if the object was successfully processed (True or False as string)\r\n- PercentScan: Placeholder property from Test-DbaDbCompression analysis (always null in output)\r\n- PercentUpdate: Placeholder property from Test-DbaDbCompression analysis (always null in output)\r\n- RowEstimatePercentOriginal: Placeholder property from Test-DbaDbCompression analysis (always null in output)\r\n- PageEstimatePercentOriginal: Placeholder property from Test-DbaDbCompression analysis (always null in output)\r\n- SizeCurrent: Placeholder property from Test-DbaDbCompression analysis (always null in output)\r\n- SizeRequested: Placeholder property from Test-DbaDbCompression analysis (always null in output)\r\n- PercentCompression: Placeholder property from Test-DbaDbCompression analysis (always null in output)\nWhen using CompressionType parameter (Row, Page, or None), returns objects for each partition that was compressed.\r\nWhen using CompressionType Recommended (default), returns objects from Test-DbaDbCompression with the AlreadyProcessed property added.\r\nIn Recommended mode, only objects with CompressionTypeRecommendation that is not \u0027NO_GAIN\u0027 or \u0027?\u0027 and meets the PercentCompression threshold are output.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaDbCompression -SqlInstance localhost -MaxRunTime 60 -PercentCompression 25\nSet the compression run time to 60 minutes and will start the compression of tables/indexes that have a difference of 25% or higher between current and recommended.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaDbCompression -SqlInstance ServerA -Database DBName -CompressionType Page -Table table1, table2\nUtilizes Page compression for tables table1 and table2 in DBName on ServerA with no time limit.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-DbaDbCompression -SqlInstance ServerA -Database DBName -PercentCompression 25 | Out-GridView\nWill compress tables/indexes within the specified database that would show any % improvement with compression and with no time limit. The results will be piped into a nicely formatted GridView.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$testCompression = Test-DbaDbCompression -SqlInstance ServerA -Database DBName\nPS C:\\\u003e Set-DbaDbCompression -SqlInstance ServerA -Database DBName -InputObject $testCompression\nGets the compression suggestions from Test-DbaDbCompression into a variable, this can then be reviewed and passed into Set-DbaDbCompression.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Set-DbaDbCompression -SqlInstance ServerA -ExcludeDatabase Database -SqlCredential $cred -MaxRunTime 60 -PercentCompression 25\nSet the compression run time to 60 minutes and will start the compression of tables/indexes for all databases except the specified excluded database. Only objects that have a difference of 25% or \r\nhigher between current and recommended will be compressed.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e$servers = \u0027Server1\u0027,\u0027Server2\u0027\nPS C:\\\u003e foreach ($svr in $servers) {\r\n\u003e\u003e Set-DbaDbCompression -SqlInstance $svr -MaxRunTime 60 -PercentCompression 25 | Export-Csv -Path C:\\temp\\CompressionAnalysisPAC.csv -Append\r\n\u003e\u003e }\nSet the compression run time to 60 minutes and will start the compression of tables/indexes across all listed servers that have a difference of 25% or higher between current and recommended. Output \r\nof command is exported to a csv.", "Description": "Compresses tables, indexes, and heaps across one or more databases using Row, Page, or intelligent recommendations based on Microsoft\u0027s Tiger Team compression analysis. Automatically handles the complex process of analyzing usage patterns, applying appropriate compression types, and rebuilding objects online when possible. Saves significant storage space, reduces backup sizes, and improves I/O performance without requiring manual compression analysis for each object. Particularly valuable for large production databases where storage costs and backup windows are concerns.", "Links": "https://dbatools.io/Set-DbaDbCompression", "Synopsis": "Applies data compression to SQL Server tables and indexes to reduce storage space and improve performance.", "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 apply compression to. Accepts wildcard patterns and multiple database names.\r\nWhen omitted, all non-system databases on the instance will be processed. Use this to target specific databases when you don\u0027t want to compress everything.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies databases to skip during the compression operation. Accepts wildcard patterns and multiple database names.\r\nUse this when you want to compress most databases but exclude specific ones like databases under maintenance or with special requirements.", "", false, "false", "", "" ], [ "Table", "Specifies which tables to compress within the selected databases. Accepts multiple table names and works with wildcard patterns.\r\nWhen omitted, all eligible tables in the database will be processed. Use this to target specific large tables or avoid compressing certain tables.", "", false, "false", "", "" ], [ "CompressionType", "Specifies the type of compression to apply: Recommended, Page, Row, or None. Default is \u0027Recommended\u0027 which analyzes each object and applies the optimal compression type.\r\nUse \u0027Page\u0027 or \u0027Row\u0027 to force all objects to the same compression level, or \u0027None\u0027 to remove compression. Recommended is best for mixed workloads where different objects benefit from different \r\ncompression types.", "", false, "false", "Recommended", "Recommended,Page,Row,None" ], [ "MaxRunTime", "Sets a time limit in minutes for the compression operation to prevent it from running indefinitely. When the time limit is reached, the function stops processing additional objects.\r\nUse this during business hours to ensure the operation completes within a maintenance window. A value of 0 (default) means no time limit.", "", false, "false", "0", "" ], [ "PercentCompression", "Sets the minimum space savings threshold (as a percentage) required before an object will be compressed. Only objects that would achieve this level of savings or higher are processed.\r\nUse this to focus compression efforts on objects that will provide the most benefit. For example, setting this to 25 will only compress objects that would save at least 25% of their current space.", "", false, "false", "0", "" ], [ "ForceOfflineRebuilds", "Forces compression operations to use offline rebuilds instead of the default online rebuilds when possible. Online rebuilds keep tables accessible during compression but use more resources.\r\nUse this switch when you need to minimize resource usage during compression or when experiencing issues with online operations. Offline rebuilds will make tables unavailable during the compression \r\nprocess.", "", false, "false", "False", "" ], [ "InputObject", "Accepts compression recommendations from Test-DbaDbCompression and applies those specific recommendations instead of running a new analysis.\r\nUse this when you want to review compression recommendations first, then apply only the ones you approve of. This approach gives you more control over which objects get compressed.", "", 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": [ "Storage", "Data", "File" ], "CommandName": "Set-DbaDbFileGroup", "Name": "Set-DbaDbFileGroup", "Author": "Adam Lancaster, github.com/lancasteradam", "Syntax": "Set-DbaDbFileGroup [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-FileGroup] \u003cString[]\u003e] [-Default] [-ReadOnly] [-AutoGrowAllFiles] [[-InputObject] \u003cObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.FileGroup\nReturns the modified FileGroup object(s) after the specified changes have been applied. One object is returned per filegroup that was successfully modified.\nDefault display properties:\r\n- Name: The name of the filegroup\r\n- IsDefault: Boolean indicating if this is the default filegroup for new objects\r\n- ReadOnly: Boolean indicating if the filegroup is read-only\r\n- AutogrowAllFiles: Boolean indicating if all files in the filegroup grow proportionally\nAdditional properties available (from SMO FileGroup object):\r\n- ID: The filegroup ID number\r\n- Parent: Reference to the parent Database object\r\n- Files: Collection of files contained in the filegroup\r\n- FileGroupType: Type of filegroup (PRIMARY, FILESTREAM, MEMORY_OPTIMIZED, etc.)\r\n- Urn: The Uniform Resource Name of the filegroup object\r\n- State: The current state of the SMO object (Existing, Creating, Pending, etc.)\nAll properties from the base SMO FileGroup object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaDbFileGroup -SqlInstance sqldev1 -Database TestDb -FileGroup HRFG1 -Default -AutoGrowAllFiles\nSets the HRFG1 filegroup to auto grow all files and makes it the default filegroup on the TestDb database on the sqldev1 instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaDbFileGroup -SqlInstance sqldev1 -Database TestDb -FileGroup HRFG1 -AutoGrowAllFiles:$false\nSets the HRFG1 filegroup to not auto grow all files on the TestDb database on the sqldev1 instance.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-DbaDbFileGroup -SqlInstance sqldev1 -Database TestDb -FileGroup HRFG1 -ReadOnly\nSets the HRFG1 filegroup to read only on the TestDb database on the sqldev1 instance.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eSet-DbaDbFileGroup -SqlInstance sqldev1 -Database TestDb -FileGroup HRFG1 -ReadOnly:$false\nSets the HRFG1 filegroup to read/write on the TestDb database on the sqldev1 instance.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sqldev1 -Database TestDb | Set-DbaDbFileGroup -FileGroup HRFG1 -AutoGrowAllFiles\nPasses in the TestDB database from the sqldev1 instance and sets the HRFG1 filegroup to auto grow all files.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaDbFileGroup -SqlInstance sqldev1 -Database TestDb -FileGroup HRFG1 | Set-DbaDbFileGroup -AutoGrowAllFiles\nPasses in the HRFG1 filegroup from the TestDB database on the sqldev1 instance and sets it to auto grow all files.", "Description": "Modifies key properties of database filegroups including setting the default filegroup for new objects, changing read-only status for data archival, and configuring auto-grow behavior across all files in the filegroup. Use this when you need to restructure database storage layout, implement data archival strategies, or optimize file growth patterns. The function validates that filegroups exist and contain at least one file before applying changes.", "Links": "https://dbatools.io/Set-DbaDbFileGroup", "Synopsis": "Modifies filegroup properties including default designation, read-only status, and auto-grow behavior.", "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 contain the filegroups to modify. Required when using SqlInstance parameter.\r\nUse this to target specific databases when working with filegroup configurations across multiple databases.", "", false, "false", "", "" ], [ "FileGroup", "Specifies the name(s) of the filegroup(s) to modify. The filegroup must exist and contain at least one file.\r\nUse this to target specific filegroups when you need to change their default status, read-only setting, or auto-grow behavior.", "", false, "false", "", "" ], [ "Default", "Sets the filegroup as the default filegroup for new database objects like tables and indexes.\r\nUse this when restructuring storage layout or when you want new objects created in a specific filegroup instead of PRIMARY.", "", false, "false", "False", "" ], [ "ReadOnly", "Controls the read-only status of the filegroup to prevent data modifications for archival or compliance purposes.\r\nSet to $true for read-only (common for historical data), or $false to restore read-write access.", "", false, "false", "False", "" ], [ "AutoGrowAllFiles", "Enables proportional growth across all files in the filegroup when any file reaches its growth threshold.\r\nUse this to maintain balanced file sizes and prevent hotspots, especially important for tempdb and high-transaction filegroups.", "", false, "false", "False", "" ], [ "InputObject", "Accepts database or filegroup objects from Get-DbaDatabase or Get-DbaDbFileGroup via pipeline.\r\nUse this for efficient processing when working with multiple databases or filegroups from previous 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", "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", "Data", "Log", "File", "Growth" ], "CommandName": "Set-DbaDbFileGrowth", "Name": "Set-DbaDbFileGrowth", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Set-DbaDbFileGrowth [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-GrowthType] \u003cString\u003e] [[-Growth] \u003cInt32\u003e] [[-FileType] \u003cString\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database file that was modified. The output represents the updated file growth configuration after the changes have been applied.\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- MaxSize: Maximum size the file can grow to; displays as dbasize object (KB, MB, GB, TB)\r\n- GrowthType: How the file grows - either \"Percent\" or \"kb\"\r\n- Growth: The growth increment value (percentage if GrowthType is Percent, kilobytes if kb)\r\n- File: Logical name of the file within SQL Server\r\n- FileName: Operating system file path\r\n- State: Current state of the file (ONLINE, OFFLINE, etc.)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaDbFileGrowth -SqlInstance sql2016 -Database test -GrowthType GB -Growth 1\nSets the test database on sql2016 to a growth of 1GB\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2016 -Database test | Set-DbaDbFileGrowth -GrowthType GB -Growth 1\nSets the test database on sql2016 to a growth of 1GB\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDatabase | Set-DbaDbFileGrowth -SqlInstance sql2017, sql2016, sql2012\nSets all database files on sql2017, sql2016, sql2012 to 64MB.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eSet-DbaDbFileGrowth -SqlInstance sql2017, sql2016, sql2012 -Database test -WhatIf\nShows what would happen if the command were executed\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eSet-DbaDbFileGrowth -SqlInstance sql2017 -Database test -GrowthType GB -Growth 1 -FileType Data\nSets growth to 1GB for only data files for database test", "Description": "Configures database file auto-growth settings using ALTER DATABASE statements to replace default percentage-based growth with fixed-size increments. This prevents unpredictable growth patterns that can cause performance issues and storage fragmentation as databases grow larger. Defaults to 64MB growth increments, which provides better control over file expansion and reduces the risk of exponential growth that can quickly consume available disk space. You can target specific file types (data files, log files, or both) and specify custom growth values in KB, MB, GB, or TB units.", "Links": "https://dbatools.io/Set-DbaDbFileGrowth", "Synopsis": "Modifies auto-growth settings for database data and log files to use fixed-size increments instead of percentage-based growth.", "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 modify file growth settings for. Accepts an array of database names.\r\nUse this when you need to target specific databases rather than all databases on an instance.", "", false, "false", "", "" ], [ "GrowthType", "Specifies the unit of measurement for the growth increment. Valid values are KB, MB, GB, or TB.\r\nChoose the appropriate unit based on your database size and expected growth patterns - MB for smaller databases, GB for larger ones.", "", false, "false", "MB", "KB,MB,GB,TB" ], [ "Growth", "Sets the numeric value for the fixed growth increment. Defaults to 64 when combined with the default MB unit.\r\nUse smaller values (16-64MB) for smaller databases or larger values (256MB-1GB) for high-growth production databases to balance performance and storage efficiency.", "", false, "false", "64", "" ], [ "FileType", "Controls which file types to modify - Data files only, Log files only, or All files (both data and log).\r\nUse \u0027Data\u0027 when you need different growth settings for data vs log files, or \u0027All\u0027 to standardize growth across all database files.", "", false, "false", "All", "All,Data,Log" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase for pipeline operations.\r\nUse this when you need to filter databases first or when working with database objects from other dbatools functions.", "", 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": "DBCC", "CommandName": "Set-DbaDbIdentity", "Name": "Set-DbaDbIdentity", "Author": "Patrick Flynn (@sqllensman)", "Syntax": "Set-DbaDbIdentity [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-Table] \u003cString[]\u003e] [[-ReSeedValue] \u003cInt32\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per table checked or reseeded, containing the DBCC CHECKIDENT results and execution context.\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 table\r\n- Table: The table name in schema.table format\r\n- Cmd: The complete DBCC CHECKIDENT command that was executed\r\n- IdentityValue: The current identity value from DBCC output (the next value to be assigned)\r\n- ColumnValue: The maximum value found in the identity column (empty string when ReSeedValue is used)\r\n- Output: The complete raw output text from the DBCC CHECKIDENT command", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-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) to return the current identity value.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e \u0027Sql1\u0027,\u0027Sql2/sqlexpress\u0027 | Set-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) to return the current identity value.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$query = \"SELECT SCHEMA_NAME(t.schema_id) +\u0027.\u0027 + t.name AS TableName FROM sys.columns c INNER JOIN sys.tables t ON t.object_id = c.object_id WHERE is_identity = 1\"\nPS C:\\\u003e $IdentityTables = Invoke-DbaQuery -SqlInstance SQLServer2017 -Database AdventureWorks2014 -Query $query\r\nPS C:\\\u003e foreach ($tbl in $IdentityTables) {\r\nPS C:\\\u003e Set-DbaDbIdentity -SqlInstance SQLServer2017 -Database AdventureWorks2014 -Table $tbl.TableName\r\nPS C:\\\u003e }\nChecks the current identity value for all tables with an Identity in the AdventureWorks2014 database on the SQLServer2017 and, if it is needed, changes the identity value.", "Description": "Executes DBCC CHECKIDENT to verify the current identity value for tables with identity columns and optionally reseed them to a specific value.\nThis is essential after bulk data operations, imports, or deletes that can leave identity values out of sync with actual table data.\nWhen run without ReSeedValue, it reports the current identity value and the maximum value in the identity column.\nWhen ReSeedValue is specified, it resets the identity counter to prevent duplicate key errors or close identity gaps.\n\nRead more:\n - https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checkident-transact-sql", "Links": "https://dbatools.io/Set-DbaDbIdentity", "Synopsis": "Checks and resets identity column values 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 values. If not specified, all databases on the instance will be processed.\r\nWhen using ReSeedValue, only a single database can be specified since reseeding requires targeting a specific table location.", "", false, "false", "", "" ], [ "Table", "Specifies which tables with identity columns to check or reseed. Use schema.table format for tables not in the default schema.\r\nWhen using ReSeedValue, only a single table can be specified since each table\u0027s identity must be reseeded individually.", "", false, "false", "", "" ], [ "ReSeedValue", "Sets the next identity value that will be assigned to new rows in the specified table.\r\nUse this after bulk operations, deletes, or imports that leave gaps in identity sequences or when the identity value needs correction.", "", 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", "" ], [ "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": [ "Mirroring", "Mirror", "HA" ], "CommandName": "Set-DbaDbMirror", "Name": "Set-DbaDbMirror", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Set-DbaDbMirror [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-Partner] \u003cString\u003e] [[-Witness] \u003cString\u003e] [[-SafetyLevel] \u003cString\u003e] [[-State] \u003cString\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Database\nReturns the Database object only when the -State parameter is specified. When -State is used with Suspend, Resume, Failover, or RemoveWitness operations, the modified SMO Database object is returned \r\nto the pipeline.\nWhen only -Partner, -Witness, or -SafetyLevel parameters are specified, no output is returned (configuration-only operations with no object output).\nDefault display properties from the returned Database object 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 (computer\\instance)\r\n- Name: Database name\r\n- Status: Current database status (Normal, Offline, Recovering, etc.)\r\n- RecoveryModel: Database recovery model (Full, Simple, BulkLogged)\r\n- Owner: Database owner login name\nAll properties from the SMO Database object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaDbMirror -SqlInstance sql2005 -Database dbatools -Partner TCP://SQL2008.ad.local:5374\nPrompts for confirmation then sets the partner to TCP://SQL2008.ad.local:5374 for the database \"dbtools\"\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaDbMirror -SqlInstance sql2005 -Database dbatools -Witness TCP://SQL2012.ad.local:5502 -Confirm:$false\nDoes not prompt for confirmation and sets the witness to TCP://SQL2012.ad.local:5502 for the database \"dbtools\"\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2005 | Out-GridView -PassThru | Set-DbaDbMirror -SafetyLevel Full -Confirm:$false\nSets the safety level to Full for databases selected from a grid view. Does not prompt for confirmation.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eSet-DbaDbMirror -SqlInstance sql2005 -Database dbatools -State Suspend -Confirm:$false\nDoes not prompt for confirmation and sets the state to suspend for the database \"dbtools\"", "Description": "Modifies database mirroring configuration by setting the partner server, witness server, safety level, or changing the mirror state. This function lets you reconfigure existing mirrored databases without manually writing ALTER DATABASE statements. Use it to add or change witness servers for automatic failover, adjust safety levels between synchronous and asynchronous modes, or control mirror states like suspend, resume, and failover operations.", "Links": "https://dbatools.io/Set-DbaDbMirror", "Synopsis": "Configures database mirroring partner, witness, safety level, and operational state settings.", "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) to configure mirroring settings for. Accepts multiple database names.\r\nUse this to target specific mirrored databases when you need to modify partner, witness, safety level, or state settings.", "", false, "false", "", "" ], [ "Partner", "Sets the mirroring partner server endpoint in TCP://servername:port format. This establishes or changes the mirror partnership.\r\nUse this when setting up initial mirroring or changing the partner server after a configuration change or migration.", "", false, "false", "", "" ], [ "Witness", "Sets the witness server endpoint in TCP://servername:port format to enable automatic failover in high-safety mode.\r\nUse this to add witness functionality for automatic failover or to change the witness server location.", "", false, "false", "", "" ], [ "SafetyLevel", "Controls transaction safety mode: \u0027Full\u0027 for synchronous high-safety, \u0027Off\u0027 for asynchronous high-performance.\r\nUse \u0027Full\u0027 when you need zero data loss with automatic failover, or \u0027Off\u0027 for better performance with potential data loss during failover.", "", false, "false", "", "Full,Off,None" ], [ "State", "Changes the operational state of the mirroring session. Options include Suspend, Resume, Failover, or RemoveWitness.\r\nUse this to temporarily pause mirroring during maintenance, resume after suspension, perform manual failover, or remove witness functionality.", "", false, "false", "", "ForceFailoverAndAllowDataLoss,Failover,RemoveWitness,Resume,Suspend,Off" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase pipeline input for batch operations.\r\nUse this to configure mirroring settings across multiple databases efficiently by piping database objects from other dbatools 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", "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", "Owner", "DbOwner" ], "CommandName": "Set-DbaDbOwner", "Name": "Set-DbaDbOwner", "Author": "Michael Fal (@Mike_Fal), mikefal.net", "Syntax": "Set-DbaDbOwner [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-InputObject] \u003cDatabase[]\u003e] [[-TargetLogin] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database where the ownership was successfully changed. If a database owner is already set to the target login, no object is returned for that database. Only databases that were \r\nactually modified produce output.\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: The name of the database whose owner was changed\r\n- Owner: The login name that is now the database owner", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaDbOwner -SqlInstance localhost\nSets database owner to \u0027sa\u0027 on all databases where the owner does not match \u0027sa\u0027.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaDbOwner -SqlInstance localhost -TargetLogin DOMAIN\\account\nSets the database owner to DOMAIN\\account on all databases where the owner does not match DOMAIN\\account.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-DbaDbOwner -SqlInstance sqlserver -Database db1, db2\nSets database owner to \u0027sa\u0027 on the db1 and db2 databases if their current owner does not match \u0027sa\u0027.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$db = Get-DbaDatabase -SqlInstance localhost -Database db1, db2\nPS C:\\\u003e $db | Set-DbaDbOwner -TargetLogin DOMAIN\\account\nSets database owner to \u0027sa\u0027 on the db1 and db2 databases if their current owner does not match \u0027sa\u0027.", "Description": "Changes database ownership to standardize who owns your databases across an instance. This is particularly useful for maintaining consistent ownership patterns after restoring databases from other environments, where databases may have orphaned owners or inconsistent ownership.\n\nBy default, the function sets ownership to \u0027sa\u0027 (or the renamed sysadmin account), but you can specify any valid login. The function only processes user databases and includes safety checks to ensure the target login exists, isn\u0027t a Windows group, and isn\u0027t already mapped as a user within the database. You can target all databases on an instance or filter to specific databases.\n\nBest Practice reference: http://weblogs.sqlteam.com/dang/archive/2008/01/13/Database-Owner-Troubles.aspx", "Links": "https://dbatools.io/Set-DbaDbOwner", "Synopsis": "Changes database ownership to a specified login when current ownership doesn\u0027t match the target.", "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 change ownership for. Accepts database names and supports wildcards for pattern matching.\r\nWhen omitted, all user databases on the instance will be processed. System databases are automatically excluded.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies databases to skip during ownership changes. Useful when processing all databases but need to exclude specific ones.\r\nAccepts database names and supports wildcards for pattern matching.", "", false, "false", "", "" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase for pipeline operations. Use this when you need to filter databases with specific criteria before changing ownership.\r\nAllows for complex database selection logic beyond simple name matching.", "", false, "true (ByValue)", "", "" ], [ "TargetLogin", "Specifies the login to set as the new database owner. Defaults to \u0027sa\u0027 (or the renamed sysadmin account if sa was renamed).\r\nThe login must exist on the server, cannot be a Windows group, and cannot already be mapped as a user within the target database. Common values include service accounts or standardized admin logins.", "Login", 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": "Set-DbaDbQueryStoreOption", "Name": "Set-DbaDbQueryStoreOption", "Author": "Enrico van de Laar (@evdlaar) | Tracy Boggiano (@TracyBoggiano)", "Syntax": "Set-DbaDbQueryStoreOption [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-AllDatabases] [[-State] \u003cString[]\u003e] [[-FlushInterval] \u003cInt64\u003e] [[-CollectionInterval] \u003cInt64\u003e] [[-MaxSize] \u003cInt64\u003e] [[-CaptureMode] \u003cString[]\u003e] [[-CleanupMode] \u003cString[]\u003e] [[-StaleQueryThreshold] \u003cInt64\u003e] [[-MaxPlansPerQuery] \u003cInt64\u003e] [[-WaitStatsCaptureMode] \u003cString[]\u003e] [[-CustomCapturePolicyExecutionCount] \u003cInt64\u003e] [[-CustomCapturePolicyTotalCompileCPUTimeMS] \u003cInt64\u003e] [[-CustomCapturePolicyTotalExecutionCPUTimeMS] \u003cInt64\u003e] \r\n[[-CustomCapturePolicyStaleThresholdHours] \u003cInt64\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.QueryStoreOptions\nReturns one QueryStoreOptions object per database that was modified. The object is returned by Get-DbaDbQueryStoreOption after the Query Store configuration changes are applied, allowing you to \r\nimmediately verify the results of the configuration changes.\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:\\\u003eSet-DbaDbQueryStoreOption -SqlInstance ServerA\\SQL -State ReadWrite -FlushInterval 600 -CollectionInterval 10 -MaxSize 100 -CaptureMode All -CleanupMode Auto -StaleQueryThreshold 100 \r\n-AllDatabases\nConfigure the Query Store settings for all user databases in the ServerA\\SQL Instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaDbQueryStoreOption -SqlInstance ServerA\\SQL -FlushInterval 600\nOnly configure the FlushInterval setting for all Query Store databases in the ServerA\\SQL Instance.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-DbaDbQueryStoreOption -SqlInstance ServerA\\SQL -Database AdventureWorks -State ReadWrite -FlushInterval 600 -CollectionInterval 10 -MaxSize 100 -CaptureMode all -CleanupMode Auto \r\n-StaleQueryThreshold 100\nConfigure the Query Store settings for the AdventureWorks database in the ServerA\\SQL Instance.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eSet-DbaDbQueryStoreOption -SqlInstance ServerA\\SQL -Exclude AdventureWorks -State ReadWrite -FlushInterval 600 -CollectionInterval 10 -MaxSize 100 -CaptureMode all -CleanupMode Auto \r\n-StaleQueryThreshold 100\nConfigure the Query Store settings for all user databases except the AdventureWorks database in the ServerA\\SQL Instance.", "Description": "Modifies Query Store configuration options for one or more databases, allowing you to control how SQL Server captures, stores, and manages query execution statistics. Query Store acts as a performance data recorder, tracking query plans and runtime statistics over time for performance analysis and plan regression troubleshooting.\n\nThis function lets you set the operational state (enabled/disabled), adjust data collection intervals, configure storage limits, control which queries get captured, and manage data retention policies. You can also enable wait statistics capture and configure advanced custom capture policies in SQL Server 2019 and later.", "Links": "https://dbatools.io/Set-DbaDbQueryStoreOption", "Synopsis": "Configures Query Store settings to control query performance data collection and retention.", "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 databases to configure Query Store options for. Accepts database names, wildcards, or database objects from Get-DbaDatabase.\r\nUse this when you need to configure Query Store for specific databases instead of all user databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific databases from Query Store configuration changes. System databases (master, tempdb, model) are automatically excluded.\r\nUseful when you want to configure most databases but skip certain ones like staging or temporary databases.", "", false, "false", "", "" ], [ "AllDatabases", "Configures Query Store options for all user databases on the instance. System databases are automatically excluded.\r\nUse this switch when you want to apply consistent Query Store settings across all user databases without specifying individual database names.", "", false, "false", "False", "" ], [ "State", "Controls Query Store operational state: ReadWrite enables full data collection, ReadOnly preserves existing data but stops new collection, Off disables Query Store completely.\r\nSet to ReadWrite to start collecting query performance data, or ReadOnly when troubleshooting performance issues without adding new data overhead.", "", false, "false", "", "ReadWrite,ReadOnly,Off" ], [ "FlushInterval", "Sets how frequently Query Store flushes runtime statistics from memory to disk, in seconds. Default is 900 seconds (15 minutes).\r\nLower values provide more real-time data persistence but increase disk I/O; higher values reduce I/O but risk losing recent data during unexpected shutdowns.", "", false, "false", "0", "" ], [ "CollectionInterval", "Defines how often Query Store aggregates runtime statistics into discrete time intervals, in minutes. Default is 60 minutes.\r\nShorter intervals provide finer granularity for performance analysis but consume more storage; longer intervals reduce storage overhead but provide less detailed trending data.", "", false, "false", "0", "" ], [ "MaxSize", "Sets the maximum storage space Query Store can consume in the database, in megabytes. Default is 100 MB.\r\nConfigure based on your database size and query volume; busy OLTP databases may need several GB, while smaller databases can use the default.", "", false, "false", "0", "" ], [ "CaptureMode", "Determines which queries Query Store captures: Auto captures relevant queries based on execution count and resource consumption, All captures every query, None captures no new queries, Custom uses \r\ndefined capture policies (SQL 2019+).\r\nUse Auto for most production environments to avoid capturing trivial queries; use All for comprehensive troubleshooting or development environments.", "", false, "false", "", "Auto,All,None,Custom" ], [ "CleanupMode", "Controls automatic cleanup of old Query Store data when approaching the MaxSize limit: Auto removes oldest data first, Off disables automatic cleanup.\r\nSet to Auto to prevent Query Store from reaching capacity and stopping data collection; use Off only when you want manual control over data retention.", "", false, "false", "", "Auto,Off" ], [ "StaleQueryThreshold", "Specifies how many days Query Store retains data for queries that haven\u0027t executed recently, used by automatic cleanup processes.\r\nSet to 30-90 days for most environments; longer retention helps with historical analysis but consumes more space, shorter retention frees space faster.", "", false, "false", "0", "" ], [ "MaxPlansPerQuery", "Limits how many execution plans Query Store retains for each individual query. Default is 200 plans per query (SQL Server 2017+).\r\nHigher values help track plan variations in dynamic environments but consume more space; lower values reduce storage but may miss important plan changes.", "", false, "false", "0", "" ], [ "WaitStatsCaptureMode", "Enables or disables wait statistics collection in Query Store (SQL Server 2017+). Options are On or Off.\r\nEnable wait stats capture when you need detailed performance analysis including what queries are waiting for; disable to reduce overhead in high-throughput systems.", "", false, "false", "", "On,Off" ], [ "CustomCapturePolicyExecutionCount", "Sets minimum execution count threshold for capturing queries when CaptureMode is Custom (SQL Server 2019+). Queries must execute at least this many times to be captured.\r\nUse values like 5-10 to capture queries that run regularly but avoid one-time or rarely executed queries that don\u0027t impact performance.", "", false, "false", "0", "" ], [ "CustomCapturePolicyTotalCompileCPUTimeMS", "Sets minimum compilation CPU time threshold in milliseconds for capturing queries when CaptureMode is Custom (SQL Server 2019+).\r\nSet to values like 1000ms (1 second) to capture queries with significant compilation overhead, helping identify queries that need plan guides or parameter optimization.", "", false, "false", "0", "" ], [ "CustomCapturePolicyTotalExecutionCPUTimeMS", "Sets minimum total execution CPU time threshold in milliseconds for capturing queries when CaptureMode is Custom (SQL Server 2019+).\r\nUse values like 100ms to focus on queries consuming significant CPU resources, filtering out lightweight queries that don\u0027t impact overall performance.", "", false, "false", "0", "" ], [ "CustomCapturePolicyStaleThresholdHours", "Defines how many hours a query can remain inactive before Query Store stops tracking new statistics for it when CaptureMode is Custom (SQL Server 2019+).\r\nSet to 24-168 hours (1-7 days) to balance between capturing actively used queries and avoiding resource consumption on dormant queries.", "", 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", "" ], [ "WhatIf", "Shows what would happen if the command were to run", "wi", false, "false", "", "" ], [ "Confirm", "Prompts for confirmation of every step. For example:\nAre you sure you want to perform this action?\r\nPerforming the operation \"Changing Desired State\" on target \"pubs on SQL2016\\VNEXT\".\r\n[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is \"Y\"):", "cf", false, "false", "", "" ] ] }, { "Tags": [ "RecoveryModel", "Database" ], "CommandName": "Set-DbaDbRecoveryModel", "Name": "Set-DbaDbRecoveryModel", "Author": "Viorel Ciucu (@viorelciucu), cviorel.com", "Syntax": "Set-DbaDbRecoveryModel [-SqlCredential \u003cPSCredential\u003e] -RecoveryModel \u003cString\u003e [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-AllDatabases] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nSet-DbaDbRecoveryModel -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] -RecoveryModel \u003cString\u003e [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-AllDatabases] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nSet-DbaDbRecoveryModel [-SqlCredential \u003cPSCredential\u003e] -RecoveryModel \u003cString\u003e [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-AllDatabases] [-EnableException] -InputObject \u003cDatabase[]\u003e [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Database\nReturns one SMO Database object for each database where the recovery model was set. The returned objects show the updated database with the new recovery model applied.\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, or BulkLogged) - this will be the newly set value\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 the result of Get-DbaDbRecoveryModel called for each updated database. When the recovery model is already set to the specified value, an error is issued and no output is returned \r\nfor that database. When -WhatIf is used, no output objects are returned.\nAll other properties from the underlying SMO Database object remain accessible via Select-Object * even though only the properties listed above are displayed by default.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaDbRecoveryModel -SqlInstance sql2014 -RecoveryModel BulkLogged -Database model -Confirm:$true -Verbose\nSets the Recovery Model to BulkLogged for database [model] on SQL Server instance sql2014. User is requested to confirm the action.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2014 -Database TestDB | Set-DbaDbRecoveryModel -RecoveryModel Simple -Confirm:$false\nSets the Recovery Model to Simple for database [TestDB] on SQL Server instance sql2014. Confirmation is not required.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-DbaDbRecoveryModel -SqlInstance sql2014 -RecoveryModel Simple -Database TestDB -Confirm:$false\nSets the Recovery Model to Simple for database [TestDB] on SQL Server instance sql2014. Confirmation is not required.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eSet-DbaDbRecoveryModel -SqlInstance sql2014 -RecoveryModel Simple -AllDatabases -Confirm:$false\nSets the Recovery Model to Simple for ALL user and system databases (except TEMPDB) on SQL Server instance sql2014. Runs without asking for confirmation.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eSet-DbaDbRecoveryModel -SqlInstance sql2014 -RecoveryModel BulkLogged -Database TestDB1, TestDB2 -Confirm:$false -Verbose\nSets the Recovery Model to BulkLogged for [TestDB1] and [TestDB2] databases on SQL Server instance sql2014. Runs without asking for confirmation.", "Description": "Changes the recovery model setting for one or more databases, allowing you to switch between Simple, Full, and BulkLogged recovery modes. This is commonly used when preparing databases for different backup strategies, reducing transaction log growth in development environments, or configuring production databases for point-in-time recovery. The function excludes tempdb and database snapshots automatically, and requires explicit database specification for safety.", "Links": "https://dbatools.io/Set-DbaDbRecoveryModel", "Synopsis": "Changes the recovery model for specified databases on SQL Server instances.", "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", "", "" ], [ "RecoveryModel", "Sets the recovery model for the specified databases. Choose Simple for minimal transaction log usage in development environments, Full for production databases requiring point-in-time recovery, or \r\nBulkLogged for bulk operations with reduced logging.\r\nThis change affects backup strategy requirements and transaction log growth patterns for the target databases.", "", true, "false", "", "Simple,Full,BulkLogged" ], [ "Database", "Specifies which databases to change the recovery model for. Accepts database names as strings or wildcard patterns.\r\nUse this when you need to target specific databases instead of all databases on the instance. Required unless using -AllDatabases.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies databases to skip when changing recovery models. Useful when combined with -AllDatabases to exclude specific databases.\r\nCommonly used to exclude databases that should maintain their current recovery model for operational reasons.", "", false, "false", "", "" ], [ "AllDatabases", "Required switch when you want to change the recovery model for all databases on the instance.\r\nThis safety parameter prevents accidentally modifying all databases without explicit confirmation. Automatically excludes tempdb and database snapshots.", "", 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", "" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase or similar commands through the pipeline.\r\nUse this when you need to apply recovery model changes to a filtered set of databases based on specific criteria like size, last backup date, or other properties.", "", true, "true (ByValue)", "", "" ], [ "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", "Prompts for confirmation. For example:\nAre you sure you want to perform this action?\r\nPerforming the operation \"ALTER DATABASE [model] SET RECOVERY Full\" on target \"[model] on WERES14224\".\r\n[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is \"Y\"):", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Schema", "Database" ], "CommandName": "Set-DbaDbSchema", "Name": "Set-DbaDbSchema", "Author": "Adam Lancaster, github.com/lancasteradam", "Syntax": "Set-DbaDbSchema [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [-Schema] \u003cString[]\u003e [-SchemaOwner] \u003cString\u003e [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Schema\nReturns one Schema object for each schema updated. The returned schema objects are the updated SMO objects after the owner has been changed and the Alter() method has been applied.\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 that was updated\r\n- IsSystemObject: Boolean indicating if this is a built-in system schema or custom user-defined schema\r\n- Owner: The new owner of the schema (updated to the value specified by -SchemaOwner)\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- 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. When -WhatIf is used, no output objects are returned.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaDbSchema -SqlInstance sqldev01 -Database example1 -Schema TestSchema1 -SchemaOwner dbatools\nUpdates the TestSchema1 schema in the example1 database in the sqldev01 instance. The dbatools user will be the new owner of the schema.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sqldev01, sqldev02 -Database example1 | Set-DbaDbSchema -Schema TestSchema1, TestSchema2 -SchemaOwner dbatools\nPasses in the example1 db via pipeline and updates the TestSchema1 and TestSchema2 schemas and assigns the dbatools user as the owner of the schemas.", "Description": "Modifies the ownership of database schemas by updating the schema owner property in SQL Server. This is commonly needed when reorganizing database security, transferring ownership from developers to service accounts, or standardizing schema ownership after database migrations. The function works by retrieving the schema object and updating its Owner property through SQL Server Management Objects, then applying the change to the database.", "Links": "https://dbatools.io/Set-DbaDbSchema", "Synopsis": "Changes the owner of database schemas to reassign security and object ownership responsibilities", "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 contain the schemas to be updated. Required when using SqlInstance parameter.\r\nUse this to target specific databases where you need to change schema ownership.", "", false, "false", "", "" ], [ "Schema", "Specifies the name(s) of the database schemas whose ownership will be changed. Accepts multiple schema names.\r\nCommon scenarios include transferring ownership from developers to service accounts or standardizing ownership after migrations.", "", true, "false", "", "" ], [ "SchemaOwner", "Specifies the database user or role that will become the new owner of the specified schemas. Must be a valid database principal.\r\nTypically used to assign ownership to service accounts, application users, or standardized roles like db_owner.", "", true, "false", "", "" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase via pipeline input. Use this to work with database objects already retrieved.\r\nUseful when you want to filter databases first or work with databases from multiple instances in a single 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", "" ], [ "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": "Set-DbaDbSequence", "Name": "Set-DbaDbSequence", "Author": "Adam Lancaster, github.com/lancasteradam", "Syntax": "Set-DbaDbSequence [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [-Sequence] \u003cString[]\u003e [[-Schema] \u003cString\u003e] [[-RestartWith] \u003cInt64\u003e] [[-IncrementBy] \u003cInt64\u003e] [[-MinValue] \u003cInt64\u003e] [[-MaxValue] \u003cInt64\u003e] [-Cycle] [[-CacheSize] \u003cInt32\u003e] [[-InputObject] \u003cDatabase[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Sequence\nReturns the updated Sequence object for each modified sequence, with all properties reflecting the changes applied.\nDefault display properties (when piping to Select-Object):\r\n- Name: The name of the sequence object\r\n- Schema: The schema containing the sequence\r\n- Owner: The principal that owns the sequence\r\n- StartValue: The starting value for the sequence\r\n- CurrentValue: The current value of the sequence\r\n- IncrementValue: The increment applied with each 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 if the sequence cycles after reaching MinValue or MaxValue\r\n- SequenceCacheType: The cache setting (NoCache, CacheWithSize, or DefaultCache)\r\n- CacheSize: The number of pre-allocated values (when applicable)\nAll properties from the SMO Sequence object are accessible using Select-Object *. Additional properties include:\r\n- CreationDate: DateTime when the sequence was created\r\n- LastModificationTime: DateTime when the sequence was last modified\r\n- Urn: The Uniform Resource Name (URN) of the sequence object\r\n- State: The SMO object state (Existing, Creating, Pending, Dropping, etc.)\r\n- Parent: Reference to the parent Database object", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaDbSequence -SqlInstance sqldev01 -Database TestDB -Sequence TestSequence -RestartWith 10000 -IncrementBy 10\nModifies the sequence TestSequence in the TestDB database on the sqldev01 instance. The sequence will restart with 10000 and increment by 10.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sqldev01 -Database TestDB | Set-DbaDbSequence -Sequence TestSequence -Schema TestSchema -Cycle\nUsing a pipeline this command modifies the sequence named TestSchema.TestSequence in the TestDB database on the sqldev01 instance. The sequence will now cycle the sequence values.", "Description": "Modifies existing SQL Server sequence objects by updating their properties such as increment value, restart point, minimum and maximum bounds, cycling behavior, and cache settings. This function is essential when you need to adjust sequence behavior after deployment, fix increment issues, or optimize performance without recreating the sequence and losing its current state.", "Links": "https://dbatools.io/Set-DbaDbSequence", "Synopsis": "Modifies properties of existing SQL Server sequence objects", "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 target database containing the sequence to modify. Accepts multiple database names.\r\nRequired when using SqlInstance parameter to identify which database contains the sequence.", "", false, "false", "", "" ], [ "Sequence", "Specifies the name of the sequence object to modify. This is the sequence you want to update properties for.\r\nMust be an existing sequence in the specified schema, otherwise the function will fail.", "Name", true, "false", "", "" ], [ "Schema", "Specifies the schema containing the sequence to modify. Defaults to \u0027dbo\u0027 if not specified.\r\nUse this when your sequence exists in a custom schema rather than the default dbo schema.", "", false, "false", "dbo", "" ], [ "RestartWith", "Sets the next value the sequence will return when NEXT VALUE FOR is called. Immediately resets the sequence to this value.\r\nUse this to fix sequence gaps, realign sequences after data imports, or reset sequences for testing.", "", false, "false", "0", "" ], [ "IncrementBy", "Sets how much the sequence value increases (or decreases if negative) with each NEXT VALUE FOR call.\r\nCommon values are 1 for sequential numbering or larger values for reserving ranges. Cannot be zero.", "", false, "false", "0", "" ], [ "MinValue", "Sets the lowest value the sequence can generate. Once reached, sequence behavior depends on the Cycle setting.\r\nUse this to establish data range constraints or prevent sequences from going below business-required minimums.", "", false, "false", "0", "" ], [ "MaxValue", "Sets the highest value the sequence can generate. Once reached, sequence behavior depends on the Cycle setting.\r\nUse this to prevent sequences from exceeding data type limits or business-defined maximum values.", "", false, "false", "0", "" ], [ "Cycle", "Enables the sequence to restart from MinValue after reaching MaxValue (or vice versa for negative increments).\r\nUse this for scenarios like rotating through a fixed set of values or when sequences need to wrap around.", "", false, "false", "False", "" ], [ "CacheSize", "Sets the number of sequence values SQL Server pre-allocates in memory for faster access.\r\nUse 0 to disable caching (guarantees no gaps but slower performance), or specify a number for high-performance scenarios. Omit this parameter to let SQL Server choose an optimal cache size.", "", false, "false", "0", "" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase via pipeline to modify sequences across multiple databases.\r\nUse this for batch operations when you need to modify the same sequence in multiple 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", "" ], [ "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", "State" ], "CommandName": "Set-DbaDbState", "Name": "Set-DbaDbState", "Author": "Simone Bizzotto (@niphold)", "Syntax": "Set-DbaDbState [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-AllDatabases] [-ReadOnly] [-ReadWrite] [-Online] [-Offline] [-Emergency] [-Detached] [-SingleUser] [-RestrictedUser] [-MultiUser] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nSet-DbaDbState -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-AllDatabases] [-ReadOnly] [-ReadWrite] [-Online] [-Offline] [-Emergency] [-Detached] [-SingleUser] [-RestrictedUser] [-MultiUser] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nSet-DbaDbState [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-AllDatabases] [-ReadOnly] [-ReadWrite] [-Online] [-Offline] [-Emergency] [-Detached] [-SingleUser] [-RestrictedUser] [-MultiUser] [-Force] [-EnableException] -InputObject \u003cPSObject[]\u003e [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database modified, with 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 (computer\\instance format)\r\n- DatabaseName: The name of the database that was modified\r\n- RW: The read/write access mode (READ_ONLY or READ_WRITE)\r\n- Status: The database status (ONLINE, OFFLINE, EMERGENCY, or DETACHED)\r\n- Access: The user access mode (SINGLE_USER, RESTRICTED_USER, or MULTI_USER)\r\n- Notes: Error details if the state change failed; null if successful (semicolon-separated list if multiple errors)\r\n- Database: The SMO Database object (not displayed by default but accessible)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaDbState -SqlInstance sqlserver2014a -Database HR -Offline\nSets the HR database as OFFLINE\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaDbState -SqlInstance sqlserver2014a -AllDatabases -Exclude HR -ReadOnly -Force\nSets all databases of the sqlserver2014a instance, except for HR, as READ_ONLY\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDbState -SqlInstance sql2016 | Where-Object Status -eq \u0027Offline\u0027 | Set-DbaDbState -Online\nFinds all offline databases and sets them to online\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eSet-DbaDbState -SqlInstance sqlserver2014a -Database HR -SingleUser\nSets the HR database as SINGLE_USER\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eSet-DbaDbState -SqlInstance sqlserver2014a -Database HR -SingleUser -Force\nSets the HR database as SINGLE_USER, dropping all other connections (and rolling back open transactions)\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sqlserver2014a -Database HR | Set-DbaDbState -SingleUser -Force\nGets the databases from Get-DbaDatabase, and sets them as SINGLE_USER, dropping all other connections (and rolling back open transactions)", "Description": "Modifies database access modes and availability states through ALTER DATABASE commands, eliminating the need to write T-SQL manually for common database administration tasks.\n\nThis function handles three categories of database state changes:\n- Read/Write access: Sets databases to READ_ONLY for reporting scenarios or READ_WRITE for normal operations\n- Online status: Brings databases ONLINE, takes them OFFLINE for maintenance, or sets EMERGENCY mode for corruption recovery\n- User access: Restricts database access to SINGLE_USER for maintenance, RESTRICTED_USER for admin-only access, or MULTI_USER for normal operations\n- Database detachment: Safely detaches databases by first removing them from Availability Groups and breaking mirroring relationships when -Force is specified\n\nThe -Force parameter rolls back open transactions immediately, allowing state changes to proceed even when active connections exist. Without -Force, operations use NO_WAIT and may fail if connections are blocking the change.\n\nReturns an object with SqlInstance, Database, RW, Status, Access, and Notes properties. The Notes field contains error details when state changes fail.", "Links": "https://dbatools.io/Set-DbaDbState", "Synopsis": "Modifies database read/write access, online status, and user access modes", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances", "", 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, "false", "", "" ], [ "Database", "Specifies which databases to modify state for. Accepts single database name, comma-separated list, or wildcards.\r\nUse this when you need to target specific databases instead of all user databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific databases from the state change operation when using -AllDatabases.\r\nUseful when you want to modify most databases but skip critical production databases or those undergoing maintenance.", "", false, "false", "", "" ], [ "AllDatabases", "Indicates that the operation should target all user databases on the instance.\r\nRequired safety parameter to prevent accidental modification of all databases when no specific database is specified.", "", false, "false", "False", "" ], [ "ReadOnly", "Sets the database to read_ONLY mode, preventing any data modifications.\r\nUse this for creating reporting databases, preparing for backups, or when you need to ensure data integrity during maintenance.", "", false, "false", "False", "" ], [ "ReadWrite", "Sets the database to read_WRITE mode, allowing normal data modifications.\r\nUse this to restore normal operations after maintenance or to enable writes on a previously read-only database.", "", false, "false", "False", "" ], [ "Online", "Brings the database online and makes it available for normal operations.\r\nUse this to restore database availability after maintenance, upgrades, or recovery operations.", "", false, "false", "False", "" ], [ "Offline", "Takes the database offline, making it inaccessible to users and applications.\r\nUse this for maintenance tasks like file moves, hardware upgrades, or when you need to ensure no connections during critical operations.", "", false, "false", "False", "" ], [ "Emergency", "Sets the database to EMERGENCY mode for corruption recovery scenarios.\r\nUse this when the database won\u0027t start normally due to corruption and you need to attempt data recovery or run emergency repairs.", "", false, "false", "False", "" ], [ "Detached", "Safely detaches the database from the SQL Server instance, removing it from sys.databases.\r\nUse this when moving databases between instances or when you need to work with database files directly. Requires -Force for mirrored or AG databases.", "", false, "false", "False", "" ], [ "SingleUser", "Restricts database access to a single connection, typically for administrative tasks.\r\nUse this during maintenance operations, database restores, or when you need exclusive access to prevent user interference.", "", false, "false", "False", "" ], [ "RestrictedUser", "Limits database access to members of db_owner, dbcreator, or sysadmin roles only.\r\nUse this during maintenance windows when you need to allow admin access while blocking regular users.", "", false, "false", "False", "" ], [ "MultiUser", "Restores normal multi-user access to the database, allowing all authorized connections.\r\nUse this to return the database to normal operations after completing single-user or restricted-user maintenance tasks.", "", false, "false", "False", "" ], [ "Force", "Rolls back open transactions immediately and kills active connections to allow the state change to proceed.\r\nUse this when normal state changes fail due to blocking connections, but be aware it will cause transaction rollbacks and connection drops.\r\nRequired for detaching databases that are in Availability Groups or mirroring relationships.", "", 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", "" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase or Get-DbaDbState through the pipeline.\r\nUse this to chain commands together, allowing you to filter databases first then modify their states in a single operation.", "", true, "true (ByValue)", "", "" ], [ "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", "Data", "Logs", "Backup" ], "CommandName": "Set-DbaDefaultPath", "Name": "Set-DbaDefaultPath", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Set-DbaDefaultPath [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Type] \u003cString[]\u003e] [-Path] \u003cString\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance where changes were committed. The object contains the current default path settings for the specified 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- Data: The current default path for new database data files (from $server.DefaultFile)\r\n- Log: The current default path for new database log files (from $server.DefaultLog)\r\n- Backup: The current default path for backup operations (from $server.BackupDirectory)\nNote: When changing Data or Log paths, the SQL Server service must be restarted for changes to take effect. Backup path changes are immediate.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaDefaultPath -SqlInstance sql01\\sharepoint -Type Data, Backup -Path C:\\mssql\\sharepoint\\data\nSets the data and backup default paths on sql01\\sharepoint to C:\\mssql\\sharepoint\\data\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaDefaultPath -SqlInstance sql01\\sharepoint -Type Data, Log -Path C:\\mssql\\sharepoint\\data -WhatIf\nShows what what happen if the command would have run", "Description": "Modifies the server-level default paths that SQL Server uses when creating new databases or performing backups without specifying explicit locations. This eliminates the need to manually specify file paths for routine database operations and ensures consistent placement of files across your environment.\n\nThe function validates that the specified path is accessible to the SQL Server service account before making changes. When changing data or log paths, a SQL Server service restart is required for the changes to take effect. Backup path changes are immediate.\n\nTo change the error log location, use Set-DbaStartupParameter", "Links": "https://dbatools.io/Set-DbaDefaultPath", "Synopsis": "Configures the default file paths for new databases and backups on SQL Server instances", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", 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, "false", "", "" ], [ "Type", "Specifies which default path types to configure: Data (new database data files), Log (new database log files), or Backup (backup operations).\r\nUse Data and Log when standardizing database file locations across instances or moving files to faster storage.\r\nBackup path changes take effect immediately, while Data and Log changes require a SQL Server service restart.", "", false, "true (ByPropertyName)", "", "Data,Backup,Log" ], [ "Path", "The directory path where SQL Server will create new database files or backups by default.\r\nMust be a valid path accessible to the SQL Server service account with appropriate permissions.\r\nUse UNC paths for shared storage or local paths like C:\\Data for dedicated storage volumes.", "", true, "true (ByPropertyName)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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": "Endpoint", "CommandName": "Set-DbaEndpoint", "Name": "Set-DbaEndpoint", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Set-DbaEndpoint [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Endpoint] \u003cString[]\u003e] [[-Owner] \u003cString\u003e] [[-Type] \u003cString\u003e] [-AllEndpoints] [[-InputObject] \u003cEndpoint[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Endpoint\nReturns one modified Endpoint object for each endpoint that was changed. The endpoint object reflects the updated property values after the Alter() operation is committed.\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 endpoint\r\n- EndpointType: The type of endpoint (DatabaseMirroring, ServiceBroker, Soap, or TSql)\r\n- ProtocolType: The communication protocol used by the endpoint\r\n- Owner: The login name that owns the endpoint\r\n- IsSystemObject: Boolean indicating if this is a system endpoint\r\n- CreateDate: DateTime when the endpoint was created\nAll properties from the SMO Endpoint object are accessible using Select-Object * for more detailed analysis.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaEndpoint -SqlInstance sql2016 -AllEndpoints -Owner sa\nSets all endpoint owners to sa on sql2016\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaEndpoint -SqlInstance sql2016 -Endpoint ep1 | Set-DbaEndpoint -Type TSql\nChanges the endpoint type to Tsql on endpoint ep1", "Description": "Modifies properties of existing SQL Server endpoints such as changing the owner for security compliance or switching the endpoint type between DatabaseMirroring, ServiceBroker, Soap, and TSql protocols. This is commonly used when transferring endpoint ownership during security audits, changing communication protocols for availability group configurations, or updating Service Broker endpoints for application messaging. The function works with specific endpoints by name or can target all endpoints on an instance, making it useful for bulk administrative changes across your SQL Server environment.", "Links": "https://dbatools.io/Set-DbaEndpoint", "Synopsis": "Modifies SQL Server endpoint properties including owner and protocol type.", "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", "", "" ], [ "Endpoint", "Specifies the name(s) of specific endpoints to modify. Accepts multiple endpoint names and wildcards for pattern matching. Use when you need to update only certain endpoints rather than all endpoints \r\non the instance.", "", false, "false", "", "" ], [ "Owner", "Specifies the new login name to assign as the endpoint owner. Common during security compliance audits when transferring endpoint ownership from individual accounts to service accounts or when \r\nstandardizing endpoint ownership across your environment.", "", false, "false", "", "" ], [ "Type", "Changes the endpoint protocol type between DatabaseMirroring, ServiceBroker, Soap, or TSql. Use DatabaseMirroring for availability group configurations, ServiceBroker for application messaging, TSql \r\nfor custom client connections, or Soap for web service integrations.", "", false, "false", "", "DatabaseMirroring,ServiceBroker,Soap,TSql" ], [ "AllEndpoints", "Modifies all endpoints found on the target SQL Server instance. Useful for bulk administrative changes like standardizing endpoint ownership or protocol types across your entire server environment.", "", false, "false", "False", "" ], [ "InputObject", "Accepts endpoint objects from the pipeline, typically from Get-DbaEndpoint. This allows you to filter endpoints with Get-DbaEndpoint first, then pipe the results for modification, providing precise \r\ncontrol over which endpoints get updated.", "", 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": [ "Instance", "ErrorLog", "Logging" ], "CommandName": "Set-DbaErrorLogConfig", "Name": "Set-DbaErrorLogConfig", "Author": "Shawn Melton (@wsmelton), wsmelton.github.com", "Syntax": "Set-DbaErrorLogConfig [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-LogCount] \u003cInt32\u003e] [[-LogSize] \u003cInt32\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance containing the current error log configuration settings.\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 in computer\\instance format\r\n- LogCount: The number of error log files SQL Server retains (integer between 6 and 99)\r\n- LogSize: The maximum size of each error log file in kilobytes; returns as dbasize object for automatic unit formatting\nThe LogCount and LogSize properties reflect the values after any modifications requested by the parameters. If no parameters are specified, the command returns the current configuration values \r\nwithout changes.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaErrorLogConfig -SqlInstance sql2017,sql2014 -LogCount 25\nSets the number of error log files to 25 on sql2017 and sql2014\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaErrorLogConfig -SqlInstance sql2014 -LogSize 102400\nSets the size of the error log file, before it rolls over, to 102400 KB (100 MB) on sql2014\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-DbaErrorLogConfig -SqlInstance sql2012 -LogCount 25 -LogSize 500\nSets the number of error log files to 25 and size before it will roll over to 500 KB on sql2012", "Description": "Configures how SQL Server manages its error log files by setting retention count and automatic rollover size. You can specify how many error log files to keep (6-99) across all SQL Server versions, and set the file size limit in KB for automatic rollover on SQL Server 2012 and later.\n\nThis helps DBAs manage disk space and ensure adequate error log history for troubleshooting without manual intervention. When a log file reaches the specified size limit, SQL Server automatically creates a new error log and archives the previous one.\n\nTo set the Path to the ErrorLog, use Set-DbaStartupParameter -ErrorLog. Note that this command requires\nremote, administrative access to the Windows/WMI server, similar to SQL Configuration Manager.", "Links": "https://dbatools.io/Set-DbaErrorLogConfig", "Synopsis": "Configures SQL Server error log retention and size rollover settings", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances", "", 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, "false", "", "" ], [ "LogCount", "Sets the number of error log files SQL Server retains before deleting the oldest ones. Must be between 6 and 99.\r\nUse this to balance disk space with troubleshooting history - more files provide longer history but consume more disk space.", "", false, "false", "0", "" ], [ "LogSize", "Sets the maximum size in KB for each error log file before SQL Server automatically creates a new log file. Only available on SQL Server 2012 and later.\r\nUse this to prevent error logs from growing too large and to ensure regular log rotation without manual intervention.", "", 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", "" ], [ "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": [ "General", "ExtendedProperties" ], "CommandName": "Set-DbaExtendedProperty", "Name": "Set-DbaExtendedProperty", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Set-DbaExtendedProperty [-InputObject] \u003cExtendedProperty[]\u003e [-Value] \u003cString\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.ExtendedProperty\nReturns the updated ExtendedProperty object for each extended property modified. The returned object reflects all changes made by the Alter() method.\nDefault properties returned:\r\n- Name: The name of the extended property\r\n- Value: The updated value that was set\nAdditional properties available (from SMO ExtendedProperty object):\r\n- ID: The identifier of the extended property\r\n- Parent: The parent object that this extended property is attached to\r\n- State: The current state of the SMO object (Existing, Creating, Pending, etc.)\r\n- Urn: The Uniform Resource Name (URN) of the extended property\r\n- Properties: Collection of SQL Server object properties\nAll properties from the base SMO ExtendedProperty object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance localhost -Database mydb | Get-DbaExtendedProperty -Name appversion | Set-DbaExtendedProperty -Value \"1.1.0\"\nSets the value of appversion to 1.1.0 on the mydb database\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaDbTable -SqlInstance localhost -Database mydb -Table mytable | Get-DbaExtendedProperty -Name appversion | Set-DbaExtendedProperty -Value \"1.1.0\"\nSets the value of appversion to 1.1.0 on the mytable table of the mydb database", "Description": "Updates the value of existing extended properties on SQL Server database objects. Extended properties store custom metadata like application versions, documentation, or business rules directly with database objects. This function modifies the values of properties that already exist, making it useful for maintaining application version numbers, updating documentation, or batch-modifying metadata across multiple objects.\n\nWorks with extended properties on all SQL Server object types including databases, tables, views, stored procedures, functions, columns, indexes, schemas, and many others. The function accepts extended property objects from Get-DbaExtendedProperty through the pipeline, so you can easily filter and update specific properties across your environment.", "Links": "https://dbatools.io/Set-DbaExtendedProperty", "Synopsis": "Updates the value of existing extended properties on SQL Server database objects", "Availability": "Windows, Linux, macOS", "Params": [ [ "InputObject", "Accepts extended property objects from Get-DbaExtendedProperty to update their values. Use this to pipeline specific extended properties that you want to modify.\r\nTypically used after filtering extended properties by name, object type, or other criteria to batch update property values across multiple database objects.", "", true, "true (ByValue)", "", "" ], [ "Value", "Specifies the new value to assign to the extended property. Accepts any string value including version numbers, descriptions, or configuration data.\r\nCommon uses include updating application version numbers, modifying documentation text, or changing configuration values stored as extended properties.", "", 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": [ "Instance", "Security" ], "CommandName": "Set-DbaExtendedProtection", "Name": "Set-DbaExtendedProtection", "Author": "Claudio Silva (@claudioessilva), claudioessilva.eu", "Syntax": "Set-DbaExtendedProtection [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-Value] \u003cObject\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per target SQL Server instance containing the Extended Protection configuration that was applied.\nProperties:\r\n- ComputerName: The computer name where the registry change was made\r\n- InstanceName: The SQL Server instance name (e.g., MSSQLSERVER, SQL2019)\r\n- SqlInstance: The full SQL Server instance name in computer\\instance format\r\n- ExtendedProtection: The Extended Protection setting value with human-readable description (e.g., \"0 - Off\", \"1 - Allowed\", \"2 - Required\")", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaExtendedProtection\nSet Extended Protection of SQL Engine on the default (MSSQLSERVER) instance on localhost to \"Off\". Requires (and checks for) RunAs admin.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaExtendedProtection -Value Required\nSet Extended Protection of SQL Engine on the default (MSSQLSERVER) instance on localhost to \"Required\". Requires (and checks for) RunAs admin.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-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.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eSet-DbaExtendedProtection -SqlInstance sql01\\SQL2008R2SP2 -Value Allowed\nSet Extended Protection of SQL Engine for the SQL2008R2SP2 on sql01 to \"Allowed\". Uses Windows Credentials to both connect and modify the registry.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eSet-DbaExtendedProtection -SqlInstance sql01\\SQL2008R2SP2 -WhatIf\nShows what would happen if the command were executed.", "Description": "Modifies the Extended Protection registry setting for SQL Server network protocols to enhance connection security. Extended Protection helps prevent authentication relay attacks by requiring additional authentication at the network protocol level.\n\nThis security feature is particularly useful in environments where you need to protect against man-in-the-middle attacks or when connecting over untrusted networks. When set to \"Required\", clients must support Extended Protection to connect, which may require updating older applications or connection strings.\n\nThe function modifies Windows registry values directly and requires administrative privileges on the target server. Changes take effect immediately for new connections without requiring a SQL Server restart. This setting 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/Set-DbaExtendedProtection", "Synopsis": "Configures Extended Protection for Authentication on SQL Server network protocols", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Allows you to login to the computer (not SQL Server instance) using alternative Windows credentials", "", false, "false", "", "" ], [ "Value", "Specifies the Extended Protection level for SQL Server network protocols. Accepts \"Off\", \"Allowed\", or \"Required\" (or equivalent integers 0, 1, 2).\r\nUse \"Off\" to disable Extended Protection, \"Allowed\" to accept both protected and unprotected connections, or \"Required\" to enforce Extended Protection for all client connections.\r\nDefaults to \"Off\" when not specified. Setting to \"Required\" may prevent older applications from connecting unless they support Extended Protection authentication.", "", false, "false", "Off", "0,Off,1,Allowed,2,Required" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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": "Login", "CommandName": "Set-DbaLogin", "Name": "Set-DbaLogin", "Author": "Sander Stad (@sqlstad), sqlstad.nl", "Syntax": "Set-DbaLogin [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Login] \u003cString[]\u003e] [[-SecurePassword] \u003cObject\u003e] [[-PasswordHash] \u003cString\u003e] [[-DefaultDatabase] \u003cString\u003e] [-Unlock] [-PasswordMustChange] [[-NewName] \u003cString\u003e] [-Disable] [-Enable] [-DenyLogin] [-GrantLogin] [-PasswordPolicyEnforced] [-PasswordExpirationEnabled] [[-AddRole] \u003cString[]\u003e] [[-RemoveRole] \u003cString[]\u003e] [[-InputObject] \u003cLogin[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Login\nReturns one modified Login object for each login that was modified. The object includes information about the changes made and the current state of the login 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- Name: Login name\r\n- DenyLogin: Boolean indicating if login is denied access to the instance\r\n- IsDisabled: Boolean indicating if the login is disabled\r\n- IsLocked: Boolean indicating if the login is locked due to failed authentication attempts\r\n- PasswordPolicyEnforced: Boolean indicating if Windows password policy is enforced for the login\r\n- PasswordExpirationEnabled: Boolean indicating if password expiration is enforced for the login\r\n- MustChangePassword: Boolean indicating if the password must be changed at next login\r\n- PasswordChanged: Boolean indicating if the password was changed in this operation\r\n- ServerRole: Comma-separated list of server roles assigned to the login\r\n- Notes: String containing any notes or errors encountered during the operation\nAdditional properties available (from SMO Login object):\r\n- LoginType: Type of login (SqlLogin, WindowsUser, WindowsGroup, Certificate, AsymmetricKey)\r\n- DefaultDatabase: Default database the login connects to\r\n- CreateDate: DateTime when the login was created\r\n- DateLastModified: DateTime of the last modification\r\n- PasswordExpirationEnabled: Password expiration setting\r\n- PasswordPolicyEnforced: Password policy enforcement setting\r\n- DaysSinceLastLogin: Number of days since the login last authenticated\r\n- Sid: Security identifier for the login\nAll properties from the base SMO Login object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$SecurePassword = (Get-Credential NoUsernameNeeded).Password\nPS C:\\\u003e $cred = New-Object System.Management.Automation.PSCredential (\"username\", $SecurePassword)\r\nPS C:\\\u003e Set-DbaLogin -SqlInstance sql1 -Login login1 -SecurePassword $cred -Unlock -PasswordMustChange\nSet the new password for login1 using a credential, unlock the account and set the option\r\nthat the user must change password at next logon.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaLogin -SqlInstance sql1 -Login login1 -Enable\nEnable the login\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-DbaLogin -SqlInstance sql1 -Login login1, login2, login3, login4 -Enable\nEnable multiple logins\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eSet-DbaLogin -SqlInstance sql1, sql2, sql3 -Login login1, login2, login3, login4 -Enable\nEnable multiple logins on multiple instances\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eSet-DbaLogin -SqlInstance sql1 -Login login1 -Disable\nDisable the login\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eSet-DbaLogin -SqlInstance sql1 -Login login1 -DenyLogin\nDeny the login to connect to the instance\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eSet-DbaLogin -SqlInstance sql1 -Login login1 -GrantLogin\nGrant the login to connect to the instance\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eSet-DbaLogin -SqlInstance sql1 -Login login1 -PasswordPolicyEnforced\nEnforces the password policy on a login\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003eSet-DbaLogin -SqlInstance sql1 -Login login1 -PasswordPolicyEnforced:$false\nDisables enforcement of the password policy on a login\n-------------------------- EXAMPLE 10 --------------------------\nPS C:\\\u003eSet-DbaLogin -SqlInstance sql1 -Login test -AddRole serveradmin\nAdd the server role \"serveradmin\" to the login\n-------------------------- EXAMPLE 11 --------------------------\nPS C:\\\u003eSet-DbaLogin -SqlInstance sql1 -Login test -RemoveRole bulkadmin\nRemove the server role \"bulkadmin\" to the login\n-------------------------- EXAMPLE 12 --------------------------\nPS C:\\\u003e$login = Get-DbaLogin -SqlInstance sql1 -Login test\nPS C:\\\u003e $login | Set-DbaLogin -Disable\nDisable the login from the pipeline\n-------------------------- EXAMPLE 13 --------------------------\nPS C:\\\u003eSet-DbaLogin -SqlInstance sql1 -Login login1 -DefaultDatabase master\nSet the default database to master on a login\n-------------------------- EXAMPLE 14 --------------------------\nPS C:\\\u003eSet-DbaLogin -SqlInstance sql1 -Login login1 -Unlock -Force\nUnlocks the login1 on the sql1 instance using the technique described at https://www.mssqltips.com/sqlservertip/2758/how-to-unlock-a-sql-login-without-resetting-the-password/\n-------------------------- EXAMPLE 15 --------------------------\nPS C:\\\u003e$hash = \"0x02001234567890ABCDEF...\"\nPS C:\\\u003e Set-DbaLogin -SqlInstance sql2 -Login login1 -PasswordHash $hash\nSets the password for login1 on sql2 using a hashed password value from another instance\n-------------------------- EXAMPLE 16 --------------------------\nPS C:\\\u003e$sourceLogin = Get-DbaLogin -SqlInstance sql1 -Login app_user\nPS C:\\\u003e $hash = Get-LoginPasswordHash -Login $sourceLogin\r\nPS C:\\\u003e Set-DbaLogin -SqlInstance sql2 -Login app_user -PasswordHash $hash\nGets the password hash from sql1 and applies it to sql2, syncing the password between instances", "Description": "Manages SQL Server login accounts by modifying passwords, account status, security settings, and server role memberships in a single operation. Handles common DBA tasks like unlocking accounts, resetting passwords with force-change requirements, and applying password policies for security compliance. Includes a special unlock feature that preserves existing passwords by temporarily disabling policy checks, eliminating the need to reset passwords when unlocking accounts. Works across multiple instances and logins simultaneously, making it ideal for bulk user management and security maintenance workflows.", "Links": "https://dbatools.io/Set-DbaLogin", "Synopsis": "Modifies SQL Server login properties including passwords, permissions, roles, and account status", "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.", "", 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", "", "" ], [ "Login", "Specifies one or more SQL Server login names to modify. Accepts an array for batch operations.\r\nUse this to target specific login accounts when performing password resets, account management, or role assignments.", "", false, "false", "", "" ], [ "SecurePassword", "Sets a new password for the login using either a PSCredential object or SecureString. Required when using -PasswordMustChange.\r\nCreate secure passwords with Get-Credential or ConvertTo-SecureString to avoid plain text exposure in scripts.", "Password", false, "false", "", "" ], [ "PasswordHash", "Sets the login password using a hashed password value (0x...). This is used for transferring logins between instances without knowing the actual password.\r\nThe hash must be in the format returned by Get-LoginPasswordHash or extracted from sys.sql_logins. Cannot be used with -SecurePassword or -PasswordMustChange.", "", false, "false", "", "" ], [ "DefaultDatabase", "Changes the default database that the login connects to after authentication. Must be an existing database name.\r\nUse this when users need to land in a specific database instead of master, such as application-specific databases.", "DefaultDB", false, "false", "", "" ], [ "Unlock", "Unlocks a locked SQL Server login account that has been disabled due to failed authentication attempts.\r\nUse with -SecurePassword to set a new password while unlocking, or with -Force to unlock without changing the password.", "", false, "false", "False", "" ], [ "PasswordMustChange", "Forces the user to change their password at next login. Requires -SecurePassword and both PasswordPolicyEnforced and PasswordExpirationEnabled to be enabled.\r\nUse this for security compliance when setting temporary passwords or after potential password compromises.", "MustChange", false, "false", "False", "" ], [ "NewName", "Renames the login to a new name. The new name must not already exist on the SQL Server instance.\r\nUse this when standardizing login naming conventions or correcting login names during organizational changes.", "", false, "false", "", "" ], [ "Disable", "Disables the login account, preventing authentication while preserving the account and its permissions.\r\nUse this for temporary account suspension during investigations or when employees are on extended leave.", "", false, "false", "False", "" ], [ "Enable", "Enables a previously disabled login account, restoring authentication access with all existing permissions intact.\r\nUse this to reactivate accounts after temporary suspension or when employees return from extended leave.", "", false, "false", "False", "" ], [ "DenyLogin", "Explicitly denies the login permission to connect to the SQL Server instance. The account remains but cannot authenticate.\r\nUse this for permanent access restriction while maintaining the login for audit trails or future reference.", "", false, "false", "False", "" ], [ "GrantLogin", "Grants or restores the login permission to connect to the SQL Server instance, reversing a previous deny action.\r\nUse this to restore access for logins that were previously denied without recreating the entire account.", "", false, "false", "False", "" ], [ "PasswordPolicyEnforced", "Enables or disables Windows password policy enforcement for the login (check_policy). Must be enabled to use password expiration checks.\r\nUse this to apply corporate password complexity and lockout policies to SQL Server authentication accounts.", "", false, "false", "False", "" ], [ "PasswordExpirationEnabled", "Enables or disables password expiration checking for the login (check_expiration). Requires PasswordPolicyEnforced to be enabled first.\r\nUse this to enforce regular password changes according to Windows password age policies for SQL Server accounts.", "", false, "false", "False", "" ], [ "AddRole", "Grants one or more server-level roles to the login. Accepts: bulkadmin, dbcreator, diskadmin, processadmin, public, securityadmin, serveradmin, setupadmin, sysadmin.\r\nUse this to assign specific server privileges without granting full sysadmin rights, following the principle of least privilege.", "", false, "false", "", "bulkadmin,dbcreator,diskadmin,processadmin,public,securityadmin,serveradmin,setupadmin,sysadmin" ], [ "RemoveRole", "Revokes one or more server-level roles from the login. Accepts: bulkadmin, dbcreator, diskadmin, processadmin, public, securityadmin, serveradmin, setupadmin, sysadmin.\r\nUse this to reduce login privileges during access reviews or when job responsibilities change.", "", false, "false", "", "bulkadmin,dbcreator,diskadmin,processadmin,public,securityadmin,serveradmin,setupadmin,sysadmin" ], [ "InputObject", "Accepts login objects from Get-DbaLogin for pipeline operations. Enables processing multiple logins from filtered queries.\r\nUse this for bulk operations when you need to modify logins based on specific criteria like locked status or role membership.", "", false, "true (ByValue)", "", "" ], [ "Force", "Unlocks a login account without requiring a password reset by temporarily manipulating password policy settings.\r\nUse this when you need to unlock accounts but cannot change the password, preserving the original password for the user.", "", 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": [ "MaxDop", "Utility" ], "CommandName": "Set-DbaMaxDop", "Name": "Set-DbaMaxDop", "Author": "Claudio Silva (@claudioessilva)", "Syntax": "Set-DbaMaxDop [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-MaxDop] \u003cInt32\u003e] [[-InputObject] \u003cPSObject\u003e] [-AllDatabases] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per configuration change applied (either instance-level or database-level). The object structure and properties vary based on whether database-scoped or instance-level \r\nconfiguration is being modified.\nInstance-level MaxDOP configuration (default):\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- PreviousInstanceMaxDopValue: The MaxDOP value before this change\r\n- CurrentInstanceMaxDop: The newly configured MaxDOP value (number of processors)\nDatabase-level MaxDOP configuration (SQL Server 2016+, with -Database, -AllDatabases, or -ExcludeDatabase):\nProperties:\r\n- InstanceName: The SQL Server instance name\r\n- Database: The name of the database with the new MaxDOP setting\r\n- PreviousDatabaseMaxDopValue: The MaxDOP value for this database before this change\r\n- CurrentDatabaseMaxDopValue: The newly configured MaxDOP value for this database", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaMaxDop -SqlInstance sql2008, sql2012\nSets Max DOP to the recommended value for servers sql2008 and sql2012.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaMaxDop -SqlInstance sql2014 -MaxDop 4\nSets Max DOP to 4 for server sql2014.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaMaxDop -SqlInstance sql2008 | Set-DbaMaxDop\nGets the recommended Max DOP from Test-DbaMaxDop and applies it to to sql2008.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eSet-DbaMaxDop -SqlInstance sql2016 -Database db1\nSet recommended Max DOP for database db1 on server sql2016.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eSet-DbaMaxDop -SqlInstance sql2016 -AllDatabases\nSet recommended Max DOP for all databases on server sql2016.", "Description": "Configures the max degree of parallelism setting to control how many processors SQL Server uses for parallel query execution. Without a specified value, the function automatically applies recommended settings based on your server\u0027s hardware configuration using Test-DbaMaxDop. This prevents performance issues caused by excessive parallelism on multi-core servers, especially in OLTP environments where parallel queries can create more overhead than benefit. For SQL Server 2016 and higher, you can set database-scoped MaxDOP configurations to fine-tune performance for specific workloads.", "Links": "https://dbatools.io/Set-DbaMaxDop", "Synopsis": "Configures SQL Server maximum degree of parallelism (MaxDOP) at instance or database level", "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 configure with database-scoped MaxDOP settings. Only works on SQL Server 2016 and higher.\r\nUse this when you need different MaxDOP values for specific databases with unique workload characteristics.\r\nCannot be combined with AllDatabases or ExcludeDatabase parameters.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies which databases to skip when applying database-scoped MaxDOP settings. Only works on SQL Server 2016 and higher.\r\nUse this when you want to configure most databases but leave certain ones (like system databases) unchanged.\r\nCannot be combined with Database or AllDatabases parameters.", "", false, "false", "", "" ], [ "MaxDop", "Sets a specific MaxDOP value instead of using the recommended value from Test-DbaMaxDop.\r\nUse this when you have specific performance requirements or want to override the automatic recommendations.\r\nCommon values are 1 (disable parallelism), 2-4 (typical OLTP), or higher values for data warehouse workloads.", "", false, "false", "-1", "" ], [ "InputObject", "Accepts the output from Test-DbaMaxDop to avoid re-analyzing server hardware and current settings.\r\nUse this when you want to review the recommendations first or apply settings from a previously saved analysis.\r\nCan be piped directly from Test-DbaMaxDop for streamlined workflows.", "", false, "true (ByValue)", "", "" ], [ "AllDatabases", "Applies database-scoped MaxDOP settings to all databases on the instance. Only works on SQL Server 2016 and higher.\r\nUse this when you want consistent MaxDOP values across all databases rather than relying on instance-level settings.\r\nCannot be combined with Database or ExcludeDatabase parameters.", "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", "" ], [ "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": [ "MaxMemory", "Memory" ], "CommandName": "Set-DbaMaxMemory", "Name": "Set-DbaMaxMemory", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Set-DbaMaxMemory [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Max] \u003cInt32\u003e] [[-InputObject] \u003cPSObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance showing the configured memory settings. This object is derived from Test-DbaMaxMemory output with added tracking properties.\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- Total: Total system memory available on the server in megabytes\r\n- MaxValue: The newly configured SQL Server max memory setting in megabytes\r\n- PreviousMaxValue: The previous SQL Server max memory setting in megabytes before this change", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaMaxMemory sqlserver1\nSet max memory to the recommended on just one server named \"sqlserver1\"\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaMaxMemory -SqlInstance sqlserver1 -Max 2048\nExplicitly set max memory to 2048 on just one server, \"sqlserver1\"\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaRegServer -SqlInstance sqlserver | Test-DbaMaxMemory | Where-Object { $_.MaxValue -gt $_.Total } | Set-DbaMaxMemory\nFind all servers in SQL Server Central Management Server that have Max SQL memory set to higher than the total memory\r\nof the server (think 2147483647), then pipe those to Set-DbaMaxMemory and use the default recommendation.", "Description": "Modifies the SQL Server \u0027Max Server Memory\u0027 configuration to prevent SQL Server from consuming all available system memory.\nThis setting controls how much memory SQL Server can allocate for its buffer pool and other memory consumers, leaving\nadequate memory for the operating system and other applications.\n\nWhen no explicit value is provided, the function calculates an optimal recommendation using a proven formula that reserves\nmemory based on total system RAM. This formula accounts for operating system overhead, scales appropriately for servers\nwith different memory configurations, and can handle multiple SQL Server instances on the same server.\n\nInspired by Jonathan Kehayias\u0027s post about SQL Server Max memory (http://bit.ly/sqlmemcalc), this uses a formula to\ndetermine the default optimum RAM to use, then sets the SQL max value to that number.\n\nJonathan notes that the formula used provides a *general recommendation* that doesn\u0027t account for everything that may\nbe going on in your specific environment.", "Links": "https://dbatools.io/Set-DbaMaxMemory", "Synopsis": "Configures SQL Server \u0027Max Server Memory\u0027 setting using calculated recommendations or explicit values", "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", "", "" ], [ "Max", "Specifies the explicit maximum memory value in megabytes for SQL Server to use. When provided, this overrides the automatic memory recommendation calculation.\r\nUse this when you need a specific memory allocation that differs from the calculated recommendation, such as reserving memory for other applications or setting conservative limits for shared servers.", "", false, "false", "0", "" ], [ "InputObject", "Accepts output objects from Test-DbaMaxMemory containing memory analysis results for one or more SQL Server instances.\r\nUse this to pipeline memory testing results directly into memory configuration, allowing you to review recommendations before applying changes.", "", 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 cmdlet runs. The cmdlet is not run.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before running the cmdlet.", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Certificate", "Security" ], "CommandName": "Set-DbaNetworkCertificate", "Name": "Set-DbaNetworkCertificate", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Set-DbaNetworkCertificate [-SqlInstance \u003cDbaInstanceParameter[]\u003e] [-Credential \u003cPSCredential\u003e] [-RestartService] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nSet-DbaNetworkCertificate [-SqlInstance \u003cDbaInstanceParameter[]\u003e] [-Credential \u003cPSCredential\u003e] -Certificate \u003cX509Certificate2\u003e [-RestartService] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nSet-DbaNetworkCertificate [-SqlInstance \u003cDbaInstanceParameter[]\u003e] [-Credential \u003cPSCredential\u003e] -Thumbprint \u003cString\u003e [-RestartService] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance processed, containing the following properties:\n- ComputerName: The name of the computer where the SQL Server instance is hosted\r\n- InstanceName: The SQL Server instance name (e.g., MSSQLSERVER, SQL2008R2SP2)\r\n- SqlInstance: The full SQL Server instance name (computer\\instance)\r\n- ServiceAccount: The service account running the SQL Server instance\r\n- CertificateThumbprint: The SHA-1 thumbprint of the newly configured certificate in lowercase\r\n- Notes: Summary of actions performed, including whether an old certificate was replaced and which service account was granted read permissions", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eNew-DbaComputerCertificate | Set-DbaNetworkCertificate -SqlInstance localhost\\SQL2008R2SP2\nCreates and imports a new certificate signed by an Active Directory CA on localhost then sets the network certificate for the SQL2008R2SP2 to that newly created certificate.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaNetworkCertificate -SqlInstance sql1\\SQL2008R2SP2 -Thumbprint 1223FB1ACBCA44D3EE9640F81B6BA14A92F3D6E2\nSets the network certificate for the SQL2008R2SP2 instance to the certificate with the thumbprint of 1223FB1ACBCA44D3EE9640F81B6BA14A92F3D6E2 in LocalMachine\\My on sql1", "Description": "Sets the network certificate for SQL Server instance. This setting is found in Configuration Manager.\n\nThis command also grants read permissions for the service account on the certificate\u0027s private key.\n\nReferences:\nhttps://www.itprotoday.com/sql-server/7-steps-ssl-encryption\nhttps://azurebi.jppp.org/2016/01/23/using-lets-encrypt-certificates-for-secure-sql-server-connections/\nhttps://blogs.msdn.microsoft.com/sqlserverfaq/2016/09/26/creating-and-registering-ssl-certificates/", "Links": "https://dbatools.io/Set-DbaNetworkCertificate", "Synopsis": "Sets the network certificate for SQL Server instance", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. Defaults to localhost.", "ComputerName", false, "true (ByPropertyName)", "$env:COMPUTERNAME", "" ], [ "Credential", "Allows you to login to the computer (not sql instance) using alternative credentials.", "", false, "true (ByPropertyName)", "", "" ], [ "Certificate", "Specifies the X509Certificate2 object to configure as the network certificate for SQL Server.\r\nUse this when piping certificate objects from other dbatools commands like New-DbaComputerCertificate.\r\nThe certificate must exist in the LocalMachine certificate store and have a private key for SQL Server to use it for SSL connections.", "", true, "true (ByValue)", "", "" ], [ "Thumbprint", "Specifies the thumbprint (SHA-1 hash) of the certificate to configure as the network certificate.\r\nUse this when you know the specific certificate thumbprint from certificates already installed in LocalMachine\\My.\r\nThe certificate must have a private key and the SQL Server service account will be granted read permissions to it.", "", true, "true (ByPropertyName)", "", "" ], [ "RestartService", "Forces an automatic restart of the SQL Server service after setting the network certificate.\r\nCertificate changes require a service restart to take effect - without this switch you\u0027ll need to manually restart SQL Server.\r\nUse this when you want the SSL configuration to be immediately active, but be aware it will cause a brief service interruption.", "", 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": [ "Network", "Connection", "SQLWMI" ], "CommandName": "Set-DbaNetworkConfiguration", "Name": "Set-DbaNetworkConfiguration", "Author": "Andreas Jordan (@JordanOrdix), ordix.de", "Syntax": "Set-DbaNetworkConfiguration [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-Credential \u003cPSCredential\u003e] [-EnableProtocol \u003cString\u003e] [-DisableProtocol \u003cString\u003e] [-DynamicPortForIPAll] [-StaticPortForIPAll \u003cInt32[]\u003e] [-IpAddress \u003cString[]\u003e] [-RestartService] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nSet-DbaNetworkConfiguration [-Credential \u003cPSCredential\u003e] [-RestartService] -InputObject \u003cObject[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance whose network configuration was modified, containing the details of changes applied and service restart 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 (computer\\instance format)\r\n- Changes: Array of strings describing each configuration change made (e.g., \"Changed TcpIpEnabled to True\")\r\n- RestartNeeded: Boolean indicating whether a SQL Server service restart is required for changes to take effect\r\n- Restarted: Boolean indicating whether the SQL Server service was successfully restarted\r\n- Exception: System.Exception object if an error occurred during WMI operations (may be present if changes failed)\nAll configuration changes require a SQL Server service restart to become active. If RestartNeeded is True and Restarted is False, you must manually restart the SQL Server service for the new settings \r\nto take effect.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaNetworkConfiguration -SqlInstance sql2016 -EnableProtocol SharedMemory -RestartService\nEnsures that the shared memory network protocol for the default instance on sql2016 is enabled.\r\nRestarts the service if needed.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaNetworkConfiguration -SqlInstance sql2016\\test -StaticPortForIPAll 14331, 14332 -RestartService\nEnsures that the TCP/IP network protocol is enabled and configured to use the ports 14331 and 14332 for all IP addresses.\r\nRestarts the service if needed.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$netConf = Get-DbaNetworkConfiguration -SqlInstance sqlserver2014a\nPS C:\\\u003e $netConf.TcpIpProperties.KeepAlive = 60000\r\nPS C:\\\u003e $netConf | Set-DbaNetworkConfiguration -RestartService -Confirm:$false\nChanges the value of the KeepAlive property for the default instance on sqlserver2014a and restarts the service.\r\nDoes not prompt for confirmation.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eSet-DbaNetworkConfiguration -SqlInstance sql2016\\test -IpAddress 192.168.3.41:1433 -RestartService\nEnsures that the TCP/IP network protocol is enabled and configured to only listen on port 1433 of IP address 192.168.3.41.\r\nRestarts the service if needed.", "Description": "Modifies SQL Server network protocol settings through WMI, allowing you to enable or disable network protocols and configure TCP/IP properties like static or dynamic ports. This replaces the need to manually use SQL Server Configuration Manager for network changes.\n\nCommon DBA scenarios include switching instances from dynamic to static ports for firewall rules, enabling TCP/IP for remote connections, or configuring specific IP addresses for multi-homed servers. You can also pass modified objects from Get-DbaNetworkConfiguration to make complex property changes.\n\nNetwork configuration changes require a SQL Server service restart to take effect - use the RestartService parameter to handle this automatically, otherwise you\u0027ll need to restart the service manually afterward.\n\nUses remote SQL WMI by default with PowerShell remoting as a fallback. Requires administrative privileges on the target server.\n\nFor detailed property explanations see: https://docs.microsoft.com/en-us/sql/tools/configuration-manager/sql-server-network-configuration", "Links": "https://dbatools.io/Set-DbaNetworkConfiguration", "Synopsis": "Modifies SQL Server network protocol settings including TCP/IP, Named Pipes, and Shared Memory configurations.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "false", "", "" ], [ "Credential", "Credential object used to connect to the Computer as a different user.", "", false, "false", "", "" ], [ "EnableProtocol", "Enables a specific SQL Server network protocol for client connections.\r\nUse SharedMemory for local-only connections, NamedPipes for legacy applications, or TcpIp for remote access.\r\nTCP/IP is required for remote connections and most modern applications.", "", false, "false", "", "SharedMemory,NamedPipes,TcpIp" ], [ "DisableProtocol", "Disables a specific SQL Server network protocol to prevent client connections via that method.\r\nCommonly used to disable unneeded protocols for security or troubleshooting purposes.\r\nBe cautious disabling TCP/IP as it will prevent all remote connections to the instance.", "", false, "false", "", "SharedMemory,NamedPipes,TcpIp" ], [ "DynamicPortForIPAll", "Configures the instance to use a random port assigned by Windows for all IP addresses.\r\nUse this for non-production environments or when you don\u0027t need predictable port numbers.\r\nAutomatically enables TCP/IP protocol and sets ListenAll to true, clearing any existing static port configuration.", "", false, "false", "False", "" ], [ "StaticPortForIPAll", "Configures the instance to use specific port numbers for all IP addresses instead of dynamic ports.\r\nEssential for production environments where firewall rules require predictable port numbers.\r\nAutomatically enables TCP/IP protocol and sets ListenAll to true. Accepts multiple ports as comma-separated values.", "", false, "false", "", "" ], [ "IpAddress", "Restricts the instance to listen only on specified IP addresses instead of all available interfaces.\r\nUse this on multi-homed servers to control which network interfaces accept SQL Server connections.\r\nFormat as \"192.168.1.10\" for dynamic ports or \"192.168.1.10:1433\" for static ports. IPv6 addresses need square brackets like \"[::1]:1433\".", "", false, "false", "", "" ], [ "RestartService", "Automatically restarts the SQL Server service when network configuration changes are made.\r\nNetwork configuration changes only take effect after a service restart, so use this to avoid manual restarts.\r\nWithout this parameter, you must manually restart the SQL Server service for changes to become active.", "", false, "false", "False", "" ], [ "InputObject", "Accepts a network configuration object from Get-DbaNetworkConfiguration for making complex property changes.\r\nUse this when you need to modify specific TCP/IP properties like KeepAlive values or make multiple configuration changes.\r\nThe Get-DbaNetworkConfiguration command must use -OutputType Full to provide the complete configuration object.", "", 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", "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": [ "PowerPlan", "OS", "Configure", "Utility" ], "CommandName": "Set-DbaPowerPlan", "Name": "Set-DbaPowerPlan", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Set-DbaPowerPlan [-ComputerName] \u003cDbaInstanceParameter[]\u003e [[-Credential] \u003cPSCredential\u003e] [[-PowerPlan] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per computer processed, containing the power plan configuration result. The object shows the power plan before and after the operation, allowing you to verify which computers had \r\ntheir power plan changed.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The target computer name\r\n- PreviousPowerPlan: The name of the power plan that was active before the operation\r\n- ActivePowerPlan: The name of the current active power plan (same as PreviousPowerPlan if no change, updated if changed)\r\n- IsChanged: Boolean indicating whether the power plan was changed (True if changed, False if already set to the target plan)\nAdditional properties available using Select-Object *:\r\n- PreviousInstanceId: The unique GUID identifier of the power plan that was active before the operation\r\n- ActiveInstanceId: The unique GUID identifier of the current active power plan", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaPowerPlan -ComputerName sql2017\nSets the Power Plan to High Performance. Skips it if its already set.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027Server1\u0027, \u0027Server2\u0027 | Set-DbaPowerPlan -PowerPlan Balanced\nSets the Power Plan to Balanced for Server1 and Server2. Skips it if its already set.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$cred = Get-Credential \u0027Domain\\User\u0027\nPS C:\\\u003e Set-DbaPowerPlan -ComputerName sql2017 -Credential $cred\nConnects using alternative Windows credential and sets the Power Plan to High Performance. Skips it if its already set.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eSet-DbaPowerPlan -ComputerName sqlcluster -PowerPlan \u0027Maximum Performance\u0027\nSets the Power Plan to \"Maximum Performance\". Skips it if its already set.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaPowerPlan -ComputerName oldserver | Set-DbaPowerPlan -ComputerName newserver1, newserver2\nUses the Power Plan of oldserver as best practice and sets the Power Plan of newserver1 and newserver2 accordingly.", "Description": "Changes the Windows power plan on SQL Server host machines using WMI and PowerShell remoting. Defaults to High Performance, which prevents CPU throttling that can severely impact database query performance and response times.\n\nWindows power plans control CPU frequency scaling, and the default \"Balanced\" plan can cause significant performance degradation under SQL Server workloads. This function ensures your SQL Server hosts are configured for optimal performance rather than power savings.\n\nIf your organization has a custom power plan considered best practice, you can specify it with -PowerPlan. The function will skip computers that already have the target power plan active.\n\nReferences:\nhttps://support.microsoft.com/en-us/kb/2207548\nhttp://www.sqlskills.com/blogs/glenn/windows-power-plan-effects-on-newer-intel-processors/", "Links": "https://dbatools.io/Set-DbaPowerPlan", "Synopsis": "Configures Windows power plan on SQL Server host computers to optimize database performance.", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the Windows host computers where SQL Server instances are running to configure the power plan.\r\nAccepts multiple server names and connects via WMI and PowerShell remoting to change OS-level power settings.\r\nUse the actual Windows computer names, not SQL Server instance names.", "", true, "true (ByValue, ByPropertyName)", "", "" ], [ "Credential", "Specifies a PSCredential object to use in authenticating to the server(s), instead of the current user account.", "", false, "true (ByPropertyName)", "", "" ], [ "PowerPlan", "Specifies the Windows power plan to set on the target computers. Defaults to \"High Performance\" when not specified.\r\nUse this when your organization has a custom power plan or specific requirements beyond the default recommendation.\r\nRun Get-DbaPowerPlan -ComputerName \u003cserver\u003e -List to see all available power plans on each computer before setting.", "CustomPowerPlan,RecommendedPowerPlan", false, "true (ByPropertyName)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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": [ "Privilege", "Security" ], "CommandName": "Set-DbaPrivilege", "Name": "Set-DbaPrivilege", "Author": "Klaas Vandenberghe (@PowerDbaKlaas)", "Syntax": "Set-DbaPrivilege [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-Type] \u003cString[]\u003e [-EnableException] [[-User] \u003cString\u003e] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "None\nThis command performs configuration operations and does not return any objects to the pipeline. Status and informational messages are displayed through Write-Message during execution (visible at \r\nVerbose level).", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaPrivilege -ComputerName sqlserver2014a -Type LPIM,IFI\nAdds the SQL Service account(s) on computer sqlserver2014a to the local privileges \u0027SeManageVolumePrivilege\u0027 and \u0027SeLockMemoryPrivilege\u0027.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027sql1\u0027,\u0027sql2\u0027,\u0027sql3\u0027 | Set-DbaPrivilege -Type IFI\nAdds the SQL Service account(s) on computers sql1, sql2 and sql3 to the local privilege \u0027SeManageVolumePrivilege\u0027.", "Description": "Configures critical Windows privileges for SQL Server service accounts including Lock Pages in Memory (LPIM), Instant File Initialization (IFI), Logon as Batch, Logon as Service, and Generate Security Audits. These privileges are essential for SQL Server performance optimization and proper service operation, eliminating the need to manually configure them through Local Security Policy. The function automatically discovers SQL service accounts on target computers or allows you to specify custom accounts, then uses secedit to update the local security policy.\n\nRequires Local Admin rights on destination computer(s).", "Links": "https://dbatools.io/Set-DbaPrivilege", "Synopsis": "Grants essential Windows privileges to SQL Server service accounts for optimal performance and security.", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "The target SQL Server instance or instances.", "cn,host,Server", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Credential object used to connect to the computer as a different user.", "", false, "false", "", "" ], [ "Type", "Specifies which Windows privileges to grant to the SQL Server service accounts. Accepts one or more values: \u0027IFI\u0027 (Instant File Initialization), \u0027LPIM\u0027 (Lock Pages in Memory), \u0027BatchLogon\u0027 (Log on as \r\na batch job), \u0027SecAudit\u0027 (Generate security audits), and \u0027ServiceLogon\u0027 (Log on as a service).\r\nThese privileges are essential for SQL Server performance and functionality - IFI speeds up database file operations, LPIM prevents memory paging for better performance, and the logon rights ensure \r\nservices can start properly.\r\nMultiple privileges can be specified together for comprehensive SQL Server optimization.", "", true, "false", "", "IFI,LPIM,BatchLogon,SecAudit,ServiceLogon" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\nUsing this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch.", "", false, "false", "False", "" ], [ "User", "Specifies a custom user account to receive the privileges instead of automatically discovering SQL Server service accounts.\r\nUse this when you need to grant privileges to a specific account that will run SQL Server services, or when the automatic service account detection doesn\u0027t work in your environment.\r\nAccepts domain accounts (DOMAIN\\User) or local accounts - ensure the account exists and will be used by SQL Server services.", "", 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": "ResourceGovernor", "CommandName": "Set-DbaResourceGovernor", "Name": "Set-DbaResourceGovernor", "Author": "John McCall (@lowlydba), lowlydba.com", "Syntax": "Set-DbaResourceGovernor [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Enabled] [-Disabled] [[-ClassifierFunction] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.ResourceGovernor\nReturns the modified Resource Governor object reflecting the new enabled/disabled state and classifier function assignment. Output is piped from Get-DbaResourceGovernor which provides detailed \r\nconfiguration details.\nDefault display properties (via Get-DbaResourceGovernor):\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- Enabled: Boolean indicating if Resource Governor is currently enabled\r\n- ClassifierFunction: Name of the classifier function currently assigned (NULL if none)\r\n- RecoveryPriority: Recovery priority setting for resource allocation\r\n- State: Current state of the Resource Governor (Existing, Creating, etc.)\nAll properties from the base SMO ResourceGovernor object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaResourceGovernor -SqlInstance sql2016 -Enabled\nSets Resource Governor to enabled for the instance sql2016.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaResourceGovernor -SqlInstance sql2012\\dev1 -Disabled\nSets Resource Governor to disabled for the instance dev1 on sq2012.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-DbaResourceGovernor -SqlInstance sql2012\\dev1 -ClassifierFunction \u0027fnRGClassifier\u0027 -Enabled\nSets Resource Governor to enabled for the instance dev1 on sq2012 and sets the classifier function to be \u0027fnRGClassifier\u0027.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eSet-DbaResourceGovernor -SqlInstance sql2012\\dev1 -ClassifierFunction \u0027NULL\u0027 -Enabled\nSets Resource Governor to enabled for the instance dev1 on sq2012 and sets the classifier function to be NULL.", "Description": "Configures Resource Governor settings at the SQL Server instance level to control CPU, memory, and I/O resource allocation for different workloads. Resource Governor requires both being enabled on the instance and having an optional classifier function that determines which resource pool and workload group incoming sessions should use based on login properties, application name, or other criteria.\n\nThis function handles the two-step Resource Governor setup process: enabling the feature and optionally assigning a classifier function. The classifier function must be a user-defined function in the master database that returns a workload group name or ID. Without a classifier function, all sessions use the default workload group.\n\nCommonly used when implementing resource management policies to prevent resource-intensive queries from impacting critical applications, or to allocate guaranteed resources to specific users or applications during peak usage periods.", "Links": "https://dbatools.io/Set-DbaResourceGovernor", "Synopsis": "Configures SQL Server Resource Governor to control workload resource allocation and sets classifier functions.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Credential object used to connect to the Windows server as a different user", "Credential", false, "false", "", "" ], [ "Enabled", "Enables Resource Governor on the SQL Server instance to activate workload resource management.\r\nUse this when you need to enforce resource limits and allocations for different workload groups.", "", false, "false", "False", "" ], [ "Disabled", "Disables Resource Governor on the SQL Server instance, removing all resource controls and workload management.\r\nAll sessions will use unlimited resources from the default resource pool when Resource Governor is disabled.", "", false, "false", "False", "" ], [ "ClassifierFunction", "Specifies the name of a user-defined function in the master database that determines which workload group incoming sessions should use.\r\nThe function must return a workload group name or ID based on session properties like login name or application name. Use \u0027NULL\u0027 to remove the current classifier function and route all sessions to \r\nthe default workload group.", "", 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": [ "ResourcePool", "ResourceGovernor" ], "CommandName": "Set-DbaRgResourcePool", "Name": "Set-DbaRgResourcePool", "Author": "John McCall (@lowlydba), lowlydba.com", "Syntax": "Set-DbaRgResourcePool [-SqlInstance \u003cDbaInstanceParameter[]\u003e] [-SqlCredential \u003cPSCredential\u003e] [-ResourcePool \u003cString[]\u003e] [-Type \u003cString\u003e] [-MinimumCpuPercentage \u003cInt32\u003e] [-MaximumCpuPercentage \u003cInt32\u003e] [-CapCpuPercentage \u003cInt32\u003e] [-MinimumMemoryPercentage \u003cInt32\u003e] [-MaximumMemoryPercentage \u003cInt32\u003e] [-MinimumIOPSPerVolume \u003cInt32\u003e] [-MaximumIOPSPerVolume \u003cInt32\u003e] [-SkipReconfigure] [-InputObject \u003cObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nSet-DbaRgResourcePool [-SqlInstance \u003cDbaInstanceParameter[]\u003e] [-SqlCredential \u003cPSCredential\u003e] [-ResourcePool \u003cString[]\u003e] [-Type \u003cString\u003e] [-MinimumCpuPercentage \u003cInt32\u003e] [-MaximumCpuPercentage \u003cInt32\u003e] [-CapCpuPercentage \u003cInt32\u003e] [-MinimumMemoryPercentage \u003cInt32\u003e] [-MaximumMemoryPercentage \u003cInt32\u003e] [-MinimumIOPSPerVolume \u003cInt32\u003e] [-MaximumIOPSPerVolume \u003cInt32\u003e] [-SkipReconfigure] [-InputObject \u003cObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nSet-DbaRgResourcePool [-SqlInstance \u003cDbaInstanceParameter[]\u003e] [-SqlCredential \u003cPSCredential\u003e] [-ResourcePool \u003cString[]\u003e] [-Type \u003cString\u003e] [-MinimumCpuPercentage \u003cInt32\u003e] [-MaximumCpuPercentage \u003cInt32\u003e] [-CapCpuPercentage \u003cInt32\u003e] [-MinimumMemoryPercentage \u003cInt32\u003e] [-MaximumMemoryPercentage \u003cInt32\u003e] [-MinimumIOPSPerVolume \u003cInt32\u003e] [-MaximumIOPSPerVolume \u003cInt32\u003e] [-MaximumProcesses \u003cInt32\u003e] [-SkipReconfigure] [-InputObject \u003cObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.ResourcePool or Microsoft.SqlServer.Management.Smo.ExternalResourcePool\nReturns the modified resource pool object with added connection context 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- Id: Unique identifier for the resource pool\r\n- Name: Name of the resource pool\r\n- CapCpuPercentage: CPU percentage cap for the pool (SQL Server 2012+)\r\n- IsSystemObject: Boolean indicating if this is a system resource pool\r\n- MaximumCpuPercentage: Maximum CPU percentage the pool can consume\r\n- MaximumIopsPerVolume: Maximum IOPS per disk volume for the pool\r\n- MaximumMemoryPercentage: Maximum memory percentage the pool can consume\r\n- MinimumCpuPercentage: Guaranteed minimum CPU percentage for the pool\r\n- MinimumIopsPerVolume: Guaranteed minimum IOPS per disk volume for the pool\r\n- MinimumMemoryPercentage: Guaranteed minimum memory percentage for the pool\r\n- WorkloadGroups: Collection of workload groups associated with this pool\nAll properties from the base SMO ResourcePool or ExternalResourcePool objects are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaRgResourcePool-SqlInstance sql2016 -ResourcePool \"poolAdmin\" -MaximumCpuPercentage 5\nConfigures a resource pool named \"poolAdmin\" for the instance sql2016 with a Maximum CPU Percent of 5.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaRgResourcePool-SqlInstance sql2012\\dev1 -ResourcePool \"poolDeveloper\" -SkipReconfigure\nConfigures a resource pool named \"poolDeveloper\" for the instance dev1 on sq2012.\r\nReconfiguration is skipped and the Resource Governor will not be able to use the new resource pool\r\nuntil it is reconfigured.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaRgResourcePool -SqlInstance sql2016 -Type \"Internal\" | Where-Object { $_.IsSystemObject -eq $false } | Set-DbaRgResourcePool -MinMemoryPercent 10\nConfigures all user internal resource pools to have a minimum memory percent of 10\r\nfor the instance sql2016 by piping output from Get-DbaRgResourcePool.", "Description": "Modifies resource allocation settings for existing Resource Governor pools to control how much CPU, memory, and disk I/O different workloads can consume.\nThis lets you adjust performance limits after analyzing workload patterns or when server capacity changes.\nWorks with both internal pools (for SQL Server queries) and external pools (for R Services, Python, or other external processes).\nThe Resource Governor is automatically reconfigured to apply changes immediately unless you skip reconfiguration.", "Links": "https://dbatools.io/Set-DbaRgResourcePool", "Synopsis": "Modifies CPU, memory, and IOPS limits for existing SQL Server Resource Governor pools.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", false, "true (ByValue, ByPropertyName)", "", "" ], [ "SqlCredential", "Credential object used to connect to the Windows server as a different user", "", false, "false", "", "" ], [ "ResourcePool", "Specifies the name of the existing resource pool to modify.\r\nUse this to target specific pools like \u0027poolAdmin\u0027 or \u0027poolDeveloper\u0027 when you need to adjust their resource limits.", "", false, "false", "", "" ], [ "Type", "Specifies whether to modify Internal or External resource pools.\r\nInternal pools control SQL Server queries and connections, while External pools manage R Services, Python, or other external processes.\r\nDefaults to Internal if not specified.", "", false, "false", "Internal", "Internal,External" ], [ "MinimumCpuPercentage", "Sets the guaranteed minimum CPU percentage (0-100) that this pool will always receive during CPU contention.\r\nUse this to ensure critical workloads get sufficient CPU even when the server is busy.\r\nFor example, set to 20 to guarantee a pool always gets at least 20% of available CPU.", "", false, "true (ByPropertyName)", "0", "" ], [ "MaximumCpuPercentage", "Sets the maximum CPU percentage (1-100) that this pool can consume during CPU contention.\r\nUse this to prevent runaway queries from monopolizing CPU resources.\r\nFor example, set to 30 to limit a development pool to 30% of available CPU.", "", false, "true (ByPropertyName)", "0", "" ], [ "CapCpuPercentage", "Sets an absolute hard cap (1-100) on CPU usage that cannot be exceeded even when CPU is available.\r\nUnlike MaximumCpuPercentage, this limit applies regardless of server load or contention.\r\nOnly available on SQL Server 2012 and later. Use this for strict resource isolation requirements.", "", false, "true (ByPropertyName)", "0", "" ], [ "MinimumMemoryPercentage", "Sets the minimum memory percentage (0-100) that is reserved exclusively for this pool and cannot be shared.\r\nUse this to guarantee memory for critical workloads that must have dedicated memory allocation.\r\nFor example, set to 15 to ensure a production pool always has at least 15% of server memory reserved.", "", false, "true (ByPropertyName)", "0", "" ], [ "MaximumMemoryPercentage", "Sets the maximum memory percentage (1-100) that this pool can consume from total server memory.\r\nUse this to prevent memory-intensive workloads from consuming all available memory.\r\nDefaults to 100, meaning no memory restrictions. Set lower values like 50 to limit pool memory usage.", "", false, "true (ByPropertyName)", "0", "" ], [ "MinimumIOPSPerVolume", "Sets the minimum guaranteed IOPS per disk volume that this pool will receive during I/O contention.\r\nUse this to ensure critical workloads get sufficient disk I/O performance even when storage is busy.\r\nFor example, set to 1000 to guarantee at least 1000 IOPS per volume for a production pool.", "", false, "true (ByPropertyName)", "0", "" ], [ "MaximumIOPSPerVolume", "Sets the maximum IOPS per disk volume that this pool can consume during I/O operations.\r\nUse this to prevent I/O-intensive workloads from overwhelming disk subsystems and affecting other pools.\r\nFor example, set to 5000 to limit a reporting pool to 5000 IOPS per volume.", "", false, "true (ByPropertyName)", "0", "" ], [ "MaximumProcesses", "Sets the maximum number of external processes allowed in this external resource pool.\r\nOnly applies to External pool types used for R Services, Python, or other external runtime processes.\r\nSet to 0 for unlimited processes (limited only by server resources), or specify a number like 10 to restrict concurrent external processes.", "", false, "false", "0", "" ], [ "SkipReconfigure", "Prevents automatic reconfiguration of the Resource Governor after making pool changes.\r\nUse this when making multiple pool modifications and you want to reconfigure manually later.\r\nWithout reconfiguration, your pool changes won\u0027t take effect until you manually reconfigure the Resource Governor.", "", false, "false", "False", "" ], [ "InputObject", "Accepts resource pool objects piped from Get-DbaRgResourcePool for bulk modifications.\r\nUse this to modify multiple pools at once by piping them from Get-DbaRgResourcePool.\r\nEliminates the need to specify SqlInstance and ResourcePool parameters when working with existing pool objects.", "", 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": [ "ResourcePool", "ResourceGovernor" ], "CommandName": "Set-DbaRgWorkloadGroup", "Name": "Set-DbaRgWorkloadGroup", "Author": "John McCall (@lowlydba), lowlydba.com", "Syntax": "Set-DbaRgWorkloadGroup [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-WorkloadGroup] \u003cString[]\u003e] [[-ResourcePool] \u003cString\u003e] [[-ResourcePoolType] \u003cString\u003e] [[-Importance] \u003cString\u003e] [[-RequestMaximumMemoryGrantPercentage] \u003cInt32\u003e] [[-RequestMaximumCpuTimeInSeconds] \u003cInt32\u003e] [[-RequestMemoryGrantTimeoutInSeconds] \u003cInt32\u003e] [[-MaximumDegreeOfParallelism] \u003cInt32\u003e] [[-GroupMaximumRequests] \u003cInt32\u003e] [-SkipReconfigure] [[-InputObject] \u003cWorkloadGroup[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.WorkloadGroup\nReturns the modified WorkloadGroup object(s) after configuration changes are applied. One object is returned per workload group that was modified, containing the updated workload group properties and \r\nresource constraints.\nThe output is obtained by retrieving the updated workload group from the Resource Governor configuration after the Alter() operation completes, ensuring that the returned object reflects all applied \r\nchanges.\nProperties available on the returned WorkloadGroup objects include:\r\n- Name: Name of the workload group\r\n- Importance: Relative priority level (LOW, MEDIUM, or HIGH)\r\n- RequestMaximumMemoryGrantPercentage: Maximum memory percentage per query request\r\n- RequestMaximumCpuTimeInSeconds: Maximum CPU time per request\r\n- RequestMemoryGrantTimeoutInSeconds: Memory grant timeout setting\r\n- MaximumDegreeOfParallelism: Maximum parallel processors for queries\r\n- GroupMaximumRequests: Maximum concurrent requests limit\r\n- Parent: Reference to the parent ResourcePool or ExternalResourcePool object", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaRgWorkloadGroup -SqlInstance sql2016 -WorkloadGroup \"groupAdmin\" -ResourcePool \"poolAdmin\"\nConfigures a workload group named \"groupAdmin\" in the resource pool \"poolAdmin\" for the instance sql2016.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaRgWorkloadGroup | Where-Object Name -eq \"groupSuperUsers\" | Set-DbaRgWorkloadGroup -GroupMaximumRequests 2\nConfigures a workload group named \"groupSuperUsers\" by setting the maximum number of group requests to 2 for the instance sql2016.", "Description": "Modifies configuration settings for Resource Governor workload groups, which control how SQL Server allocates CPU, memory, and parallelism resources to different categories of queries and connections.\nUse this function to adjust resource limits for specific workload groups when you need to prioritize critical applications, limit resource-hungry queries, or enforce service level agreements through resource allocation policies.\nChanges automatically trigger a Resource Governor reconfiguration unless skipped, and plan-affecting settings only apply to new query plans after clearing the procedure cache.\nSupports both internal resource pools (standard workloads) and external resource pools (R/Python integration scenarios).", "Links": "https://dbatools.io/Set-DbaRgWorkloadGroup", "Synopsis": "Modifies Resource Governor workload group settings to control query resource consumption and limits.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", false, "false", "", "" ], [ "SqlCredential", "Credential object used to connect to the Windows server as a different user", "", false, "false", "", "" ], [ "WorkloadGroup", "Name of the specific workload group to modify within the resource pool.\r\nUse this to target individual workload groups when you need to adjust resource limits for specific application categories or user groups.", "", false, "false", "", "" ], [ "ResourcePool", "Name of the resource pool that contains the workload group to be modified.\r\nRequired when specifying WorkloadGroup by name rather than piping from Get-DbaRgWorkloadGroup.", "", false, "false", "", "" ], [ "ResourcePoolType", "Specifies whether to target Internal resource pools (standard SQL workloads) or External resource pools (R/Python integration scenarios).\r\nChoose Internal for typical database workloads, or External when managing Machine Learning Services resource allocation.", "", false, "false", "", "Internal,External" ], [ "Importance", "Sets the relative priority level for requests within this workload group compared to other groups in the same resource pool.\r\nUse HIGH for critical business applications, MEDIUM for standard workloads, or LOW for background processes that can tolerate delays.", "", false, "false", "", "LOW,MEDIUM,HIGH" ], [ "RequestMaximumMemoryGrantPercentage", "Sets the maximum percentage of the resource pool\u0027s memory that any single query can request for operations like sorting and hashing.\r\nValues range from 1-100 percent. Use lower values to prevent single queries from monopolizing memory resources.", "", false, "false", "0", "" ], [ "RequestMaximumCpuTimeInSeconds", "Defines the maximum CPU time in seconds that any single request can consume before being terminated.\r\nSet this to prevent runaway queries from consuming excessive CPU resources. Use 0 for unlimited CPU time.", "", false, "false", "0", "" ], [ "RequestMemoryGrantTimeoutInSeconds", "Sets how long queries can wait for memory grants before timing out with insufficient memory errors.\r\nIncrease this for environments with heavy memory contention, or decrease to fail fast when memory is unavailable.", "", false, "false", "0", "" ], [ "MaximumDegreeOfParallelism", "Controls the maximum number of parallel processors that queries in this workload group can use.\r\nOverride the server-level MAXDOP setting for specific workload groups to optimize resource allocation based on workload characteristics.", "", false, "false", "0", "" ], [ "GroupMaximumRequests", "Limits the total number of concurrent requests that can execute simultaneously within this workload group.\r\nUse this to prevent resource pool saturation by limiting how many queries from this group can run at once.", "", false, "false", "0", "" ], [ "SkipReconfigure", "Prevents automatic Resource Governor reconfiguration after making workload group changes.\r\nUse this when making multiple configuration changes and you want to reconfigure manually once at the end to minimize disruption.", "", false, "false", "False", "" ], [ "InputObject", "Accepts workload group objects piped from Get-DbaRgWorkloadGroup for bulk configuration operations.\r\nAllows you to modify multiple workload groups across different instances 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", "" ], [ "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": "SpConfigure", "CommandName": "Set-DbaSpConfigure", "Name": "Set-DbaSpConfigure", "Author": "Nic Cain, sirsql.net", "Syntax": "Set-DbaSpConfigure [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Value] \u003cInt32\u003e] [[-Name] \u003cString[]\u003e] [[-InputObject] \u003cObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per configuration setting successfully modified. Each object contains the change details including the configuration name and before/after values.\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- ConfigName: Name of the configuration setting that was modified\r\n- PreviousValue: The previous configured value before the change (integer)\r\n- NewValue: The new value that was set (integer)\nIf a configuration change is not dynamic, a warning message is issued indicating that SQL Server must be restarted for the new value to take effect.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaSpConfigure -SqlInstance localhost -Name ScanForStartupProcedures -Value 1\nAdjusts the Scan for startup stored procedures configuration value to 1 and notifies the user that this requires a SQL restart to take effect\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaSpConfigure -SqlInstance sql2017, sql2014 -Name XPCmdShellEnabled, IsSqlClrEnabled | Set-DbaSpConfigure -Value $false\nSets the values for XPCmdShellEnabled and IsSqlClrEnabled on sql2017 and sql2014 to False\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-DbaSpConfigure -SqlInstance localhost -Name XPCmdShellEnabled -Value 1\nAdjusts the xp_cmdshell configuration value to 1.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eSet-DbaSpConfigure -SqlInstance localhost -Name XPCmdShellEnabled -Value 1 -WhatIf\nReturns information on the action that would be performed. No actual change will be made.", "Description": "This function safely modifies SQL Server instance-level configuration values that are normally changed through sp_configure. Use this when you need to adjust settings like max memory, xp_cmdshell, cost threshold for parallelism, or any other server configuration option.\n\nFor dynamic settings, changes take effect immediately. For static settings, you\u0027ll receive a warning that SQL Server must be restarted before the new value becomes active.\n\nBuilt-in safety prevents setting values outside their defined minimum and maximum ranges, protecting against configuration errors that could prevent SQL Server from starting or cause performance issues.", "Links": "https://dbatools.io/Set-DbaSpConfigure", "Synopsis": "Modifies SQL Server instance-level configuration settings through sp_configure", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. This can be a\r\ncollection 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", "", "" ], [ "Value", "Sets the new configuration value within the setting\u0027s valid range (minimum to maximum). The function validates the value against SQL Server\u0027s defined limits to prevent invalid configurations that \r\ncould prevent startup or cause performance issues.", "NewValue,NewConfig", false, "false", "0", "" ], [ "Name", "Specifies which SQL Server configuration setting to modify, such as \u0027max server memory (MB)\u0027, \u0027xp_cmdshell\u0027, or \u0027cost threshold for parallelism\u0027. Use this when targeting specific settings by name \r\ninstead of piping from Get-DbaSpConfigure.", "Config,ConfigName", false, "false", "", "" ], [ "InputObject", "Accepts configuration objects piped from Get-DbaSpConfigure to modify multiple settings across instances. Use this approach when you need to bulk update configurations or apply conditional logic \r\nbased on current values.", "", 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": "SPN", "CommandName": "Set-DbaSpn", "Name": "Set-DbaSpn", "Author": "Drew Furgiuele (@pittfurg), port1433.com", "Syntax": "Set-DbaSpn [-SPN] \u003cString\u003e [-ServiceAccount] \u003cString\u003e [[-Credential] \u003cPSCredential\u003e] [-NoDelegation] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one or two objects per service account processed, depending on delegation configuration:\nSPN Registration Result Object (always returned):\r\n- Name (string) - The Service Principal Name that was added\r\n- ServiceAccount (string) - The Active Directory account that owns the SPN\r\n- Property (string) - Always \"servicePrincipalName\" indicating the AD property that was modified\r\n- IsSet (boolean) - True if the SPN was successfully added, False if the operation failed\r\n- Notes (string) - Status message: \"Successfully added SPN\" or \"Failed to add SPN\"\nDelegation Configuration Result Object (conditionally returned):\r\n- Name (string) - The Service Principal Name for which delegation was configured\r\n- ServiceAccount (string) - The Active Directory account for which delegation was configured\r\n- Property (string) - Always \"msDS-AllowedToDelegateTo\" indicating the AD property that was modified\r\n- IsSet (boolean) - True if constrained delegation was successfully enabled, False if the operation failed\r\n- Notes (string) - Status message: \"Successfully added constrained delegation\" or \"Failed to add constrained delegation\"\nThe delegation object is only returned when:\r\n- The SPN was successfully added (IsSet = $true for the first object)\r\n- AND the -NoDelegation parameter was NOT specified\r\n- AND the ShouldProcess check passed (when -WhatIf is not used)\nWhen -NoDelegation is specified, only the SPN registration object is returned.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaSpn -SPN MSSQLSvc/SQLSERVERA.domain.something -ServiceAccount domain\\account\nPS C:\\\u003e Set-DbaSpn -SPN MSSQLSvc/SQLSERVERA.domain.something -ServiceAccount domain\\account -EnableException\nConnects to Active Directory and adds a provided SPN to the given account.\r\nConnects to Active Directory and adds a provided SPN to the given account, suppressing all error messages and throw exceptions that can be caught instead\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaSpn -SPN MSSQLSvc/SQLSERVERA.domain.something -ServiceAccount domain\\account -Credential ad\\sqldba\nConnects to Active Directory and adds a provided SPN to the given account. Uses alternative account to connect to AD.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-DbaSpn -SPN MSSQLSvc/SQLSERVERA.domain.something -ServiceAccount domain\\account -NoDelegation\nConnects to Active Directory and adds a provided SPN to the given account, without the delegation.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eTest-DbaSpn -ComputerName sql2016 | Where-Object { $_.isSet -eq $false } | Set-DbaSpn\nSets all missing SPNs for sql2016\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eTest-DbaSpn -ComputerName sql2016 | Where-Object { $_.isSet -eq $false } | Set-DbaSpn -WhatIf\nDisplays what would happen trying to set all missing SPNs for sql2016", "Description": "This function will connect to Active Directory and search for an account. If the account is found, it will attempt to add an SPN. Once the SPN is added, the function will also set delegation to that service, unless -NoDelegation is specified. In order to run this function, the credential you provide must have write access to Active Directory.\n\nNote: This function supports -WhatIf", "Links": "https://dbatools.io/Set-DbaSpn", "Synopsis": "Sets an SPN for a given service account in active directory (and also enables delegation to the same SPN by default)", "Availability": "Windows, Linux, macOS", "Params": [ [ "SPN", "Specifies the Service Principal Name to register in Active Directory for SQL Server Kerberos authentication.\r\nMust follow the format \u0027MSSQLSvc/hostname:port\u0027 or \u0027MSSQLSvc/FQDN:port\u0027 for named instances.\r\nUse this to enable Kerberos authentication and eliminate double-hop authentication issues.", "RequiredSPN", true, "true (ByPropertyName)", "", "" ], [ "ServiceAccount", "Specifies the Active Directory account that runs the SQL Server service and will own the SPN.\r\nCan be a domain user account (domain\\username) or computer account (computername$) depending on your SQL Server service configuration.\r\nThis account must exist in Active Directory and you must have permissions to modify its properties.", "InstanceServiceAccount,AccountName", true, "true (ByPropertyName)", "", "" ], [ "Credential", "The credential you want to use to connect to Active Directory to make the changes", "", false, "true (ByPropertyName)", "", "" ], [ "NoDelegation", "Prevents automatic configuration of Kerberos constrained delegation for the specified SPN.\r\nUse this when you want to manually configure delegation later or when delegation is not required for your environment.\r\nBy default, the function enables constrained delegation to allow the service account to authenticate to other 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", "" ], [ "WhatIf", "Shows what would happen if the command was executed", "wi", false, "false", "", "" ], [ "Confirm", "Turns confirmations before changes on or off", "cf", false, "false", "", "" ] ] }, { "Tags": [ "Startup", "Parameter", "Configure" ], "CommandName": "Set-DbaStartupParameter", "Name": "Set-DbaStartupParameter", "Author": "Stuart Moore (@napalmgram), stuart-moore.com", "Syntax": "Set-DbaStartupParameter [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [[-MasterData] \u003cString\u003e] [[-MasterLog] \u003cString\u003e] [[-ErrorLog] \u003cString\u003e] [[-TraceFlag] \u003cString[]\u003e] [-CommandPromptStart] [-MinimalStart] [[-MemoryToReserve] \u003cInt32\u003e] [-SingleUser] [[-SingleUserDetails] \u003cString\u003e] [-NoLoggingToWinEvents] [-StartAsNamedInstance] [-DisableMonitoring] [-IncreasedExtents] [-TraceFlagOverride] [[-StartupConfig] \u003cObject\u003e] [-Offline] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Object with added NoteProperties\nReturns the startup parameter object from Get-DbaStartupParameter with additional context properties added:\nBase properties (from Get-DbaStartupParameter):\r\n- CommandPromptStart (boolean) - Whether command prompt start flag (-c) is enabled\r\n- DisableMonitoring (boolean) - Whether performance monitoring is disabled (-x)\r\n- ErrorLog (string) - Path to the error log file (-e parameter)\r\n- IncreasedExtents (boolean) - Whether increased extents flag (-E) is enabled\r\n- MasterData (string) - Path to master database data file (-d parameter)\r\n- MasterLog (string) - Path to master database log file (-l parameter)\r\n- MemoryToReserve (int) - Memory reserved in MB (-g parameter)\r\n- MinimalStart (boolean) - Whether minimal start flag (-f) is enabled\r\n- NoLoggingToWinEvents (boolean) - Whether Windows event logging is disabled (-n)\r\n- ParameterString (string) - Complete startup parameter string as stored in registry\r\n- SingleUser (boolean) - Whether single-user mode (-m) is enabled\r\n- SingleUserDetails (string) - Specific login allowed in single-user mode (if specified)\r\n- StartAsNamedInstance (boolean) - Whether named instance flag (-s) is enabled\r\n- TraceFlags (string) - Comma-separated list of enabled trace flags (-T parameters)\nAdded properties:\r\n- OriginalStartupParameters (string) - The startup parameter string before any modifications (added to all outputs)\r\n- Notes (string) - Message indicating changes were made and restart is required (added when Credential parameter not provided)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaStartupParameter -SqlInstance server1\\instance1 -SingleUser\nWill configure the SQL Instance server1\\instance1 to startup up in Single User mode at next startup\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaStartupParameter -SqlInstance sql2016 -IncreasedExtents\nWill configure the SQL Instance sql2016 to IncreasedExtents = True (-E)\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-DbaStartupParameter -SqlInstance sql2016 -IncreasedExtents:$false -WhatIf\nShows what would happen if you attempted to configure the SQL Instance sql2016 to IncreasedExtents = False (no -E)\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eSet-DbaStartupParameter -SqlInstance server1\\instance1 -TraceFlag 8032,8048\nThis will append Trace Flags 8032 and 8048 to the startup parameters\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eSet-DbaStartupParameter -SqlInstance sql2016 -SingleUser:$false -TraceFlagOverride\nThis will remove all trace flags and set SingleUser to false\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eSet-DbaStartupParameter -SqlInstance server1\\instance1 -SingleUser -TraceFlag 8032,8048 -TraceFlagOverride\nThis will set Trace Flags 8032 and 8048 to the startup parameters, removing any existing Trace Flags\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eSet-DbaStartupParameter -SqlInstance sql2016 -SingleUser:$false -TraceFlagOverride -Offline\nThis will remove all trace flags and set SingleUser to false from an offline instance\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eSet-DbaStartupParameter -SqlInstance sql2016 -ErrorLog c:\\Sql\\ -Offline\nThis will attempt to change the ErrorLog path to c:\\sql\\. However, with the offline switch this will not happen. To force it, use the -Force switch like so:\nSet-DbaStartupParameter -SqlInstance sql2016 -ErrorLog c:\\Sql\\ -Offline -Force\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003e$StartupConfig = Get-DbaStartupParameter -SqlInstance server1\\instance1\nPS C:\\\u003e Set-DbaStartupParameter -SqlInstance server1\\instance1 -SingleUser -NoLoggingToWinEvents\r\nPS C:\\\u003e #Restart your SQL instance with the tool of choice\r\nPS C:\\\u003e #Do Some work\r\nPS C:\\\u003e Set-DbaStartupParameter -SqlInstance server1\\instance1 -StartupConfig $StartupConfig\r\nPS C:\\\u003e #Restart your SQL instance with the tool of choice and you\u0027re back to normal\nIn this example we take a copy of the existing startup configuration of server1\\instance1\nWe then change the startup parameters ahead of some work\nAfter the work has been completed, we can push the original startup parameters back to server1\\instance1 and resume normal operation", "Description": "Changes the startup parameters that SQL Server uses when the service starts, including paths to master database files, error log location, and various startup flags. These parameters are stored in the Windows registry and require elevated permissions to modify.\n\nThis function is commonly used to enable single-user mode for emergency repairs, set trace flags for troubleshooting, relocate system database files during migrations, or adjust memory settings. Changes take effect only after the SQL Server service is restarted.\n\nThe function validates file paths when the instance is online to prevent startup failures, but can work offline with the -Force parameter when you need to modify parameters for instances that won\u0027t start.\n\nFor full details of what each parameter does, please refer to this MSDN article - https://msdn.microsoft.com/en-us/library/ms190737(v=sql.105).aspx", "Links": "https://dbatools.io/Set-DbaStartupParameter", "Synopsis": "Modifies SQL Server startup parameters stored in the Windows registry", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The SQL Server instance to be modified\nIf the Sql Instance is offline path parameters will be ignored as we cannot test the instance\u0027s access to the path. If you want to force this to work then please use the Force switch", "", 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", "", "" ], [ "Credential", "Windows Credential with permission to log on to the server running the SQL instance", "", false, "false", "", "" ], [ "MasterData", "Specifies the file path to the master database data file (master.mdf). Required when relocating system databases or recovering from corrupted system files.\r\nUse this when moving SQL Server installations, restoring from backup to different locations, or troubleshooting startup issues caused by missing or corrupted master database files. The path must be \r\naccessible by the SQL Server service account.\r\nWill be ignored if SqlInstance is offline unless the Force parameter is used, as the function validates the path accessibility when the instance is online.", "", false, "false", "", "" ], [ "MasterLog", "Specifies the file path to the master database log file (mastlog.ldf). Required when relocating system databases or recovering from corrupted system files.\r\nUse this alongside MasterData when moving SQL Server installations or troubleshooting startup failures related to master database corruption. The path must be accessible by the SQL Server service \r\naccount.\r\nWill be ignored if SqlInstance is offline unless the Force parameter is used, as the function validates the path accessibility when the instance is online.", "", false, "false", "", "" ], [ "ErrorLog", "Specifies the file path where SQL Server will write its error log files. Controls where diagnostic information, startup messages, and error details are stored.\r\nUse this when you need to redirect error logs to a different drive for space management, centralized logging, or compliance requirements. The directory must exist and be writable by the SQL Server \r\nservice account.\r\nWill be ignored if SqlInstance is offline unless the Force parameter is used, as the function validates the path accessibility when the instance is online.", "", false, "false", "", "" ], [ "TraceFlag", "Specifies one or more trace flags to enable at SQL Server startup as a comma-separated list. Trace flags control specific SQL Server behaviors and diagnostic features.\r\nUse this for enabling global trace flags like 1117 (uniform extent allocations), 1118 (reduce tempdb contention), or 3226 (suppress successful backup messages). By default, these flags are appended \r\nto existing trace flags.\r\nUse TraceFlagOverride parameter to replace all existing trace flags instead of appending to them.", "", false, "false", "", "" ], [ "CommandPromptStart", "Enables faster startup when SQL Server is launched from command prompt rather than as a Windows service. Bypasses Service Control Manager initialization routines.\r\nUse this when you need to start SQL Server manually for troubleshooting or testing scenarios where you\u0027ll be running sqlservr.exe directly from command line instead of using service management tools.", "", false, "false", "False", "" ], [ "MinimalStart", "Starts SQL Server with minimal configuration, loading only essential components and services. Automatically places the instance in single-user mode with reduced functionality.\r\nUse this when SQL Server won\u0027t start normally due to configuration problems like excessive memory allocation, corrupted configuration settings, or problematic startup procedures. Essential for \r\nemergency recovery scenarios.\r\nNote that many features will be unavailable in minimal start mode, making it suitable only for troubleshooting and corrective actions.", "", false, "false", "False", "" ], [ "MemoryToReserve", "Specifies the amount of memory in megabytes to reserve outside the SQL Server buffer pool for system components and extended procedures.\r\nUse this when experiencing out-of-memory errors related to extended procedures, OLE DB providers, or CLR assemblies, especially on systems with large amounts of RAM allocated to SQL Server. The \r\nreserved memory hosts DLL files, distributed query providers, and automation objects.\r\nDefault value is 256 MB, but you may need to increase this on servers with heavy use of extended procedures or CLR integration.", "", false, "false", "0", "" ], [ "SingleUser", "Starts SQL Server in single-user mode, allowing only one connection at a time. Prevents other users and applications from connecting to the instance.\r\nUse this for emergency maintenance, database recovery operations, or when you need exclusive access to troubleshoot corruption or perform administrative tasks that require isolation.\r\nCombine with SingleUserDetails parameter to restrict access to a specific login for additional security during maintenance windows.", "", false, "false", "False", "" ], [ "SingleUserDetails", "Specifies which login or application can connect when SQL Server is in single-user mode. Restricts the single connection to a specific user account.\r\nUse this to ensure only authorized personnel can access the instance during maintenance windows, preventing applications or other users from grabbing the single available connection.\r\nCan specify a login name, domain account, or application name. Automatically quoted if the value contains spaces.", "", false, "false", "", "" ], [ "NoLoggingToWinEvents", "Disables SQL Server from writing startup and shutdown messages to the Windows Application Event Log. Only affects system event logging, not SQL Server error log files.\r\nUse this to reduce event log clutter in environments with frequent SQL Server restarts or when centralized logging systems capture SQL Server events through other means.\r\nSQL Server will continue writing to its own error log files regardless of this setting.", "", false, "false", "False", "" ], [ "StartAsNamedInstance", "Enables starting a named instance of SQL Server, ensuring proper instance identification and network connectivity for non-default instances.\r\nUse this when configuring startup parameters for named instances that need to be explicitly identified during startup to avoid conflicts with default instances or other named instances on the same \r\nserver.\r\nRequired for named instances to register properly with SQL Server Browser service and establish correct network endpoints.", "", false, "false", "False", "" ], [ "DisableMonitoring", "Disables SQL Server\u0027s internal performance monitoring and statistics collection to reduce overhead on high-performance systems.\r\nUse this only on production systems where every bit of performance matters and you have alternative monitoring solutions in place. Disables PerfMon counters, CPU statistics, cache-hit ratios, DBCC \r\nSQLPERF data, some DMVs, and many extended events.\r\nWarning: This significantly reduces your ability to diagnose performance issues and should only be used when monitoring overhead is confirmed to impact critical workloads.", "", false, "false", "False", "" ], [ "IncreasedExtents", "Increases the number of extents allocated for each file in a file group, improving allocation efficiency for databases with multiple data files.\r\nUse this on systems with multiple data files per filegroup to reduce allocation contention and improve performance during heavy insert/update operations.\r\nParticularly beneficial for tempdb configurations with multiple data files or user databases designed with multiple files for performance.", "", false, "false", "False", "" ], [ "TraceFlagOverride", "Replaces all existing trace flags with only the ones specified in the TraceFlag parameter. Without this switch, new trace flags are appended to existing ones.\r\nUse this when you need to completely reset the trace flag configuration or remove problematic trace flags that are causing issues.\r\nIf no TraceFlag values are provided with this switch, all existing trace flags will be removed from the startup parameters.", "", false, "false", "False", "" ], [ "StartupConfig", "Applies a complete startup configuration object previously captured with Get-DbaStartupParameter. Restores all startup parameters to match the saved configuration.\r\nUse this to quickly restore previous startup configurations after troubleshooting, rollback changes during maintenance, or standardize startup parameters across multiple instances.\r\nAutomatically enables TraceFlagOverride, so all existing trace flags will be replaced with those from the saved configuration.", "", false, "false", "", "" ], [ "Offline", "Performs startup parameter changes without attempting to connect to the SQL Server instance, improving performance when you know the instance is not running.\r\nUse this when modifying startup parameters for instances that are intentionally stopped or when you want to avoid connection overhead on known offline instances.\r\nWhen using this switch, file path parameters (MasterData, MasterLog, ErrorLog) cannot be validated and will be ignored unless the Force parameter is also specified.", "", false, "false", "False", "" ], [ "Force", "Bypasses file path validation for MasterData, MasterLog, and ErrorLog parameters, allowing changes even when paths cannot be verified.\r\nUse this when configuring startup parameters for offline instances or when you need to set paths that will be valid after a restart but are not currently accessible.\r\nExercise caution as invalid paths will prevent SQL Server from starting, requiring manual registry editing to correct.", "", 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": [ "Network", "Connection", "TCP", "Configure" ], "CommandName": "Set-DbaTcpPort", "Name": "Set-DbaTcpPort", "Author": "@H0s0n77", "Syntax": "Set-DbaTcpPort [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-Credential] \u003cPSCredential\u003e] [-Port] \u003cInt32[]\u003e [[-IpAddress] \u003cIPAddress[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.Void\nThis command does not return any output to the pipeline. It modifies SQL Server network configuration and optionally restarts services.\r\nWhen -Force is used, the Database Engine service is restarted to apply the port configuration changes immediately.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaTcpPort -SqlInstance sql2017 -Port 1433\nSets the port number 1433 for all IP Addresses on the default instance on sql2017. Prompts for confirmation.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaTcpPort -SqlInstance winserver\\sqlexpress -IpAddress 192.168.1.22 -Port 1433 -Confirm:$false\nSets the port number 1433 for IP 192.168.1.22 on the sqlexpress instance on winserver. Does not prompt for confirmation.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-DbaTcpPort -SqlInstance sql2017, sql2019 -port 1337 -Credential ad\\dba -Force\nSets the port number 1337 for all IP Addresses on SqlInstance sql2017 and sql2019 using the credentials for ad\\dba. Prompts for confirmation. Restarts the service.", "Description": "Configures TCP port settings for SQL Server instances by modifying the network configuration through SQL Server Configuration Manager functionality. This replaces the manual process of opening SQL Server Configuration Manager to change port settings for security hardening or network compliance.\n\nThe function can target all IP addresses (IPAll setting) or specific IP addresses, disables dynamic port allocation, and sets static port numbers. This is commonly used to move SQL Server off the default port 1433 for security purposes, configure custom ports for named instances, or meet organizational network segmentation requirements.\n\nImportant: SQL Server must be restarted before the new port configuration takes effect. Use the -Force parameter to automatically restart the Database Engine service, or restart manually after running the command.", "Links": "https://dbatools.io/Set-DbaTcpPort", "Synopsis": "Configures SQL Server TCP port settings for specified instances and IP addresses.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "Credential", "Credential object used to connect to the Windows server itself as a different user (like SQL Configuration Manager).", "", false, "false", "", "" ], [ "Port", "Specifies the TCP port number for SQL Server to listen on, replacing any existing static or dynamic port configuration.\r\nUse this to move SQL Server off the default port 1433 for security hardening or to configure custom ports for named instances.\r\nAccepts any valid port number between 1 and 65535, with common choices being 1433 (default), 1434, or organization-specific port ranges.", "", true, "false", "", "" ], [ "IpAddress", "Specifies which IP address should listen on the configured port instead of applying to all IP addresses.\r\nUse this for multi-homed servers where you need SQL Server to listen only on specific network interfaces.\r\nWhen omitted, the port change applies to all IP addresses (IPAll setting), which is the typical configuration for most servers.", "", false, "false", "", "" ], [ "Force", "Automatically restarts the SQL Server Database Engine service to apply the new port configuration immediately.\r\nUse this when you need the port change to take effect right away instead of waiting for the next service restart.\r\nWithout this parameter, you must manually restart SQL Server before the new port settings become active.", "", 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": [ "Tempdb", "Configuration" ], "CommandName": "Set-DbaTempDbConfig", "Name": "Set-DbaTempDbConfig", "Author": "Michael Fal (@Mike_Fal), mikefal.net", "Syntax": "Set-DbaTempDbConfig [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-DataFileCount] \u003cInt32\u003e] [-DataFileSize] \u003cInt32\u003e [[-LogFileSize] \u003cInt32\u003e] [[-DataFileGrowth] \u003cInt32\u003e] [[-LogFileGrowth] \u003cInt32\u003e] [[-DataPath] \u003cString[]\u003e] [[-LogPath] \u003cString\u003e] [[-OutFile] \u003cString\u003e] [-OutputScriptOnly] [-DisableGrowth] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject (default behavior)\nReturns configuration details after successfully applying tempdb settings. 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 (computer\\instance)\r\n- DataFileCount: The number of data files configured (int)\r\n- DataFileSize: Total size for all data files combined; dbasize object convertible to Bytes, KB, MB, GB, TB\r\n- SingleDataFileSize: Size of each individual data file; dbasize object convertible to Bytes, KB, MB, GB, TB\r\n- LogSize: Size of the transaction log file; dbasize object convertible to Bytes, KB, MB, GB, TB\r\n- DataPath: Path(s) where tempdb data files are located (string or string array)\r\n- LogPath: Path where the tempdb log file is located (string)\r\n- DataFileGrowth: Growth increment for data files; dbasize object convertible to Bytes, KB, MB, GB, TB\r\n- LogFileGrowth: Growth increment for log file; dbasize object convertible to Bytes, KB, MB, GB, TB\nSystem.String[] (when -OutputScriptOnly is specified)\nReturns array of T-SQL ALTER DATABASE statements that would configure tempdb without executing them.\nSystem.Void (when -OutFile is specified)\nNo output is returned to the pipeline when -OutFile is used; the T-SQL script is written directly to the specified file path.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbaTempDbConfig -SqlInstance localhost -DataFileSize 1000\nCreates tempdb with a number of data files equal to the logical cores where each file is equal to 1000MB divided by the number of logical cores, with a log file of 250MB.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbaTempDbConfig -SqlInstance localhost -DataFileSize 1000 -DataFileCount 8\nCreates tempdb with 8 data files, each one sized at 125MB, with a log file of 250MB.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSet-DbaTempDbConfig -SqlInstance localhost -DataFileSize 1000 -OutputScriptOnly\nProvides a SQL script output to configure tempdb according to the passed parameters.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eSet-DbaTempDbConfig -SqlInstance localhost -DataFileSize 1000 -DisableGrowth\nDisables the growth for the data and log files.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eSet-DbaTempDbConfig -SqlInstance localhost -DataFileSize 1000 -OutputScriptOnly\nReturns the T-SQL script representing tempdb configuration.", "Description": "Configures tempdb database files to follow Microsoft\u0027s recommended best practices for performance optimization. This function calculates the optimal number of data files based on logical CPU cores (capped at 8) and distributes the specified total data file size evenly across those files. You must specify the target SQL Server instance and total data file size as mandatory parameters.\n\nThe function automatically determines the appropriate number of data files based on your server\u0027s logical cores, but you can override this behavior. It validates the current tempdb configuration to ensure it won\u0027t conflict with your desired settings - existing files must be smaller than the calculated target size and you cannot have more existing files than the target configuration.\n\nAdditional parameters let you customize file paths, log file size, and growth settings. The function generates ALTER DATABASE statements but does not shrink or delete existing files. If your current tempdb is larger than your target configuration, you\u0027ll need to shrink it manually before running this function. A SQL Server restart is required for tempdb changes to take effect.", "Links": "https://dbatools.io/Set-DbaTempDbConfig", "Synopsis": "Configures tempdb database files according to Microsoft best practices for optimal performance", "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", "", "" ], [ "DataFileCount", "Sets the number of tempdb data files to create. When omitted, automatically uses the logical core count (capped at 8 per Microsoft best practices).\r\nOverride this when you need a specific file count different from core count, though exceeding core count generates a warning as it goes against best practices.", "", false, "false", "0", "" ], [ "DataFileSize", "Sets the total size in MB for all tempdb data files combined. This value gets evenly divided across all data files.\r\nFor example, 1000MB with 4 files creates four 250MB files. Choose based on your workload\u0027s tempdb usage patterns and available storage.", "", true, "false", "0", "" ], [ "LogFileSize", "Sets the tempdb log file size in MB. When omitted, the existing log file size remains unchanged.\r\nUse this to resize the log file when current sizing doesn\u0027t match your tempdb transaction volume requirements.", "", false, "false", "0", "" ], [ "DataFileGrowth", "Controls the growth increment for tempdb data files in MB when they need to expand. Defaults to 512 MB.\r\nSet this based on your typical tempdb usage spikes to avoid frequent small growths that can impact performance. Use 0 with -DisableGrowth to prevent growth entirely.", "", false, "false", "512", "" ], [ "LogFileGrowth", "Controls the growth increment for the tempdb log file in MB when it needs to expand. Defaults to 512 MB.\r\nSize this according to your transaction log activity in tempdb to minimize auto-growth events during peak workloads.", "", false, "false", "512", "" ], [ "DataPath", "Sets the folder path(s) where tempdb data files will be created. When omitted, uses the current tempdb data file location.\r\nSpecify multiple paths to distribute files across different drives for performance. Files are distributed round-robin across the provided paths.", "", false, "false", "", "" ], [ "LogPath", "Sets the folder path where the tempdb log file will be created. When omitted, uses the current tempdb log file location.\r\nConsider placing the log file on a separate drive from data files to reduce I/O contention for write-heavy tempdb workloads.", "", false, "false", "", "" ], [ "OutFile", "Saves the generated T-SQL script to the specified file path instead of executing it.\r\nUseful for storing configuration scripts in source control or running them later through scheduled maintenance processes.", "", false, "false", "", "" ], [ "OutputScriptOnly", "Returns the generated T-SQL script without executing it against the SQL Server instance.\r\nUse this to review the configuration changes before applying them, or to run the script manually during maintenance windows.", "", false, "false", "False", "" ], [ "DisableGrowth", "Prevents tempdb files from auto-growing by setting growth to 0. Overrides any values specified for -DataFileGrowth and -LogFileGrowth.\r\nUse this when you want to pre-size tempdb files appropriately and prevent unexpected growth during production workloads.", "", 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", "", "" ] ] }, { "Description": "This function creates or changes configuration values. These can be used to provide dynamic configuration information outside the PowerShell variable system.", "CommandName": "Set-DbatoolsConfig", "Synopsis": "Sets configuration entries.", "Author": "Friedrich Weinmann (@FredWeinmann)", "Syntax": "Set-DbatoolsConfig -FullName \u003cString\u003e [-Value \u003cObject\u003e] [-Description \u003cString\u003e] [-Validation \u003cString\u003e] [-Handler \u003cScriptBlock\u003e]\r\n [-Hidden] [-Default] [-Initialize] [-DisableValidation] [-DisableHandler] [-EnableException] [-SimpleExport] [-ModuleExport]\r\n [-PassThru] [-AllowDelete] [\u003cCommonParameters\u003e]\r\n\r\n Set-DbatoolsConfig -FullName \u003cString\u003e [-Description \u003cString\u003e] [-Validation \u003cString\u003e] [-Handler \u003cScriptBlock\u003e] [-Hidden]\r\n [-Default] [-Initialize] [-DisableValidation] [-DisableHandler] [-EnableException] -PersistedValue \u003cString\u003e [-PersistedType\r\n \u003cConfigurationValueType\u003e] [-SimpleExport] [-ModuleExport] [-PassThru] [-AllowDelete] [\u003cCommonParameters\u003e]\r\n\r\n Set-DbatoolsConfig -Name \u003cString\u003e [-Module \u003cString\u003e] [-Value \u003cObject\u003e] [-Description \u003cString\u003e] [-Validation \u003cString\u003e] [-Handler\r\n \u003cScriptBlock\u003e] [-Hidden] [-Default] [-Initialize] [-DisableValidation] [-DisableHandler] [-EnableException] [-SimpleExport]\r\n [-ModuleExport] [-PassThru] [-AllowDelete] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "returnValue\r\n-----------\r\n@{type=}", "Examples": "---------------------- Example 1: Simple ----------------------\r\n C:\\PS\u003e Set-DbatoolsConfig -FullName Path.DbatoolsData -Value E:\\temp\\dbatools\r\n\r\n Updates the configuration entry for Path.DbatoolsData to E:\\temp\\dbatools", "Name": "Set-DbatoolsConfig", "Params": [ [ "Default", "", "", false, "false", null, "" ], [ "Description", "", "", false, "false", null, "" ], [ "DisableHandler", "", "", false, "false", null, "" ], [ "DisableValidation", "", "", false, "false", null, "" ], [ "EnableException", "", "", false, "false", null, "" ], [ "FullName", "", "", true, "false", null, "" ], [ "Handler", "", "", false, "false", null, "" ], [ "Hidden", "", "", false, "false", null, "" ], [ "Initialize", "", "", false, "false", null, "" ], [ "Module", "", "", false, "false", null, "" ], [ "ModuleExport", "", "", false, "false", null, "" ], [ "Name", "", "", true, "false", null, "" ], [ "PassThru", "", "", false, "false", null, "" ], [ "PersistedType", "", "", false, "false", null, "" ], [ "PersistedValue", "", "", true, "false", null, "" ], [ "Register", "", "", false, "false", null, "" ], [ "SimpleExport", "", "", false, "false", null, "" ], [ "Validation", "", "", false, "false", null, "" ], [ "Value", "", "", false, "false", null, "" ] ], "Links": null, "Availability": "Windows, Linux, macOS" }, { "Name": "Set-DbatoolsInsecureConnection", "Description": "Microsoft changed the default connection settings in SQL Server client libraries to require encryption and validate certificates, which can break existing dbatools scripts and connections in development environments. This function reverts those security defaults by configuring dbatools to trust all server certificates and disable encryption requirements.\n\nThe function sets two key dbatools configuration values: sql.connection.trustcert (true) and sql.connection.encrypt (false). By default, these settings persist across PowerShell sessions, but you can use -SessionOnly to apply them temporarily.\n\nThis is particularly useful when working with development servers, self-signed certificates, or legacy environments where the new security defaults cause connection failures.\n\nYou can read more here: https://dbatools.io/newdefaults", "Synopsis": "Reverts SQL Server connection security defaults to disable encryption and trust all certificates", "Outputs": "None\nThis command configures dbatools connection security settings but does not output any objects to the pipeline.\r\nThe internal configuration values are applied silently to enable insecure connections (disabled encryption, trusted certificates).", "Alias": "", "CommandName": "Set-DbatoolsInsecureConnection", "Availability": "Windows, Linux, macOS", "Links": "https://dbatools.io/Set-DbatoolsInsecureConnection\nhttps://blog.netnerds.net/2023/03/new-defaults-for-sql-server-connections-encryption-trust-certificate/", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbatoolsInsecureConnection\nSets the default connection settings to trust all server certificates and not require encrypted connections.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSet-DbatoolsInsecureConnection -SessionOnly\nSets the default connection settings to trust all server certificates and not require encrypted connections.\nDoes not persist across sessions so the default will return if you close and reopen PowerShell.", "Params": [ [ "SessionOnly", "Applies the insecure connection settings only to the current PowerShell session instead of persisting them permanently.\r\nUse this when testing connection settings or when you need insecure connections temporarily without changing your permanent dbatools configuration.", "", false, "false", "False", "" ], [ "Scope", "Specifies where to store the persistent connection settings when SessionOnly is not used. Defaults to UserDefault.\r\nUserDefault applies to the current user only, while SystemDefault applies to all users on the machine.", "", false, "false", "UserDefault", "" ], [ "Register", "This parameter is deprecated and will be removed in a future release.\r\nThe function now automatically handles registration of settings when SessionOnly is not specified.", "", false, "false", "False", "" ] ], "Syntax": "Set-DbatoolsInsecureConnection [-SessionOnly] [[-Scope] {UserDefault | UserMandatory | SystemDefault | SystemMandatory | FileUserLocal | FileUserShared | FileSystem}] [-Register] [\u003cCommonParameters\u003e]" }, { "Name": "Set-DbatoolsPath", "Description": "Configures or updates a path under a name.\nThe path can be persisted using the \"-Register\" command.\nPaths setup like this can be retrieved using Get-DbatoolsPath.", "Synopsis": "Configures or updates a path under a name.", "Outputs": "None\nThis command configures internal dbatools path settings but does not output any objects to the pipeline.\r\nUse Get-DbatoolsPath to retrieve the configured path values.", "Alias": "", "CommandName": "Set-DbatoolsPath", "Availability": "Windows, Linux, macOS", "Links": "https://dbatools.io/Set-DbatoolsPath", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSet-DbatoolsPath -Name \u0027temp\u0027 -Path \u0027C:\\temp\u0027\nConfigures C:\\temp as the current temp path. (does not override $Env:TEMP !)", "Params": [ [ "Name", "Specifies the alias name to associate with the path for easy retrieval.\r\nUse descriptive names like \u0027backups\u0027, \u0027scripts\u0027, or \u0027logs\u0027 to organize commonly used directory paths.\r\nThe name can be referenced later with Get-DbatoolsPath to quickly access the stored path.", "", true, "false", "", "" ], [ "Path", "Specifies the directory path to store under the given name.\r\nCan be any valid file system path including network shares and mapped drives.\r\nUse this to centralize path management for backup locations, script directories, or output folders.", "", true, "false", "", "" ], [ "Register", "Persists the path configuration across PowerShell sessions and module reloads.\r\nWithout this switch, the path mapping only exists for the current session.\r\nEssential when setting up permanent path aliases for team environments or automated scripts.", "", true, "false", "False", "" ], [ "Scope", "Determines where the persistent configuration is stored when using -Register.\r\nUserDefault stores the setting for the current user only, while other scopes affect system-wide or module-level settings.\r\nChoose the appropriate scope based on whether the path should be available to all users or just the current user.", "", false, "false", "UserDefault", "" ] ], "Syntax": "Set-DbatoolsPath -Name \u003cString\u003e -Path \u003cString\u003e [\u003cCommonParameters\u003e]\nSet-DbatoolsPath -Name \u003cString\u003e -Path \u003cString\u003e -Register [-Scope {UserDefault | UserMandatory | SystemDefault | SystemMandatory | FileUserLocal | FileUserShared | FileSystem}] [\u003cCommonParameters\u003e]" }, { "Tags": [ "Database", "FileSystem" ], "CommandName": "Show-DbaDbList", "Name": "Show-DbaDbList", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Show-DbaDbList [-SqlInstance] \u003cDbaInstanceParameter\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Title] \u003cString\u003e] [[-Header] \u003cString\u003e] [[-DefaultDb] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.String\nReturns the name of the selected database when the user selects a database and clicks OK.\r\nFor example: \"master\", \"msdb\", \"model\", \"tempdb\", or any user-created database name.\nReturns $null if the user cancels the dialog, closes the window without selecting a database, or if the OK button is not explicitly clicked.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eShow-DbaDbList -SqlInstance sqlserver2014a\nShows a GUI list of databases using Windows Authentication to connect to the SQL Server. Returns a string of the selected database.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eShow-DbaDbList -SqlInstance sqlserver2014a -SqlCredential $cred\nShows a GUI list of databases using SQL credentials to connect to the SQL Server. Returns a string of the selected database.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eShow-DbaDbList -SqlInstance sqlserver2014a -DefaultDb master\nShows a GUI list of databases using Windows Authentication to connect to the SQL Server. The \"master\" database will be selected when the lists shows. Returns a string of the selected database.", "Description": "Creates a Windows Presentation Framework dialog that connects to a SQL Server instance and presents all databases in a visual tree view for selection. This eliminates the need to hardcode database names in scripts or remember exact database names when building interactive tools.\n\nThe function returns the name of the selected database as a string, making it ideal for building user-friendly maintenance scripts, allowing end users to choose databases without SQL Server Management Studio, or creating dynamic tools that work across different environments where database names may vary.\n\nClicking OK returns the selected database name, while Cancel returns null, allowing your scripts to handle user cancellation gracefully.", "Links": "https://dbatools.io/Show-DbaDbList", "Synopsis": "Displays available databases in an interactive selection window", "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", "", "" ], [ "Title", "Sets the title text that appears in the window\u0027s title bar. Defaults to \"Select Database\".\r\nUse this to customize the dialog title for specific maintenance scripts or to indicate the purpose of the database selection.", "", false, "false", "Select Database", "" ], [ "Header", "Specifies the instruction text displayed above the database tree view. Defaults to \"Select the database:\".\r\nCustomize this to provide context-specific instructions like \"Choose database to backup:\" or \"Select database for maintenance:\".", "", false, "false", "Select the database:", "" ], [ "DefaultDb", "Pre-selects a specific database when the selection dialog opens.\r\nUse this when you have a preferred or most commonly selected database to reduce clicks for end users.", "", 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", "FileSystem", "OS" ], "CommandName": "Show-DbaInstanceFileSystem", "Name": "Show-DbaInstanceFileSystem", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Show-DbaInstanceFileSystem [-SqlInstance] \u003cDbaInstanceParameter\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.String\nReturns the full directory path with trailing backslash when the user selects a folder and clicks OK.\r\nFor example: \"C:\\\", \"D:\\Backup\\\", or \"C:\\Program Files\\Microsoft SQL Server\\\".\nReturns $null if the user cancels the dialog or closes the window without selecting a path.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eShow-DbaInstanceFileSystem -SqlInstance sql2017\nShows a list of databases using Windows Authentication to connect to the SQL Server. Returns a string of the selected path.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eShow-DbaInstanceFileSystem -SqlInstance sql2017 -SqlCredential $cred\nShows a list of databases using SQL credentials to connect to the SQL Server. Returns a string of the selected path.", "Description": "Similar to the remote file system popup you see when browsing a remote SQL Server in SQL Server Management Studio, this function allows you to traverse the remote SQL Server\u0027s file structure. This replaces the need to manually type or guess directory paths when setting up backup locations, restore operations, or specifying data and log file paths.\n\nShow-DbaInstanceFileSystem uses SQL Management Objects to browse the directories and what you see is limited to the permissions of the account running the command. The function opens a Windows Presentation Framework GUI with a familiar tree view interface, complete with drive and folder icons, making it easy to navigate and select the correct directory path for your SQL Server operations.", "Links": "https://dbatools.io/Show-DbaInstanceFileSystem", "Synopsis": "Displays a GUI tree view for browsing remote SQL Server file systems and returns the selected directory path", "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", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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": "Start-DbaAgentJob", "Name": "Start-DbaAgentJob", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Start-DbaAgentJob [-SqlCredential \u003cPSCredential\u003e] [-Job \u003cString[]\u003e] [-StepName \u003cString\u003e] [-ExcludeJob \u003cString[]\u003e] [-AllJobs] [-Wait] [-Parallel] [-WaitPeriod \u003cInt32\u003e] [-SleepPeriod \u003cInt32\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nStart-DbaAgentJob -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Job \u003cString[]\u003e] [-StepName \u003cString\u003e] [-ExcludeJob \u003cString[]\u003e] [-AllJobs] [-Wait] [-Parallel] [-WaitPeriod \u003cInt32\u003e] [-SleepPeriod \u003cInt32\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nStart-DbaAgentJob [-SqlCredential \u003cPSCredential\u003e] [-Job \u003cString[]\u003e] [-StepName \u003cString\u003e] [-ExcludeJob \u003cString[]\u003e] -InputObject \u003cJob[]\u003e [-AllJobs] [-Wait] [-Parallel] [-WaitPeriod \u003cInt32\u003e] [-SleepPeriod \u003cInt32\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Agent.Job\nReturns one SQL Server Agent Job object per job started. Job objects are returned from Get-DbaAgentJob after the job execution completes (when -Wait is specified) or immediately after starting \r\n(without -Wait).\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 Agent job\r\n- CurrentRunStatus: The current execution status of the job (Idle, Executing, etc.)\r\n- LastRunDate: DateTime of the most recent job execution\r\n- LastRunOutcome: Outcome of the last run (Succeeded, Failed, Cancelled, etc.)\r\n- IsEnabled: Boolean indicating if the job is enabled\r\n- HasSchedule: Boolean indicating if the job has schedules\r\n- OwnerLoginName: Login that owns the job\nAdditional properties available (from SMO Agent.Job object):\r\n- JobSteps: Collection of job steps defined in this job\r\n- Schedules: Collection of schedules assigned to this job\r\n- Notifications: Notification settings for the job\r\n- Category: The job category name\r\n- CategoryID: The job category ID\r\n- CreatedDate: DateTime when the job was created\r\n- Description: Job description text\nNote: When using sequential processing without -Wait, jobs start but the command returns after they begin. When using -Wait (sequential or parallel), the command waits for job completion before \r\nreturning results.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eStart-DbaAgentJob -SqlInstance localhost\nStarts all running SQL Agent Jobs on the local SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgentJob -SqlInstance sql2016 -Job cdc.DBWithCDC_capture | Start-DbaAgentJob\nStarts the cdc.DBWithCDC_capture SQL Agent Job on sql2016\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eStart-DbaAgentJob -SqlInstance sql2016 -Job cdc.DBWithCDC_capture\nStarts the cdc.DBWithCDC_capture SQL Agent Job on sql2016\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$servers | Find-DbaAgentJob -IsFailed | Start-DbaAgentJob\nRestarts all failed jobs on all servers in the $servers collection\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eStart-DbaAgentJob -SqlInstance sql2016 -AllJobs\nStart all the jobs\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eStart-DbaAgentJob -SqlInstance sql2016 -Job @(\u0027Job1\u0027, \u0027Job2\u0027, \u0027Job3\u0027) -Wait\nThis is a serialized approach to submitting jobs and waiting for each job to continue the next.\r\nStarts Job1, waits for completion of Job1\r\nStarts Job2, waits for completion of Job2\r\nStarts Job3, Waits for completion of Job3\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eStart-DbaAgentJob -SqlInstance sql2016 -Job @(\u0027Job1\u0027, \u0027Job2\u0027, \u0027Job3\u0027) -Wait -Parallel\nThis is a parallel approach to submitting all jobs and waiting for them all to complete.\r\nStarts Job1, starts Job2, starts Job3 and waits for completion of Job1, Job2, and Job3.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eStart-DbaAgentJob -SqlInstance sql2016 -Job JobWith5Steps -StepName Step4\nStarts the JobWith5Steps SQL Agent Job at step Step4.", "Description": "Starts one or more SQL Server Agent jobs that are currently idle. This function validates jobs are in an idle state before starting them and can optionally wait for job completion before returning results. You can start all jobs, specific jobs by name, or exclude certain jobs from execution. It also supports starting jobs at specific steps rather than from the beginning, which is useful for resuming failed jobs or testing individual job steps.", "Links": "https://dbatools.io/Start-DbaAgentJob", "Synopsis": "Starts SQL Server Agent jobs and optionally waits for completion", "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", "", "" ], [ "Job", "Specifies the names of specific SQL Agent jobs to start. Accepts job names as strings and supports multiple job names in an array.\r\nUse this when you need to start only certain jobs instead of all jobs on the server. Job names are case-sensitive and must match exactly.", "", false, "false", "", "" ], [ "StepName", "Specifies the job step name where job execution should begin instead of starting from the first step.\r\nUse this to resume a failed job at a specific step or to test individual job steps without running the entire job sequence.", "", false, "false", "", "" ], [ "ExcludeJob", "Specifies job names to exclude from starting when using -AllJobs or when no specific jobs are specified.\r\nUse this to start all jobs except certain ones, such as excluding maintenance jobs during business hours or problematic jobs that need special handling.", "", false, "false", "", "" ], [ "InputObject", "Accepts SQL Agent job objects from the pipeline, typically from Get-DbaAgentJob or other dbatools functions.\r\nUse this when chaining dbatools commands together to start jobs that meet specific criteria, such as failed jobs or jobs with certain schedules.", "", true, "true (ByValue)", "", "" ], [ "AllJobs", "Starts all SQL Agent jobs that are currently in an idle state on the target instance.\r\nUse this switch when you need to start all available jobs, typically after server maintenance or during bulk job execution scenarios.", "", false, "false", "False", "" ], [ "Wait", "Waits for each job to complete execution before returning results or proceeding to the next job.\r\nUse this when you need to ensure job completion before continuing your script, or when jobs have dependencies that require sequential execution.", "", false, "false", "False", "" ], [ "Parallel", "Starts all specified jobs simultaneously and waits for all to complete, rather than starting and waiting for each job sequentially.\r\nUse this when jobs can run concurrently without conflicts to reduce total execution time. Requires the -Wait parameter to function.", "", false, "false", "False", "" ], [ "WaitPeriod", "Sets the polling interval in seconds for checking job status when using the -Wait parameter. Defaults to 3 seconds.\r\nAdjust this value based on your job duration - use shorter intervals for quick jobs or longer intervals for jobs that run for hours to reduce server load.", "", false, "false", "3", "" ], [ "SleepPeriod", "Sets the initial wait time in milliseconds after starting a job before checking its status. Defaults to 300 milliseconds.\r\nIncrease this value if you experience issues with jobs not showing as started immediately, which can occur on heavily loaded servers.", "", false, "false", "300", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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": [ "Certificate", "Security" ], "CommandName": "Start-DbaDbEncryption", "Name": "Start-DbaDbEncryption", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Start-DbaDbEncryption [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-EncryptorName] \u003cString\u003e] [[-EncryptorType] \u003cString\u003e] [[-Database] \u003cString[]\u003e] [-BackupPath] \u003cString\u003e [-MasterKeySecurePassword] \u003cSecureString\u003e [[-CertificateSubject] \u003cString\u003e] [[-CertificateStartDate] \u003cDateTime\u003e] [[-CertificateExpirationDate] \u003cDateTime\u003e] [-CertificateActiveForServiceBrokerDialog] [-BackupSecurePassword] \u003cSecureString\u003e [[-InputObject] \u003cDatabase[]\u003e] [-AllUserDatabases] [-Force] [-Parallel] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nWhen using the -Parallel parameter, returns one object per database after encryption is enabled. In sequential mode, no output is returned to the pipeline, only progress messages.\nProperties (when -Parallel is specified):\r\n- ComputerName: The computer name of the SQL Server instance where encryption was applied\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 that was encrypted\r\n- EncryptionEnabled: Boolean indicating if encryption was successfully enabled on the database\r\n- Status: String indicating operation result - either \"Success\" or \"Failed\"\r\n- Error: Error message if Status is \"Failed\", otherwise null\nNote: Sequential processing (default, without -Parallel) does not output to the pipeline. Use -Parallel to receive result objects for each encrypted database.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$masterkeypass = (Get-Credential justneedpassword).Password\nPS C:\\\u003e $certbackuppass = (Get-Credential justneedpassword).Password\r\nPS C:\\\u003e $params = @{\r\n\u003e\u003e SqlInstance = \"sql01\"\r\n\u003e\u003e AllUserDatabases = $true\r\n\u003e\u003e MasterKeySecurePassword = $masterkeypass\r\n\u003e\u003e BackupSecurePassword = $certbackuppass\r\n\u003e\u003e BackupPath = \"C:\\temp\"\r\n\u003e\u003e EnableException = $true\r\n\u003e\u003e }\r\nPS C:\\\u003e Start-DbaDbEncryption @params\nPrompts for two passwords (the username doesn\u0027t matter, this is just an easy \u0026 secure way to get a secure password)\nThen encrypts all user databases on sql01, creating master keys and certificates as needed, and backing all of them up to C:\\temp, securing them with the password set in $certbackuppass\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$masterkeypass = (Get-Credential justneedpassword).Password\nPS C:\\\u003e $certbackuppass = (Get-Credential justneedpassword).Password\r\nPS C:\\\u003e $splatEncryption = @{\r\n\u003e\u003e SqlInstance = \"sql01\", \"sql02\"\r\n\u003e\u003e AllUserDatabases = $true\r\n\u003e\u003e MasterKeySecurePassword = $masterkeypass\r\n\u003e\u003e BackupSecurePassword = $certbackuppass\r\n\u003e\u003e BackupPath = \"\\\\backup\\tde\"\r\n\u003e\u003e Parallel = $true\r\n\u003e\u003e }\r\nPS C:\\\u003e Start-DbaDbEncryption @splatEncryption\nEncrypts all user databases on sql01 and sql02 using parallel processing for improved performance.\r\nMaster keys and certificates are created sequentially per instance, then database encryption operations run in parallel.", "Description": "Automates the complete TDE implementation process from start to finish, handling all the complex key management steps that would otherwise require multiple manual commands. This function sets up the entire encryption infrastructure including master keys, certificates or asymmetric keys, database encryption keys, and automatically backs up all encryption components to protect against data loss.\n\nThe function performs these operations in sequence: ensures a service master key exists in the master database and backs it up, creates or validates a database certificate or asymmetric key in master and backs it up, creates a database encryption key in each target database, and finally enables encryption on the databases. This eliminates the tedious manual process of running separate commands for each TDE component and ensures you don\u0027t miss critical backup steps that could leave your encrypted databases unrecoverable.\n\nMost valuable for compliance initiatives where you need to encrypt multiple databases quickly while maintaining proper key backup procedures. Also essential for disaster recovery planning since it ensures all encryption keys are properly backed up during the initial setup process.", "Links": "https://dbatools.io/Start-DbaDbEncryption", "Synopsis": "Implements Transparent Data Encryption (TDE) on user databases with automated key infrastructure and backup management", "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", "", "" ], [ "EncryptorName", "Specifies the name of the certificate or asymmetric key in the master database that will encrypt the database encryption keys.\r\nIf not specified, the function will automatically find an existing certificate or asymmetric key. When used with -Force, creates a new certificate with this name if none exists.\r\nFor asymmetric keys, the key must reside on an extensible key management provider to encrypt database encryption keys.", "Certificate,CertificateName", false, "false", "", "" ], [ "EncryptorType", "Determines whether to use a certificate or asymmetric key for TDE encryption. Defaults to Certificate.\r\nCertificate is the most common choice for standard TDE implementations. Use AsymmetricKey when integrating with extensible key management providers.", "", false, "false", "Certificate", "AsymmetricKey,Certificate" ], [ "Database", "Specifies which user databases to encrypt with Transparent Data Encryption (TDE). Accepts single database names, arrays, or wildcards.\r\nUse this when you need to encrypt specific databases instead of all user databases on the instance.", "", false, "false", "", "" ], [ "BackupPath", "Directory path where master key and certificate backup files will be stored, accessible by the SQL Server service account.\r\nCritical for disaster recovery as these backups are required to restore TDE-encrypted databases.\r\nEnsure this path has appropriate security permissions and is included in your backup strategy.", "", true, "false", "", "" ], [ "MasterKeySecurePassword", "Secure password used to create and protect the service master key in the master database if one doesn\u0027t exist.\r\nRequired for all TDE operations because the function cannot determine if master key creation is needed until runtime.\r\nThis password protects the root of the encryption hierarchy and is critical for disaster recovery.", "", true, "false", "", "" ], [ "CertificateSubject", "Sets the subject field for TDE certificates created during the encryption process.\r\nUse this to standardize certificate naming for compliance or organizational requirements.", "", false, "false", "", "" ], [ "CertificateStartDate", "Specifies when TDE certificates become valid. Defaults to the current date and time.\r\nUseful for planned encryption rollouts where certificates need to activate at a specific time.", "", false, "false", "(Get-Date)", "" ], [ "CertificateExpirationDate", "Sets when TDE certificates will expire. Defaults to 5 years from the current date.\r\nPlan certificate renewals well before expiration to avoid service disruptions during database operations.", "", false, "false", "(Get-Date).AddYears(5)", "" ], [ "CertificateActiveForServiceBrokerDialog", "Enables the TDE certificate for Service Broker dialog security in addition to database encryption.\r\nUse this when your databases utilize Service Broker and need certificate-based dialog security.", "", false, "false", "False", "" ], [ "BackupSecurePassword", "Secure password used to encrypt backup files for master keys and certificates created during TDE setup.\r\nEssential for disaster recovery as these backups are required to restore encrypted databases on different servers.\r\nMust be stored securely as losing this password makes the encrypted data unrecoverable.", "", true, "false", "", "" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase for TDE encryption via pipeline.\r\nAllows filtering and processing specific databases before encryption, useful for complex selection criteria.", "", false, "true (ByValue)", "", "" ], [ "AllUserDatabases", "Encrypts all user databases on the instance, excluding system databases (master, model, tempdb, msdb).\r\nUse this for compliance initiatives when you need to encrypt every user database quickly.\r\nSystem databases are automatically excluded as they cannot be encrypted with TDE.", "", false, "false", "False", "" ], [ "Force", "Creates a new certificate with the specified EncryptorName if it doesn\u0027t exist in the master database.\r\nRequires EncryptorName to be specified. Use this when you need to establish new TDE infrastructure with specific naming conventions.", "", false, "false", "False", "" ], [ "Parallel", "Enables parallel processing of databases using runspace pools with 1-10 concurrent threads.\r\nUse this when enabling encryption on multiple databases to improve performance.\r\nShared resources (master keys and certificates) are created sequentially before parallel processing begins.\r\nWithout this switch, databases are processed sequentially.", "", 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": "Endpoint", "CommandName": "Start-DbaEndpoint", "Name": "Start-DbaEndpoint", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Start-DbaEndpoint [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Endpoint] \u003cString[]\u003e] [-AllEndpoints] [[-InputObject] \u003cEndpoint[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Endpoint\nReturns the Endpoint object(s) that were successfully started.\nProperties:\r\n- Name: The endpoint name\r\n- EndpointState: The state of the endpoint (Started, Stopped, Disabled)\r\n- EndpointType: The type of endpoint (DatabaseMirroring, ServiceBroker, Tsql, SoapEndpoint, etc.)\r\n- ProtocolType: The communication protocol used (TCP, NamedPipes, SharedMemory)\r\n- Owner: The owner of the endpoint\r\n- IsAdminEndpoint: Boolean indicating if this is an administrative endpoint\r\n- IsSystemObject: Boolean indicating if this is a system-created endpoint\r\n- ID: Unique identifier for the endpoint\r\n- Parent: References the parent Server object", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eStart-DbaEndpoint -SqlInstance sqlserver2012 -AllEndpoints\nStarts all endpoints on the sqlserver2014 instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eStart-DbaEndpoint -SqlInstance sqlserver2012 -Endpoint endpoint1,endpoint2 -SqlCredential sqladmin\nLogs into sqlserver2012 using alternative credentials and starts the endpoint1 and endpoint2 endpoints.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-Endpoint -SqlInstance sqlserver2012 -Endpoint endpoint1 | Start-DbaEndpoint\nStarts the endpoints returned from the Get-Endpoint function.", "Description": "Starts stopped SQL Server endpoints that are required for Database Mirroring, Service Broker, SOAP, and custom TCP connections. Endpoints must be in a started state to accept network connections and facilitate features like Availability Groups, database mirroring partnerships, and Service Broker message routing. This function is commonly used after maintenance windows, server restarts, or when troubleshooting connectivity issues where endpoints were inadvertently stopped.", "Links": "https://dbatools.io/Start-DbaEndpoint", "Synopsis": "Starts stopped SQL Server endpoints for Database Mirroring, Service Broker, and other network services.", "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", "", "" ], [ "Endpoint", "Specifies the names of specific endpoints to start on the target SQL Server instance.\r\nUse this when you only need to start particular endpoints like Database Mirroring or Service Broker endpoints rather than all endpoints on the server.", "", false, "false", "", "" ], [ "AllEndpoints", "Starts all endpoints on the target SQL Server instance regardless of their current state or type.\r\nThis is required when using the SqlInstance parameter and you want to start all endpoints rather than specific ones.", "", false, "false", "False", "" ], [ "InputObject", "Accepts endpoint objects from the pipeline, typically from Get-DbaEndpoint cmdlet output.\r\nUse this to start endpoints that have already been retrieved and filtered by other dbatools 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", "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": "Start-DbaMigration", "Name": "Start-DbaMigration", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Start-DbaMigration [[-Source] \u003cDbaInstanceParameter\u003e] [[-Destination] \u003cDbaInstanceParameter[]\u003e] [-DetachAttach] [-Reattach] [-BackupRestore] [[-SharedPath] \u003cString\u003e] [-WithReplace] [-NoRecovery] [-SetSourceReadOnly] [-SetSourceOffline] [-ReuseSourceFolderStructure] [-IncludeSupportDbs] [[-SourceSqlCredential] \u003cPSCredential\u003e] [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-Exclude] \u003cString[]\u003e] [-DisableJobsOnDestination] [-DisableJobsOnSource] [-ExcludeSaRename] [-UseLastBackup] [-KeepCDC] [-KeepReplication] [-Continue] [-Force] [[-AzureCredential] \u003cString\u003e] [[-MasterKeyPassword] \r\n\u003cSecureString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "Start-SqlMigration", "Outputs": "Object (output from Copy-DbaDatabase command when -Exclude Databases is not specified)\nWhen databases are migrated (default behavior unless -Exclude Databases is used), this function returns the output from Copy-DbaDatabase. The specific object type and properties depend on the \r\nmigration method selected:\nWhen using -BackupRestore method:\r\nReturns database migration status objects showing which databases were successfully restored on destination servers.\nWhen using -DetachAttach method:\r\nReturns database reattachment status objects showing which databases were successfully attached on destination servers.\nNo output is returned when -Exclude Databases is specified, as the function then only migrates server-level objects without providing pipeline output.\nAll other migration operations (logins, SQL Agent jobs, configuration, etc.) perform their tasks without returning objects to the pipeline. Use -Verbose to see detailed progress messages for all \r\nmigration steps.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eStart-DbaMigration -Source sqlserver\\instance -Destination sqlcluster -DetachAttach\nAll databases, logins, job objects and sp_configure options will be migrated from sqlserver\\instance to sqlcluster. Databases will be migrated using the detach/copy files/attach method. Dbowner will \r\nbe updated. User passwords, SIDs, database roles and server roles will be migrated along with the login.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$params = @{\n\u003e\u003e Source = \"sqlcluster\"\r\n\u003e\u003e Destination = \"sql2016\"\r\n\u003e\u003e SourceSqlCredential = $scred\r\n\u003e\u003e DestinationSqlCredential = $cred\r\n\u003e\u003e SharedPath = \"\\\\fileserver\\share\\sqlbackups\\Migration\"\r\n\u003e\u003e BackupRestore = $true\r\n\u003e\u003e ReuseSourceFolderStructure = $true\r\n\u003e\u003e Force = $true\r\n\u003e\u003e }\r\n\u003e\u003e\r\nPS C:\\\u003e Start-DbaMigration @params -Verbose\nUtilizes splatting technique to set all the needed parameters. This will migrate databases using the backup/restore method. It will also include migration of the logins, database mail configuration, \r\ncredentials, SQL Agent, Central Management Server, and SQL Server global configuration.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eStart-DbaMigration -Verbose -Source sqlcluster -Destination sql2016 -DetachAttach -Reattach -SetSourceReadonly\nMigrates databases using detach/copy/attach. Reattach at source and set source databases read-only. Also migrates everything else.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eStart-DbaMigration -Verbose -Source sqlcluster -Destination sql2016 -BackupRestore -SharedPath \"\\\\fileserver\\backups\" -SetSourceOffline\nMigrates databases using backup/restore method. Sets source databases offline before migration to prevent any connections during the process.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$PSDefaultParameters = @{\n\u003e\u003e \"dbatools:Source\" = \"sqlcluster\"\r\n\u003e\u003e \"dbatools:Destination\" = \"sql2016\"\r\n\u003e\u003e }\r\n\u003e\u003e\r\nPS C:\\\u003e Start-DbaMigration -Verbose -Exclude Databases, Logins\nUtilizes the PSDefaultParameterValues system variable, and sets the Source and Destination parameters for any function in the module that has those parameter names. This prevents the need from \r\npassing them in constantly.\r\nThe execution of the function will migrate everything but logins and databases.", "Description": "Start-DbaMigration consolidates most of the migration tools in dbatools into one command for complete instance migrations. This function serves as an \"easy button\" when you need to move an entire SQL Server instance to new hardware, perform version upgrades, or consolidate servers. It\u0027s less flexible than using individual migration functions but handles the complexity of orchestrating a full migration workflow.\n\nThe function migrates:\n\nAll user databases to exclude support databases such as ReportServerTempDB (Use -IncludeSupportDbs for this). Use -Exclude Databases to skip.\nAll logins. Use -Exclude Logins to skip.\nAll database mail objects. Use -Exclude DatabaseMail\nAll credentials. Use -Exclude Credentials to skip.\nAll objects within the Job Server (SQL Agent). Use -Exclude AgentServer to skip.\nAll linked servers. Use -Exclude LinkedServers to skip.\nAll groups and servers within Central Management Server. Use -Exclude CentralManagementServer to skip.\nAll SQL Server configuration objects (everything in sp_configure). Use -Exclude SpConfigure to skip.\nAll user objects in system databases. Use -Exclude SysDbUserObjects to skip.\nAll system triggers. Use -Exclude SystemTriggers to skip.\nAll system backup devices. Use -Exclude BackupDevices to skip.\nAll Audits. Use -Exclude Audits to skip.\nAll Endpoints. Use -Exclude Endpoints to skip.\nAll Extended Events. Use -Exclude ExtendedEvents to skip.\nAll Policy Management objects. Use -Exclude PolicyManagement to skip.\nAll Resource Governor objects. Use -Exclude ResourceGovernor to skip.\nAll Server Audit Specifications. Use -Exclude ServerAuditSpecifications to skip.\nAll Custom Errors (User Defined Messages). Use -Exclude CustomErrors to skip.\nAll Server Roles. Use -Exclude ServerRoles to skip.\nAll Data Collector collection sets. Does not configure the server. Use -Exclude DataCollector to skip.\nAll startup procedures. Use -Exclude StartupProcedures to skip.\nAll custom Extended Stored Procedures. Use -Exclude ExtendedStoredProcedures to skip.\n\nThis script provides the ability to migrate databases using detach/copy/attach or backup/restore. SQL Server logins, including passwords, SID and database/server roles can also be migrated. In addition, job server objects can be migrated and server configuration settings can be exported or migrated. This script works with named instances, clusters and SQL Express.\n\nBy default, databases will be migrated to the destination SQL Server\u0027s default data and log directories. You can override this by specifying -ReuseSourceFolderStructure. Filestreams and filegroups are also migrated. Safety is emphasized.", "Links": "https://dbatools.io/Start-DbaMigration", "Synopsis": "Migrates entire SQL Server instances including all databases, logins, server configuration, and server objects from source to destination servers.", "Availability": "Windows, Linux, macOS", "Params": [ [ "Source", "Specifies the source SQL Server instance to migrate from. Accepts server name, server\\instance, or connection string formats.\r\nThis is the instance where all databases, logins, and server objects currently exist.", "", false, "false", "", "" ], [ "Destination", "Specifies one or more destination SQL Server instances to migrate to. Accepts server name, server\\instance, or connection string formats.\r\nWhen specifying multiple destinations, all objects will be migrated to each destination server.\r\nMultiple destinations require -Reattach when using -DetachAttach method.", "", false, "false", "", "" ], [ "DetachAttach", "Uses detach, copy, and attach method to migrate databases. Temporarily makes databases unavailable during the migration process.\r\nFiles are copied using BITS over administrative shares and databases are reattached if destination attachment fails.\r\nThis method is faster than backup/restore but requires downtime and breaks mirroring/replication.", "", false, "false", "False", "" ], [ "Reattach", "Reattaches all databases to the source server after a detach/attach migration completes.\r\nUse this when you want to keep the source databases online after migration, such as for testing or gradual cutover scenarios.\r\nRequired when using -DetachAttach with multiple destination servers.", "", false, "false", "False", "" ], [ "BackupRestore", "Uses backup and restore method to migrate databases instead of detach/attach. Creates copy-only backups to preserve existing backup chains.\r\nRequires either -SharedPath for new backups or -UseLastBackup to restore from existing backup files.\r\nThis method is safer for production environments as it doesn\u0027t detach databases.", "", false, "false", "False", "" ], [ "SharedPath", "Specifies the network path where backup files will be created and stored during migration. Must be a UNC path (\\\\server\\share) or Azure Storage URL.\r\nBoth source and destination SQL Server service accounts require read/write permissions to this location.\r\nOnly used with -BackupRestore method when not using -UseLastBackup.", "", false, "false", "", "" ], [ "WithReplace", "Forces restore operations to overwrite existing databases with the same name on the destination.\r\nUse this when you need to replace existing databases or when destination databases have different file paths than source.\r\nOnly applies to backup/restore method.", "", false, "false", "False", "" ], [ "NoRecovery", "Restores databases in NORECOVERY mode, leaving them in a restoring state for additional log backups.\r\nUse this when you plan to apply differential or transaction log backups after the initial restore.\r\nOnly applies to backup/restore method and prevents normal database access until recovered.", "", false, "false", "False", "" ], [ "SetSourceReadOnly", "Sets migrated databases to read-only mode on the source server before migration begins.\r\nThis prevents data changes during migration and helps ensure data consistency.\r\nWhen combined with -Reattach, databases remain read-only after being reattached to the source.", "", false, "false", "False", "" ], [ "SetSourceOffline", "Sets migrated databases offline on the source server before migration begins.\r\nThis prevents any connections to the source databases during migration, ensuring complete isolation.\r\nWhen combined with -Reattach, databases are brought back online after being reattached to the source.", "", false, "false", "False", "" ], [ "ReuseSourceFolderStructure", "Preserves the original file paths from the source server when restoring databases on the destination.\r\nBy default, databases are restored to the destination\u0027s default data and log directories.\r\nUse this when you need to maintain specific drive letters or folder structures on the destination server.", "", false, "false", "False", "" ], [ "IncludeSupportDbs", "Includes system support databases in the migration: ReportServer, ReportServerTempDB, SSISDB, and distribution databases.\r\nBy default, these databases are excluded to prevent conflicts with existing services.\r\nUse this when migrating servers with SQL Server Reporting Services, Integration Services, or replication configured.", "", false, "false", "False", "" ], [ "SourceSqlCredential", "Specifies credentials to connect to the source SQL Server instance. Use when the current Windows account lacks sufficient permissions.\r\nAccepts PowerShell credential objects created with Get-Credential for SQL Authentication or alternative Windows accounts.", "", false, "false", "", "" ], [ "DestinationSqlCredential", "Specifies credentials to connect to the destination SQL Server instance(s). Use when the current Windows account lacks sufficient permissions.\r\nAccepts PowerShell credential objects created with Get-Credential for SQL Authentication or alternative Windows accounts.", "", false, "false", "", "" ], [ "Exclude", "Specifies which migration components to skip during the migration process.\r\nUse this to exclude specific object types when you only need partial migrations or when certain objects should remain on the source.\r\nValid values: Databases, Logins, AgentServer, Credentials, LinkedServers, SpConfigure, CentralManagementServer, DatabaseMail, SysDbUserObjects, SystemTriggers, BackupDevices, Audits, Endpoints, \r\nExtendedEvents, PolicyManagement, ResourceGovernor, ServerAuditSpecifications, CustomErrors, ServerRoles, DataCollector, StartupProcedures, AgentServerProperties, MasterCertificates.", "", false, "false", "", "Databases,Logins,AgentServer,Credentials,LinkedServers,SpConfigure,CentralManagementServer,DatabaseMail,SysDbUserObjects,SystemTriggers,BackupDevices,Audits,Endpoints,ExtendedEvents,PolicyManagement,ResourceGovernor,ServerAuditSpecifications,CustomErrors,ServerRoles,DataCollector,StartupProcedures,ExtendedStoredProcedures,AgentServerProperties,MasterCertificates" ], [ "DisableJobsOnDestination", "Disables all migrated SQL Agent jobs on the destination server after migration completes.\r\nUse this to prevent jobs from running automatically on the destination until you\u0027re ready to activate them.\r\nHelpful for staged migrations or when you need to update job schedules before activation.", "", false, "false", "False", "" ], [ "DisableJobsOnSource", "Disables all SQL Agent jobs on the source server during the migration process.\r\nUse this to prevent jobs from running and potentially interfering with database migrations.\r\nJobs remain disabled on the source after migration completes.", "", false, "false", "False", "" ], [ "ExcludeSaRename", "Prevents renaming the sa account on the destination to match the source server\u0027s sa account name.\r\nBy default, the destination sa account is renamed to match the source for consistency.\r\nUse this when you want to maintain the destination server\u0027s original sa account name.", "", false, "false", "False", "" ], [ "UseLastBackup", "Uses existing backup files instead of creating new backups during database migration.\r\nThe function will locate the most recent full, differential, and log backups for each database.\r\nBackup files must be accessible to all destination servers, typically on a network share.", "", false, "false", "False", "" ], [ "KeepCDC", "Preserves Change Data Capture (CDC) configuration and data during database migration.\r\nBy default, CDC information is not migrated to avoid potential conflicts with existing CDC configurations.\r\nUse this when you need to maintain CDC functionality on the destination server.", "", false, "false", "False", "" ], [ "KeepReplication", "Preserves replication configuration and metadata during database migration.\r\nBy default, replication settings are not migrated to prevent conflicts with existing replication topologies.\r\nUse this when migrating databases that participate in replication and you want to maintain those settings.", "", false, "false", "False", "" ], [ "Continue", "Attempts to apply additional transaction log backups to databases already in RESTORING or STANDBY states.\r\nUse this to bring destination databases up-to-date when they were previously restored with NORECOVERY.\r\nOnly works with -UseLastBackup and requires databases to already exist in a restoring state.", "", false, "false", "False", "" ], [ "Force", "Overwrites existing objects on the destination server without prompting for confirmation.\r\nFor databases: drops existing databases with matching names before restoring.\r\nFor logins: drops and recreates existing logins instead of skipping them.\r\nFor DetachAttach method: breaks database mirroring and removes databases from Availability Groups.", "", false, "false", "False", "" ], [ "AzureCredential", "Specifies the name of a SQL Server credential for accessing Azure Storage when SharedPath points to an Azure Storage account.\r\nThe credential must already exist on both source and destination servers with proper access to the Azure Storage container.\r\nOnly needed when using Azure Storage URLs for the SharedPath parameter.", "", false, "false", "", "" ], [ "MasterKeyPassword", "Specifies the password for creating or opening database master keys during certificate migration.\r\nRequired when migrating databases with encrypted objects or certificates that need master key protection.\r\nMust be provided as a SecureString object 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": "PerfMon", "CommandName": "Start-DbaPfDataCollectorSet", "Name": "Start-DbaPfDataCollectorSet", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Start-DbaPfDataCollectorSet [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-CollectorSet] \u003cString[]\u003e] [[-InputObject] \u003cObject[]\u003e] [-NoWait] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one Performance Monitor Data Collector Set object for each collector set that was successfully started.\nProperties:\r\n- ComputerName: The name of the computer where the Data Collector Set is located\r\n- State: The current state of the Data Collector Set (Running, Stopped, etc.)\r\n- Name: The name of the Data Collector Set\r\n- DataCollectorSetObject: The underlying Windows Performance Monitor Data Collector Set COM object\nReturns nothing if no collector sets are found matching the specified parameters, if they are already running, if they are disabled, or if the -WhatIf parameter is used.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eStart-DbaPfDataCollectorSet\nAttempts to start all ready Collectors on localhost.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eStart-DbaPfDataCollectorSet -ComputerName sql2017\nAttempts to start all ready Collectors on localhost.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eStart-DbaPfDataCollectorSet -ComputerName sql2017, sql2016 -Credential ad\\sqldba -CollectorSet \u0027System Correlation\u0027\nStarts the \u0027System Correlation\u0027 Collector on sql2017 and sql2016 using alternative credentials.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorSet -CollectorSet \u0027System Correlation\u0027 | Start-DbaPfDataCollectorSet\nStarts the \u0027System Correlation\u0027 Collector.", "Description": "Starts Performance Monitor Data Collector Sets that have been configured to gather system performance data. This is useful for SQL Server performance troubleshooting when you need to collect OS-level metrics like CPU, memory, disk I/O, and network statistics alongside your SQL Server monitoring. The function checks the collector set status before starting and will skip sets that are already running or disabled.", "Links": "https://dbatools.io/Start-DbaPfDataCollectorSet", "Synopsis": "Starts Windows Performance Monitor Data Collector Sets on local or remote computers.", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the target computer(s) where Performance Monitor Data Collector Sets will be started. Defaults to localhost.\r\nUse this when you need to start collector sets on remote SQL Server machines or when managing multiple servers from a central location.", "", 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 Performance Monitor Data Collector Sets to start. When omitted, all ready collector sets will be started.\r\nUse this when you only need to start particular collector sets like \u0027System Performance\u0027 or custom sets created for SQL Server monitoring.", "DataCollectorSet", false, "false", "", "" ], [ "InputObject", "Accepts Performance Monitor Data Collector Set objects from Get-DbaPfDataCollectorSet via the pipeline. Objects must contain DataCollectorSetObject property.\r\nUse this when you want to filter collector sets with Get-DbaPfDataCollectorSet first, then start only the matching sets through the pipeline.", "", false, "true (ByValue)", "", "" ], [ "NoWait", "When specified, starts the collector set and returns results immediately without waiting for the startup process to complete.\r\nUse this when starting multiple collector sets in scripts where you don\u0027t need to confirm each one fully initialized before proceeding.", "", 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": [ "Service", "SqlServer", "Instance", "Connect" ], "CommandName": "Start-DbaService", "Name": "Start-DbaService", "Author": "Kirill Kravtsov (@nvarscar)", "Syntax": "Start-DbaService [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [-InstanceName \u003cString[]\u003e] [-SqlInstance \u003cDbaInstanceParameter[]\u003e] [-Type \u003cString[]\u003e] [-Timeout \u003cInt32\u003e] [-Credential \u003cPSCredential\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nStart-DbaService [-InstanceName \u003cString[]\u003e] [-Type \u003cString[]\u003e] -InputObject \u003cObject[]\u003e [-Timeout \u003cInt32\u003e] [-Credential \u003cPSCredential\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.ServiceProcess.ServiceController\nReturns one ServiceController object per service that was successfully started. Each object represents a SQL Server related service on the target computer(s).\nDefault display properties (from ServiceController):\r\n- Name: The service name (e.g., MSSQLSERVER, SQLSERVERAGENT, MSSQLServerOlapService)\r\n- DisplayName: The friendly display name of the service\r\n- Status: The current status of the service (Running, Stopped, StartPending, StopPending, etc.)\r\n- StartType: How the service starts (Boot, System, Automatic, Manual, Disabled)\nAdditional properties available from ServiceController:\r\n- ServiceName: The name of the service\r\n- ServiceType: The type of service\r\n- CanPauseAndContinue: Boolean indicating if the service can be paused and resumed\r\n- CanShutdown: Boolean indicating if the service should be notified of system shutdown\r\n- CanStop: Boolean indicating if the service can be stopped\r\n- ServiceHandle: The service\u0027s Windows handle\r\n- DependentServices: Collection of services that depend on this service\r\n- ServicesDependedOn: Collection of services that this service depends on\r\n- RequiredServices: Collection of services required for this service to run\nReturns nothing if no services are found matching the specified parameters, or if the -WhatIf parameter is used.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eStart-DbaService -ComputerName sqlserver2014a\nStarts the SQL Server related services on computer sqlserver2014a.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027sql1\u0027,\u0027sql2\u0027,\u0027sql3\u0027| Get-DbaService | Start-DbaService\nGets the SQL Server related services on computers sql1, sql2 and sql3 and starts them.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eStart-DbaService -ComputerName sql1,sql2 -Instance MSSQLSERVER\nStarts the SQL Server services related to the default instance MSSQLSERVER on computers sql1 and sql2.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eStart-DbaService -ComputerName $MyServers -Type SSRS\nStarts the SQL Server related services of type \"SSRS\" (Reporting Services) on computers in the variable MyServers.", "Description": "Starts SQL Server services (Engine, Agent, Browser, FullText, SSAS, SSIS, SSRS, PolyBase, Launchpad) on one or more computers following proper dependency order. This function handles the complexity of starting services in the correct sequence so you don\u0027t have to manually determine which services depend on others. Commonly used after maintenance windows, server reboots, or when troubleshooting stopped services across an environment.\n\nRequires Local Admin rights on destination computer(s).", "Links": "https://dbatools.io/Start-DbaService", "Synopsis": "Starts SQL Server related services across multiple computers while respecting service dependencies.", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the computer names where SQL Server services should be started. Accepts multiple computer names for bulk operations.\r\nUse this when you need to start services across multiple servers simultaneously, such as after a maintenance window or environment-wide restart.", "cn,host,Server", false, "false", "$env:COMPUTERNAME", "" ], [ "InstanceName", "Filters services to only those belonging to specific named instances. Does not affect default instance (MSSQLSERVER) services.\r\nUse this when you have multiple instances on the same server and only want to start services for specific named instances like SQL2019 or REPORTING.", "Instance", false, "false", "", "" ], [ "SqlInstance", "Use a combination of computername and instancename to get the SQL Server related services for specific instances on specific computers.\nParameters ComputerName and InstanceName will be ignored if SqlInstance is used.", "", false, "false", "", "" ], [ "Type", "Filters to specific SQL Server service types rather than starting all services. Valid types: Agent, Browser, Engine, FullText, SSAS, SSIS, SSRS, PolyBase, Launchpad.\r\nUse this when you need to start only specific service types, such as starting just SQL Agent after maintenance or only SSRS services on reporting servers.", "", false, "false", "", "Agent,Browser,Engine,FullText,SSAS,SSIS,SSRS,PolyBase,Launchpad" ], [ "InputObject", "Accepts service objects from Get-DbaService through the pipeline for targeted service operations.\r\nUse this when you need fine-grained control over which specific services to start, such as when Get-DbaService has filtered to stopped services only.", "ServiceCollection", true, "true (ByValue)", "", "" ], [ "Timeout", "Sets the maximum time in seconds to wait for each service to start before moving to the next service. Defaults to 60 seconds.\r\nIncrease this value for slow-starting services or when starting services on heavily loaded servers. Set to 0 to wait indefinitely.", "", false, "false", "60", "" ], [ "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", "" ], [ "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": "Trace", "CommandName": "Start-DbaTrace", "Name": "Start-DbaTrace", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Start-DbaTrace [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Id] \u003cInt32[]\u003e] [[-InputObject] \u003cObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object for each trace that was started or would be started (if -WhatIf is specified).\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 trace ID number\r\n- Status: Numeric trace status value (0=stopped, 1=running, 2=closed)\r\n- IsRunning: Boolean indicating if the trace is currently running\r\n- Path: The file path where the trace output is stored\r\n- MaxSize: Maximum size of the trace file in megabytes (0=unlimited)\r\n- StopTime: DateTime when the trace is scheduled to stop, or null if running indefinitely\r\n- MaxFiles: Maximum number of rollover files (0=unlimited)\r\n- IsRowset: Boolean indicating if trace output is written as rowset\r\n- IsRollover: Boolean indicating if rollover file creation is enabled\r\n- IsShutdown: Boolean indicating if trace will stop on server shutdown\r\n- IsDefault: Boolean indicating if this is the default system trace\r\n- BufferCount: Number of in-memory buffers allocated for the trace\r\n- BufferSize: Size of each buffer in kilobytes\r\n- FilePosition: Current file position for trace output\r\n- ReaderSpid: Server process ID reading the trace (SPID)\r\n- StartTime: DateTime when the trace was started\r\n- LastEventTime: DateTime of the most recent trace event\r\n- EventCount: Number of events captured by the trace\r\n- DroppedEventCount: Number of events dropped due to buffer limitations\nAdditional properties available but excluded from default view:\r\n- RemotePath: UNC path to the trace file for remote access (null if Path is empty)\r\n- Parent: Reference to the Microsoft.SqlServer.Management.Smo.Server object\r\n- SqlCredential: The credentials used to connect to the instance\nUse Select-Object * to access all properties.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eStart-DbaTrace -SqlInstance sql2008\nStarts all traces on sql2008\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eStart-DbaTrace -SqlInstance sql2008 -Id 1\nStarts all trace with ID 1 on sql2008\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaTrace -SqlInstance sql2008 | Out-GridView -PassThru | Start-DbaTrace\nStarts selected traces on sql2008", "Description": "Starts SQL Server traces that have been defined but are not currently running. This function activates traces by setting their status to 1 using sp_trace_setstatus, allowing you to begin collecting trace data for performance monitoring, auditing, or troubleshooting. The default trace cannot be started with this function - use Set-DbaSpConfigure to enable it instead.", "Links": "https://dbatools.io/Start-DbaTrace", "Synopsis": "Starts existing SQL Server traces that are currently stopped", "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", "", "" ], [ "Id", "Specifies the numeric IDs of specific traces to start. When omitted, all stopped traces on the instance will be started.\r\nUse this when you need to start only particular traces rather than all available stopped traces.", "", false, "false", "", "" ], [ "InputObject", "Accepts trace objects from the pipeline, typically from Get-DbaTrace. This allows you to filter traces first, then start only the selected ones.\r\nUse this parameter when piping trace objects or when you have trace objects from a previous Get-DbaTrace 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", "" ], [ "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": "Start-DbaXESession", "Name": "Start-DbaXESession", "Author": "Doug Meyers", "Syntax": "Start-DbaXESession [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] -Session \u003cObject[]\u003e [-StartAt \u003cDateTime\u003e] [-StopAt \u003cDateTime\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nStart-DbaXESession [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-StartAt \u003cDateTime\u003e] [-StopAt \u003cDateTime\u003e] -AllSessions [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nStart-DbaXESession [-StartAt \u003cDateTime\u003e] [-StopAt \u003cDateTime\u003e] -InputObject \u003cSession[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.XEvent.Session\nReturns one Session object for each Extended Events session that was started or would be started (if -WhatIf is specified).\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 Extended Events session\r\n- Status: Current session status - either \"Running\" or \"Stopped\"\r\n- StartTime: DateTime when the session was started (null if stopped)\r\n- AutoStart: Boolean indicating if the session starts automatically when SQL Server starts\r\n- State: SMO object state (Existing, Creating, Pending, etc.)\r\n- Targets: Collection of target objects configured for this session\r\n- TargetFile: Array of resolved file paths for all event_file targets (includes UNC paths for network access)\r\n- Events: Collection of Extended Events configured in this session\r\n- MaxMemory: Maximum memory allocation for the session in KB\r\n- MaxEventSize: Maximum event size the session will capture in KB\nAdditional properties added as NoteProperties:\r\n- Session: The session name (alias for Name property)\r\n- RemoteTargetFile: Array of UNC paths for all target files (for remote file access)\r\n- Parent: Reference to the parent Microsoft.SqlServer.Management.Smo.Server object\r\n- Store: Reference to the Microsoft.SqlServer.Management.XEvent.XEStore object\nWhen -StartAt is specified, jobs are created but the session objects are returned immediately without waiting for scheduled execution.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eStart-DbaXESession -SqlInstance sqlserver2012 -AllSessions\nStarts all Extended Event Session on the sqlserver2014 instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eStart-DbaXESession -SqlInstance sqlserver2012 -Session xesession1,xesession2\nStarts the xesession1 and xesession2 Extended Event sessions.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eStart-DbaXESession -SqlInstance sqlserver2012 -Session xesession1,xesession2 -StopAt (Get-Date).AddMinutes(30)\nStarts the xesession1 and xesession2 Extended Event sessions and stops them in 30 minutes.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eStart-DbaXESession -SqlInstance sqlserver2012 -Session AlwaysOn_health -StartAt (Get-Date).AddMinutes(1)\nStarts the AlwaysOn_health Extended Event sessions in 1 minute. The command will return immediately.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaXESession -SqlInstance sqlserver2012 -Session xesession1 | Start-DbaXESession\nStarts the sessions returned from the Get-DbaXESession function.", "Description": "Activates Extended Events sessions that have been created but are not currently running. Extended Events sessions are SQL Server\u0027s lightweight monitoring framework used for troubleshooting performance issues, security auditing, and capturing specific database activity patterns.\n\nThe function can start individual sessions by name, all user-created sessions at once, or sessions scheduled to start and stop at specific times. When using -AllSessions, it automatically excludes built-in system sessions (AlwaysOn_health, system_health, telemetry_xevents) so you don\u0027t accidentally interfere with SQL Server\u0027s internal monitoring.\n\nFor scheduled operations, the function creates temporary SQL Agent jobs that execute at the specified times and then delete themselves. This is particularly useful for capturing data during specific time windows or off-hours troubleshooting sessions.", "Links": "https://dbatools.io/Start-DbaXESession", "Synopsis": "Starts Extended Events sessions on SQL Server instances for monitoring and troubleshooting.", "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.", "", 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", "", "" ], [ "Session", "Specifies the names of specific Extended Events sessions to start. Accepts multiple session names as an array.\r\nUse this when you need to start only certain sessions rather than all user-created sessions on the instance.", "Sessions", true, "false", "", "" ], [ "StartAt", "Schedules the Extended Events sessions to start at a specific date and time using a temporary SQL Agent job.\r\nThe command returns immediately while the job handles starting sessions at the scheduled time, useful for capturing activity during specific time windows.", "", false, "false", "", "" ], [ "StopAt", "Schedules the Extended Events sessions to stop at a specific date and time using a temporary SQL Agent job.\r\nUse this with StartAt or on already running sessions to create time-bounded monitoring windows for troubleshooting specific issues.", "", false, "false", "", "" ], [ "AllSessions", "Starts all user-created Extended Events sessions on the instance while excluding system sessions (AlwaysOn_health, system_health, telemetry_xevents).\r\nUse this when you want to activate all custom monitoring sessions without interfering with SQL Server\u0027s built-in diagnostics.", "", true, "false", "False", "" ], [ "InputObject", "Accepts Extended Events session objects from Get-DbaXESession for pipeline operations.\r\nUse this when you need to filter sessions with Get-DbaXESession first, then start only the matching sessions.", "", 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", "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": [ "Job", "Agent" ], "CommandName": "Stop-DbaAgentJob", "Name": "Stop-DbaAgentJob", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Stop-DbaAgentJob [-SqlCredential \u003cPSCredential\u003e] [-Job \u003cString[]\u003e] [-ExcludeJob \u003cString[]\u003e] [-Wait] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nStop-DbaAgentJob -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Job \u003cString[]\u003e] [-ExcludeJob \u003cString[]\u003e] [-Wait] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nStop-DbaAgentJob [-SqlCredential \u003cPSCredential\u003e] [-Job \u003cString[]\u003e] [-ExcludeJob \u003cString[]\u003e] -InputObject \u003cJob[]\u003e [-Wait] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Agent.Job\nReturns one SMO Job object for each job that was stopped. The object represents the job after the stop operation has been initiated (or completed if -Wait is specified).\nDefault display properties (via SMO Agent.Job):\r\n- Name: The name of the SQL Server Agent job\r\n- Enabled: Boolean indicating if the job is enabled\r\n- CurrentRunStatus: The current execution status of the job (Idle, Executing, etc.)\r\n- LastRunOutcome: The outcome of the last job execution (Succeeded, Failed, Retry, Canceled, etc.)\r\n- LastRunDate: DateTime of the most recent job execution\r\n- NextRunDate: DateTime of the next scheduled job execution\r\n- OwnerLoginName: The login name of the job owner\nAll SMO Job object properties are accessible using Select-Object *. See Microsoft SQL Server Management Objects (SMO) documentation for the complete property list.\nNote: When -Wait is specified, the function waits until CurrentRunStatus becomes Idle before returning. Without -Wait, the function returns immediately after initiating the stop operation, and \r\nCurrentRunStatus may still show Executing.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eStop-DbaAgentJob -SqlInstance localhost\nStops all running SQL Agent Jobs on the local SQL Server instance\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgentJob -SqlInstance sql2016 -Job cdc.DBWithCDC_capture | Stop-DbaAgentJob\nStops the cdc.DBWithCDC_capture SQL Agent Job on sql2016\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eStop-DbaAgentJob -SqlInstance sql2016 -Job cdc.DBWithCDC_capture\nStops the cdc.DBWithCDC_capture SQL Agent Job on sql2016", "Description": "Stops currently executing SQL Server Agent jobs and returns the job objects for verification after the stop attempt.\nPerfect for halting runaway jobs during maintenance windows, stopping jobs that are causing blocking or performance issues, or clearing job queues before scheduled operations.\nThe function automatically skips jobs that are already idle and can optionally wait until jobs have completely finished stopping before returning results.\nWorks with individual job names, exclusion filters, or accepts piped job objects from Get-DbaAgentJob and other dbatools commands.", "Links": "https://dbatools.io/Stop-DbaAgentJob", "Synopsis": "Stops running SQL Server Agent jobs by calling their Stop() method.", "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", "", "" ], [ "Job", "Specifies which SQL Agent jobs to stop by name. Accepts exact job names from the target instance.\r\nUse this when you need to stop specific jobs instead of all running jobs. If unspecified, all currently running jobs will be processed.", "", false, "false", "", "" ], [ "ExcludeJob", "Specifies SQL Agent job names to exclude from the stop operation. Accepts exact job names from the target instance.\r\nUse this when you want to stop most jobs but preserve critical ones like backup jobs, monitoring jobs, or maintenance routines during troubleshooting.", "", false, "false", "", "" ], [ "InputObject", "Accepts SQL Agent job objects from pipeline operations, typically from Get-DbaAgentJob or other dbatools commands.\r\nThis allows you to filter jobs using complex criteria upstream and then pipe the results directly to Stop-DbaAgentJob for processing.", "", true, "true (ByValue)", "", "" ], [ "Wait", "Waits for each job to completely finish stopping before returning results. Without this switch, the function returns immediately after sending the stop command.\r\nUse this when you need to ensure jobs have fully terminated before proceeding with subsequent operations like maintenance or troubleshooting steps.", "", 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": [ "Certificate", "Security" ], "CommandName": "Stop-DbaDbEncryption", "Name": "Stop-DbaDbEncryption", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Stop-DbaDbEncryption [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Parallel] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database processed, with output varying based on encryption status and processing mode.\nDefault properties (sequential mode without -Parallel):\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\r\n- EncryptionEnabled: Boolean indicating whether encryption is enabled after the operation\nWhen -Parallel is specified, additional properties are included:\r\n- Status: The operation result (Success, NotEncrypted, or Failed)\r\n- Error: Error message if the operation failed; null on success", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eStop-DbaDbEncryption -SqlInstance sql01\nRemoves this does that\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eStop-DbaDbEncryption -SqlInstance sql01 -Confirm:$false\nDisables TDE on all user databases on sql01 without prompting for confirmation.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eStop-DbaDbEncryption -SqlInstance sql01, sql02 -Parallel -Confirm:$false\nDisables TDE on all user databases across multiple instances using parallel processing for improved performance", "Description": "Disables Transparent Data Encryption (TDE) on all user databases within a SQL Server instance by calling Disable-DbaDbEncryption for each encrypted database found. This function automatically excludes system databases (master, model, tempdb, msdb, resource) and only processes databases that currently have encryption enabled.\n\nThis is commonly used during instance decommissioning, migration scenarios where TDE is not required in the target environment, or when standardizing security configurations across multiple databases. The function provides a convenient way to decrypt multiple databases at once rather than handling each database individually.\n\nEach database is fully decrypted and the Database Encryption Key (DEK) is dropped to complete the TDE removal process. Certificates and master keys remain untouched and available for other purposes.", "Links": "https://dbatools.io/Stop-DbaDbEncryption", "Synopsis": "Disables Transparent Data Encryption (TDE) on all user databases across a SQL Server instance", "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", "", "" ], [ "Parallel", "Enables parallel processing of databases using runspace pools with 1-10 concurrent threads.\r\nUse this when disabling encryption on multiple databases to improve performance.\r\nWithout this switch, databases are processed sequentially.", "", 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": "Endpoint", "CommandName": "Stop-DbaEndpoint", "Name": "Stop-DbaEndpoint", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Stop-DbaEndpoint [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Endpoint] \u003cString[]\u003e] [-AllEndpoints] [[-InputObject] \u003cEndpoint[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Endpoint\nReturns the endpoint object(s) after they have been successfully stopped. One object is returned per endpoint that was stopped.\nProperties include:\r\n- Name: The name of the endpoint\r\n- EndpointType: Type of endpoint (ServiceBroker, DatabaseMirroring, TSQL_DEFAULT_TCP, TSQL_DEFAULT_HTTP, or custom application)\r\n- ProtocolType: The protocol used by the endpoint\r\n- State: Current state of the endpoint (Stopped, Started, or Disabled)\r\n- Parent: Reference to the parent server or database object\r\n- Protocol: Detailed protocol configuration object\r\n- Payload: Endpoint payload and payload type configuration\nAll properties from the base SMO Endpoint object are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eStop-DbaEndpoint -SqlInstance sql2017a -AllEndpoints\nStops all endpoints on the sqlserver2014 instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eStop-DbaEndpoint -SqlInstance sql2017a -Endpoint endpoint1,endpoint2\nStops the endpoint1 and endpoint2 endpoints.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-Endpoint -SqlInstance sql2017a -Endpoint endpoint1 | Stop-DbaEndpoint\nStops the endpoints returned from the Get-Endpoint command.", "Description": "Stops specific or all SQL Server endpoints on target instances. Endpoints are communication channels that SQL Server uses for features like Service Broker messaging, Database Mirroring, Availability Groups, and custom applications. You might need to stop endpoints during maintenance windows, troubleshooting connectivity issues, or when decommissioning specific services. This command safely stops the endpoints without dropping them, so they can be restarted later with Start-DbaEndpoint.", "Links": "https://dbatools.io/Stop-DbaEndpoint", "Synopsis": "Stops SQL Server communication endpoints like Service Broker, Database Mirroring, or custom TCP endpoints.", "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", "", "" ], [ "Endpoint", "Specifies the names of specific endpoints to stop. Accepts multiple endpoint names as an array.\r\nUse this when you need to stop only certain endpoints while leaving others running, such as stopping a Service Broker endpoint for maintenance while keeping Database Mirroring endpoints active.", "", false, "false", "", "" ], [ "AllEndpoints", "Stops all endpoints on the specified SQL Server instance. Required when using SqlInstance parameter if Endpoint is not specified.\r\nUse this during full maintenance windows or when you need to completely disable all endpoint communication for troubleshooting network connectivity issues.", "", false, "false", "False", "" ], [ "InputObject", "Accepts endpoint objects from Get-DbaEndpoint for pipeline operations. Allows filtering and processing endpoints before stopping them.\r\nUse this for complex scenarios where you need to filter endpoints based on their properties before stopping 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", "" ], [ "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", "Process" ], "CommandName": "Stop-DbaExternalProcess", "Name": "Stop-DbaExternalProcess", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Stop-DbaExternalProcess [-ComputerName] \u003cDbaInstanceParameter\u003e [[-Credential] \u003cPSCredential\u003e] [[-ProcessId] \u003cInt32\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per successfully stopped external process with the following properties:\r\n- ComputerName: The name of the computer where the process was terminated\r\n- ProcessId: The Windows process ID that was stopped (integer)\r\n- Name: The process name/executable name of the terminated process\r\n- Status: The status of the operation; always \"Stopped\" when successful", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaExternalProcess -ComputerName SQL01 | Stop-DbaExternalProcess\nKills all OS processes created by SQL Server on SQL01\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaExternalProcess -ComputerName SQL01 | Where-Object Name -eq \"cmd.exe\" | Stop-DbaExternalProcess\nKills all cmd.exe processes created by SQL Server on SQL01", "Description": "Terminates external processes that were created by SQL Server, such as those spawned by xp_cmdshell, BCP operations, SSIS packages, or external script executions. This function is designed to work with the output from Get-DbaExternalProcess to resolve specific performance issues.\n\nThe primary use case is troubleshooting hung SQL Server sessions that display External Wait Types like WAITFOR_RESULTS or EXTERNAL_SCRIPT_NETWORK_IO. When SQL Server is waiting for an external process to complete and that process becomes unresponsive, this command provides a safe way to terminate the problematic process without affecting the SQL Server service itself.\n\nThis approach is much more targeted than killing SQL Server sessions directly, as it addresses the root cause (the stuck external process) rather than just terminating the database connection that\u0027s waiting for it.\n\nhttps://web.archive.org/web/20201027122300/http://vickyharp.com/2013/12/killing-sessions-with-external-wait-types/", "Links": "https://dbatools.io/Stop-DbaExternalProcess", "Synopsis": "Terminates operating system processes spawned by SQL Server instances", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the Windows server hosting the SQL Server instance where external processes need to be terminated.\r\nUse this when troubleshooting hung sessions with external wait types on remote SQL Server hosts.", "", true, "true (ByPropertyName)", "", "" ], [ "Credential", "Allows you to login to $ComputerName using alternative credentials.", "", false, "true (ByPropertyName)", "", "" ], [ "ProcessId", "Specifies the Windows process ID of the external process spawned by SQL Server that needs to be terminated.\r\nTypically obtained from Get-DbaExternalProcess output when identifying processes causing EXTERNAL_SCRIPT_NETWORK_IO or WAITFOR_RESULTS wait types.", "pid", false, "true (ByPropertyName)", "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", "" ], [ "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": "PerfMon", "CommandName": "Stop-DbaPfDataCollectorSet", "Name": "Stop-DbaPfDataCollectorSet", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Stop-DbaPfDataCollectorSet [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-CollectorSet] \u003cString[]\u003e] [[-InputObject] \u003cObject[]\u003e] [-NoWait] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Objects from Get-DbaPfDataCollectorSet\nReturns Data Collector Set objects from Get-DbaPfDataCollectorSet after successfully stopping each collector set. The output includes the refreshed state of each collector set with updated status \r\ninformation showing it is no longer running.\nProperties returned match those from Get-DbaPfDataCollectorSet, including:\r\n- ComputerName: The computer where the Data Collector Set is configured\r\n- Name: The name of the Data Collector Set that was stopped\r\n- State: The current state (should be \"Stopped\" after successful termination)\r\n- Enabled: Boolean indicating if the collector set is enabled\r\n- DataCollectorSetObject: Reference to the underlying Windows COM object\nNote: If a collector set is not in \"Running\" state, Stop-Function prevents output and returns no objects for that set. Only successfully stopped collectors generate output.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eStop-DbaPfDataCollectorSet\nAttempts to stop all ready Collectors on localhost.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eStop-DbaPfDataCollectorSet -ComputerName sql2017\nAttempts to stop all ready Collectors on localhost.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eStop-DbaPfDataCollectorSet -ComputerName sql2017, sql2016 -Credential ad\\sqldba -CollectorSet \u0027System Correlation\u0027\nStops the \u0027System Correlation\u0027 Collector on sql2017 and sql2016 using alternative credentials.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaPfDataCollectorSet -CollectorSet \u0027System Correlation\u0027 | Stop-DbaPfDataCollectorSet\nStops the \u0027System Correlation\u0027 Collector.", "Description": "Stops running Performance Monitor Data Collector Sets that are actively collecting performance counters for SQL Server monitoring and analysis. This function interacts with the Windows Performance Logs and Alerts (PLA) service to gracefully halt data collection processes. Commonly used to stop baseline data collection after capturing sufficient performance metrics, or to halt monitoring during maintenance windows when counter data isn\u0027t needed.", "Links": "https://dbatools.io/Stop-DbaPfDataCollectorSet", "Synopsis": "Stops Windows Performance Monitor Data Collector Sets used for SQL Server performance monitoring.", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the target computer where Performance Monitor Data Collector Sets are running. Accepts multiple computer names for bulk operations.\r\nUse this when stopping collectors on remote SQL Server instances or when managing multiple servers from a central location.\r\nDefaults to localhost when 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 exact name of the Data Collector Set to stop. Supports multiple collector names for stopping several sets simultaneously.\r\nUse this when you need to stop specific performance monitoring sets without affecting other running collectors on the system.\r\nCommon SQL Server collector sets include \u0027SQL Server Data Collector Set\u0027 and custom monitoring configurations.", "DataCollectorSet", false, "false", "", "" ], [ "InputObject", "Accepts Data Collector Set objects from Get-DbaPfDataCollectorSet via pipeline input.\r\nUse this approach when you need to filter or examine collector properties before stopping them, or when building complex monitoring workflows.", "", false, "true (ByValue)", "", "" ], [ "NoWait", "Returns control immediately after initiating the stop command without waiting for the collector to fully terminate.\r\nUse this in automated scripts where you need to stop multiple collectors quickly or when the stopping process might take time due to large data buffers being flushed.", "", 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": [ "Diagnostic", "Process" ], "CommandName": "Stop-DbaProcess", "Name": "Stop-DbaProcess", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Stop-DbaProcess [-SqlCredential \u003cPSCredential\u003e] [-Spid \u003cInt32[]\u003e] [-ExcludeSpid \u003cInt32[]\u003e] [-Database \u003cString[]\u003e] [-Login \u003cString[]\u003e] [-Hostname \u003cString[]\u003e] [-Program \u003cString[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nStop-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] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nStop-DbaProcess [-SqlCredential \u003cPSCredential\u003e] [-Spid \u003cInt32[]\u003e] [-ExcludeSpid \u003cInt32[]\u003e] [-Database \u003cString[]\u003e] [-Login \u003cString[]\u003e] [-Hostname \u003cString[]\u003e] [-Program \u003cString[]\u003e] -InputObject \u003cObject[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per successfully killed process, confirming the termination action with session details.\nProperties:\r\n- SqlInstance: The name of the SQL Server instance where the process was terminated\r\n- Spid: The session ID (SPID) of the killed process\r\n- Login: The login name associated with the killed process\r\n- Host: The hostname or computer name where the client process originated\r\n- Database: The name of the database the killed session was connected to\r\n- Program: The application or program name that initiated the killed session\r\n- Status: Always set to \"Killed\" to confirm successful process termination\nNote: Processes matching filter criteria but matching ExcludeSpid, or the current session, or processes that fail to kill will not generate output objects.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eStop-DbaProcess -SqlInstance sqlserver2014a -Login base\\ctrlb, sa\nFinds all processes for base\\ctrlb and sa on sqlserver2014a, then kills them. Uses Windows Authentication to login to sqlserver2014a.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eStop-DbaProcess -SqlInstance sqlserver2014a -SqlCredential $credential -Spid 56, 77\nFinds processes for spid 56 and 57, then kills them. Uses alternative (SQL or Windows) credentials to login to sqlserver2014a.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eStop-DbaProcess -SqlInstance sqlserver2014a -Program \u0027Microsoft SQL Server Management Studio\u0027\nFinds processes that were created in Microsoft SQL Server Management Studio, then kills them.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eStop-DbaProcess -SqlInstance sqlserver2014a -Hostname workstationx, server100\nFinds processes that were initiated (computers/clients) workstationx and server 1000, then kills them.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eStop-DbaProcess -SqlInstance sqlserver2014 -Database tempdb -WhatIf\nShows what would happen if the command were executed.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eGet-DbaProcess -SqlInstance sql2016 -Program \u0027dbatools PowerShell module - dbatools.io\u0027 | Stop-DbaProcess\nFinds processes that were created with dbatools, then kills them.", "Description": "Terminates SQL Server processes by targeting specific SPIDs, logins, hostnames, programs, or databases. This is essential for resolving blocking situations, stopping runaway queries that consume resources, or cleaning up abandoned connections from applications or users.\n\nThe function automatically prevents you from killing your own connection session to avoid disconnecting yourself. You can filter processes by multiple criteria and use it alongside Get-DbaProcess to identify problem sessions before terminating them.", "Links": "https://dbatools.io/Stop-DbaProcess", "Synopsis": "Terminates SQL Server processes (SPIDs) to resolve blocking, kill runaway queries, or clean up connections.", "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", "", "" ], [ "Spid", "Targets specific session IDs (SPIDs) for termination. Use this when you know the exact process ID causing problems, typically identified from blocking reports or activity monitors. You can specify \r\nmultiple SPIDs to kill several problem sessions at once.", "", false, "false", "", "" ], [ "ExcludeSpid", "Protects specific session IDs from termination even if they match other filter criteria. Use this to preserve important connections like monitoring tools or critical application sessions when killing \r\nprocesses by login, hostname, or database. This exclusion is applied last, overriding all other matching filters.", "", false, "false", "", "" ], [ "Database", "Kills all active sessions connected to specified databases. Useful when you need to perform exclusive database operations like restores, schema changes, or when preparing for database maintenance. \r\nThis will disconnect all users currently connected to the targeted databases.", "", false, "false", "", "" ], [ "Login", "Terminates all active sessions for specified login names. Use this to disconnect all connections from a specific user account, such as when removing user access or troubleshooting login-specific \r\nissues. Supports multiple logins and accepts both Windows (DOMAIN\\user) and SQL logins.", "", false, "false", "", "" ], [ "Hostname", "Kills all sessions originating from specified client computer names. Useful when a problematic application server or workstation is creating excessive connections or when you need to force disconnect \r\nall sessions from a specific machine. Accepts multiple hostnames including both short names and FQDNs.", "", false, "false", "", "" ], [ "Program", "Terminates sessions based on the client application name. Use this to disconnect all connections from specific applications like SSMS, poorly-behaved ETL tools, or misbehaving custom applications. \r\nCommon program names include \u0027Microsoft SQL Server Management Studio\u0027 and various .NET application names.", "", false, "false", "", "" ], [ "InputObject", "Accepts process objects from Get-DbaProcess through the pipeline. Use this approach to first identify and review problematic sessions before terminating them, providing better control and \r\nverification of which processes will be killed.", "", 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", "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": [ "Service", "Stop" ], "CommandName": "Stop-DbaService", "Name": "Stop-DbaService", "Author": "Kirill Kravtsov (@nvarscar)", "Syntax": "Stop-DbaService [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [-InstanceName \u003cString[]\u003e] [-SqlInstance \u003cDbaInstanceParameter[]\u003e] [-Type \u003cString[]\u003e] [-Timeout \u003cInt32\u003e] [-Credential \u003cPSCredential\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nStop-DbaService [-InstanceName \u003cString[]\u003e] [-Type \u003cString[]\u003e] -InputObject \u003cObject[]\u003e [-Timeout \u003cInt32\u003e] [-Credential \u003cPSCredential\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Wmi.Service\nReturns one service object per service that was stopped, with the following default display properties:\r\n- ComputerName: The name of the computer hosting the SQL Server service\r\n- ServiceName: The Windows service name (e.g., MSSQLSERVER, SQLSERVERAGENT, SSRS)\r\n- InstanceName: The SQL Server instance name associated with the service\r\n- ServiceType: The type of SQL Server service (Engine, Agent, SSRS, SSAS, SSIS, PolyBase, Launchpad, Browser, FullText)\r\n- State: The current state of the service (Running, Stopped, etc.)\r\n- Status: The result of the stop operation (Successful, Failed)\r\n- Message: Detailed status message describing the operation result (success or failure reason)\nAdditional properties available via Select-Object *:\r\n- ServiceAccount: The Windows account running the service\r\n- StartMode: The startup type (Automatic, Manual, Disabled)\r\n- Properties: Collection of additional service properties\r\n- Parent: Reference to the parent computer object\nWhen -Force is used with Engine type services, dependent services (Agent, PolyBase) are automatically stopped first to prevent service dependency conflicts. All dependent services appear in the \r\noutput with their own status information.\nIf no services match the specified parameters, no output is generated.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eStop-DbaService -ComputerName sqlserver2014a\nStops the SQL Server related services on computer sqlserver2014a.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e\u0027sql1\u0027,\u0027sql2\u0027,\u0027sql3\u0027| Get-DbaService | Stop-DbaService\nGets the SQL Server related services on computers sql1, sql2 and sql3 and stops them.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eStop-DbaService -ComputerName sql1,sql2 -Instance MSSQLSERVER\nStops the SQL Server services related to the default instance MSSQLSERVER on computers sql1 and sql2.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eStop-DbaService -ComputerName $MyServers -Type SSRS\nStops the SQL Server related services of type \"SSRS\" (Reporting Services) on computers in the variable MyServers.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eStop-DbaService -ComputerName sql1 -Type Engine -Force\nStops SQL Server database engine services on sql1 forcing dependent SQL Server Agent services to stop as well.", "Description": "Stops SQL Server services including Database Engine, SQL Agent, Reporting Services, Analysis Services, Integration Services, PolyBase, Launchpad, and other components across one or more computers. Automatically handles service dependencies to prevent dependency conflicts during shutdown operations.\n\nParticularly useful for planned maintenance windows, troubleshooting service issues, or preparing servers for patching and reboots. The Force parameter allows stopping dependent services automatically, which is essential when stopping Database Engine services that have SQL Agent dependencies.\n\nSupports targeting specific service types or instances, making it ideal for selective service management in multi-instance environments. Can be combined with Get-DbaService for advanced filtering and bulk operations across entire SQL Server environments.\n\nRequires Local Admin rights on destination computer(s).", "Links": "https://dbatools.io/Stop-DbaService", "Synopsis": "Stops SQL Server-related Windows services with proper dependency handling.", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the target computer(s) containing SQL Server services to stop. Accepts multiple computer names for bulk service management.\r\nUse this when you need to stop SQL Server services across multiple servers during maintenance windows or troubleshooting scenarios.", "cn,host,Server", false, "false", "$env:COMPUTERNAME", "" ], [ "InstanceName", "Targets services belonging to specific SQL Server named instances. Filters results to match only the specified instance names.\r\nEssential in multi-instance environments where you need to stop services for particular instances while leaving others running.", "Instance", false, "false", "", "" ], [ "SqlInstance", "Use a combination of computername and instancename to get the SQL Server related services for specific instances on specific computers.\nParameters ComputerName and InstanceName will be ignored if SqlInstance is used.", "", false, "false", "", "" ], [ "Type", "Filters which SQL Server service types to stop. Valid options: Agent, Browser, Engine, FullText, SSAS, SSIS, SSRS, PolyBase, Launchpad.\r\nUse this when you need to stop specific service types across instances, such as stopping all SQL Agent services for patching while keeping Database Engine services running.", "", false, "false", "", "Agent,Browser,Engine,FullText,SSAS,SSIS,SSRS,PolyBase,Launchpad" ], [ "InputObject", "Accepts service objects directly from Get-DbaService, allowing for advanced filtering and pipeline operations.\r\nUse this approach when you need complex service filtering that goes beyond the built-in ComputerName, InstanceName, and Type parameters.", "ServiceCollection", true, "true (ByValue)", "", "" ], [ "Timeout", "Sets the maximum wait time in seconds for each service stop operation before timing out. Default is 60 seconds, specify 0 to wait indefinitely.\r\nIncrease this value for services that take longer to shut down gracefully, particularly in environments with large databases or heavy workloads.", "", false, "false", "60", "" ], [ "Credential", "Credential object used to connect to the computer as a different user.", "", false, "false", "", "" ], [ "Force", "Automatically stops dependent services when stopping SQL Server Database Engine services. Prevents dependency conflicts that would otherwise block the stop operation.\r\nRequired when stopping Engine services that have dependent SQL Agent services running, as SQL Agent must be stopped first to avoid service dependency errors.", "", 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 cmdlet runs. The cmdlet is not run.", "wi", false, "false", "", "" ], [ "Confirm", "Prompts you for confirmation before running the cmdlet.", "cf", false, "false", "", "" ] ] }, { "Tags": "Trace", "CommandName": "Stop-DbaTrace", "Name": "Stop-DbaTrace", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Stop-DbaTrace [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Id] \u003cInt32[]\u003e] [[-InputObject] \u003cObject[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per trace that was stopped, with the following default display properties:\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- Id: The unique identifier of the trace\r\n- IsRunning: Boolean indicating if the trace is currently running (false after successful stop)\nAdditional properties available via Select-Object *:\r\n- Status: Current status of the trace\r\n- Path: File path where trace events are logged\r\n- MaxSize: Maximum size of the trace file in MB\r\n- StopTime: DateTime when the trace will stop\r\n- MaxFiles: Maximum number of trace files for rollover\r\n- IsRowset: Boolean indicating if trace data is in rowset format\r\n- IsRollover: Boolean indicating if trace file rollover is enabled\r\n- IsShutdown: Boolean indicating if trace stops on shutdown\r\n- IsDefault: Boolean indicating if this is the default trace\r\n- BufferCount: Number of buffers in memory\r\n- BufferSize: Size of each buffer in KB\r\n- FilePosition: Current position in the trace file\r\n- ReaderSpid: SPID of the trace reader process\r\n- StartTime: DateTime when the trace started\r\n- LastEventTime: DateTime of the last event logged\r\n- EventCount: Total number of events logged\r\n- DroppedEventCount: Number of events dropped due to buffer overflow\r\n- Parent: Reference to the parent SQL Server object", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eStop-DbaTrace -SqlInstance sql2008\nStops all traces on sql2008\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eStop-DbaTrace -SqlInstance sql2008 -Id 1\nStops all trace with ID 1 on sql2008\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaTrace -SqlInstance sql2008 | Out-GridView -PassThru | Stop-DbaTrace\nStops selected traces on sql2008", "Description": "Stops one or more running SQL Server traces by calling sp_trace_setstatus with a status of 0. This is useful when you need to stop traces created for troubleshooting, performance monitoring, or security auditing that are no longer needed or are impacting server performance. The function prevents you from accidentally stopping the default trace and provides guidance to use Set-DbaSpConfigure if you need to disable it. Works with trace IDs or accepts piped input from Get-DbaTrace for selective stopping of traces.", "Links": "https://dbatools.io/Stop-DbaTrace", "Synopsis": "Stops running SQL Server traces using sp_trace_setstatus", "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", "", "" ], [ "Id", "Specifies the trace IDs to stop. Accepts one or more trace ID numbers as integers.\r\nUse this when you need to stop specific traces instead of all running traces on the instance.", "", false, "false", "", "" ], [ "InputObject", "Accepts trace objects from the pipeline, typically from Get-DbaTrace output.\r\nThis enables selective stopping of traces by piping Get-DbaTrace results through filtering commands like Out-GridView or Where-Object.", "", 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": [ "ExtendedEvent", "XE", "XEvent" ], "CommandName": "Stop-DbaXESession", "Name": "Stop-DbaXESession", "Author": "Doug Meyers", "Syntax": "Stop-DbaXESession [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] -Session \u003cObject[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nStop-DbaXESession [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] -AllSessions [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nStop-DbaXESession -InputObject \u003cSession[]\u003e [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.XEvent.Session\nReturns one Extended Events session object for each session that was stopped. The session objects reflect the stopped state after the command completes.\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- Name: The name of the Extended Events session\r\n- State: The current state of the session (Created, Started, Stopped, or Altered)\r\n- IsRunning: Boolean indicating if the session is currently running (false after stopping)\r\n- StartTime: DateTime when the session was started (null if not currently running)\r\n- DefinitionFileLocation: Path to the XML definition file for the session\r\n- MaxMemory: Maximum memory in MB allocated to the session\r\n- EventRetentionMode: How events are retained (AllowSingleEventLoss, AllowMultipleEventLoss, NoEventLoss, or DropOnFullBuffer)\nAdditional properties available on the SMO Session object (via Select-Object *):\r\n- Urn: The Uniform Resource Name for the session object\r\n- Properties: Collection of session property objects\r\n- TargetCount: Number of targets associated with the session\r\n- EventCount: Number of events collected by the session\r\n- MaxDispatchLatency: Maximum latency in seconds for event dispatch\r\n- SuspendedEventCount: Number of currently suspended events", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eStop-DbaXESession -SqlInstance sqlserver2012 -AllSessions\nStops all Extended Event Session on the sqlserver2014 instance.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eStop-DbaXESession -SqlInstance sqlserver2012 -Session xesession1,xesession2\nStops the xesession1 and xesession2 Extended Event sessions.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaXESession -SqlInstance sqlserver2012 -Session xesession1 | Stop-DbaXESession\nStops the sessions returned from the Get-DbaXESession function.", "Description": "Stops active Extended Events sessions that are currently collecting diagnostic data or monitoring SQL Server activity. This function helps DBAs manage resource usage by ending sessions that may be consuming disk space, memory, or CPU cycles. You can stop specific sessions by name, stop all user-created sessions while preserving critical system sessions, or use pipeline input from Get-DbaXESession. The function safely checks if sessions are running before attempting to stop them and provides clear feedback about the operation results.", "Links": "https://dbatools.io/Stop-DbaXESession", "Synopsis": "Stops running Extended Events sessions on 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 2008 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", "", "" ], [ "Session", "Specifies the names of specific Extended Events sessions to stop by name. Accepts session names as strings or arrays for multiple sessions.\r\nUse this when you need to stop particular monitoring sessions while leaving others running, such as stopping a performance troubleshooting session while keeping system health sessions active.", "Sessions", true, "false", "", "" ], [ "AllSessions", "Stops all user-created Extended Events sessions while preserving critical system sessions (AlwaysOn_health, system_health, telemetry_xevents).\r\nUse this when performing maintenance, reducing resource usage, or cleaning up after troubleshooting activities without disrupting essential SQL Server monitoring.", "", true, "false", "False", "" ], [ "InputObject", "Accepts Extended Events session objects from Get-DbaXESession through the pipeline for stopping sessions.\r\nUse this approach when you need to filter sessions based on properties like status, start time, or event counts before stopping them, enabling more sophisticated session management workflows.", "", 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", "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": "Suspend-DbaAgDbDataMovement", "Name": "Suspend-DbaAgDbDataMovement", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Suspend-DbaAgDbDataMovement [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-AvailabilityGroup] \u003cString\u003e] [[-Database] \u003cString[]\u003e] [[-InputObject] \u003cAvailabilityDatabase[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.AvailabilityDatabase\nReturns one AvailabilityDatabase object for each database where data movement was suspended. When suspending data movement for multiple databases, one object is returned per database.\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- 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 (true after suspension completes)\nAdditional properties available on the SMO AvailabilityDatabase object (via Select-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- LastCommitTime: Timestamp of last committed transaction\r\n- LogSendQueue: Size of log send queue in KB\r\n- RedoRate: Rate of redo operations (bytes/sec)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSuspend-DbaAgDbDataMovement -SqlInstance sql2017a -AvailabilityGroup ag1 -Database db1, db2\nSuspends data movement on db1 and db2 to ag1 on sql2017a. Prompts for confirmation.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAgDatabase -SqlInstance sql2017a, sql2019 | Out-GridView -Passthru | Suspend-DbaAgDbDataMovement -Confirm:$false\nSuspends data movement on the selected availability group databases. Does not prompt for confirmation.", "Description": "Temporarily halts data movement between primary and secondary replicas for specified availability group databases. This stops transaction log records from being sent to secondary replicas, which is useful during maintenance windows, troubleshooting synchronization issues, or when preparing for manual failovers. While suspended, the secondary databases will fall behind the primary and cannot be failed over to until data movement is resumed.", "Links": "https://dbatools.io/Suspend-DbaAgDbDataMovement", "Synopsis": "Suspends data synchronization for availability group databases to halt replication between 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 the availability group containing the databases to suspend. Required when using SqlInstance parameter.\r\nUse this to target databases within a specific AG when multiple availability groups exist on the instance.", "", false, "false", "", "" ], [ "Database", "Specifies which availability group databases to suspend data movement for. Accepts multiple database names.\r\nUse this when you need to halt synchronization for specific databases while leaving other AG databases running normally.", "", false, "false", "", "" ], [ "InputObject", "Accepts availability group database objects piped from Get-DbaAgDatabase or other dbatools AG commands.\r\nUse this for pipeline operations when you want to filter and select specific AG databases before suspending data movement.", "", 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": "Sync-DbaAvailabilityGroup", "Name": "Sync-DbaAvailabilityGroup", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Sync-DbaAvailabilityGroup [[-Primary] \u003cDbaInstanceParameter\u003e] [[-PrimarySqlCredential] \u003cPSCredential\u003e] [[-Secondary] \u003cDbaInstanceParameter[]\u003e] [[-SecondarySqlCredential] \u003cPSCredential\u003e] [[-AvailabilityGroup] \u003cString\u003e] [[-Exclude] \u003cString[]\u003e] [[-Login] \u003cString[]\u003e] [[-ExcludeLogin] \u003cString[]\u003e] [[-Job] \u003cString[]\u003e] [[-ExcludeJob] \u003cString[]\u003e] [-DisableJobOnDestination] [[-InputObject] \u003cAvailabilityGroup[]\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "None\nThis function does not return output objects to the user. It performs synchronization operations by calling underlying Copy-Dba* and Sync-Dba* commands to synchronize server-level objects from the \r\nprimary to secondary replicas.\nThe underlying sync commands (Copy-DbaSpConfigure, Copy-DbaLogin, Copy-DbaCustomError, Copy-DbaCredential, Copy-DbaDbMail, Copy-DbaLinkedServer, Copy-DbaInstanceTrigger, Copy-DbaAgentJobCategory, \r\nCopy-DbaAgentOperator, Copy-DbaAgentAlert, Copy-DbaAgentProxy, Copy-DbaAgentSchedule, Copy-DbaAgentJob, and Sync-DbaLoginPermission) may produce output when called directly with the underlying \r\nCopy-Dba* and Sync-Dba* commands.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSync-DbaAvailabilityGroup -Primary sql2016a -AvailabilityGroup db3\nSyncs the following on all replicas found in the db3 AG:\r\nSpConfigure, CustomErrors, Credentials, DatabaseMail, LinkedServers\r\nLogins, LoginPermissions, SystemTriggers, DatabaseOwner, AgentCategory,\r\nAgentOperator, AgentAlert, AgentProxy, AgentSchedule, AgentJob\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sql2016a | Sync-DbaAvailabilityGroup -ExcludeType LoginPermissions, LinkedServers -ExcludeLogin login1, login2 -Job job1, job2\nSyncs the following on all replicas found in all AGs on the specified instance:\r\nSpConfigure, CustomErrors, Credentials, DatabaseMail, Logins,\r\nSystemTriggers, DatabaseOwner, AgentCategory, AgentOperator\r\nAgentAlert, AgentProxy, AgentSchedule, AgentJob.\nCopies all logins except for login1 and login2 and only syncs job1 and job2\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sql2016a | Sync-DbaAvailabilityGroup -WhatIf\nShows what would happen if the command were to run but doesn\u0027t actually perform the action.", "Description": "Copies server-level objects from the primary replica to all secondary replicas in an availability group. Availability groups only synchronize databases, not the server-level dependencies that applications need to function properly after failover.\n\nThis command ensures that logins, SQL Agent jobs, linked servers, and other critical server objects exist on all replicas so your applications work seamlessly regardless of which replica becomes primary. By default, it synchronizes these object types:\n\nSpConfigure\nCustomErrors\nCredentials\nDatabaseMail\nLinkedServers\nLogins\nLoginPermissions\nSystemTriggers\nDatabaseOwner\nAgentCategory\nAgentOperator\nAgentAlert\nAgentProxy\nAgentSchedule\nAgentJob\n\nAny of these object types can be excluded using the -Exclude parameter. For granular control over specific objects (like excluding individual jobs or logins), use the -ExcludeJob, -ExcludeLogin parameters or the underlying Copy-Dba* commands directly.\n\nThe command copies ALL objects of each enabled type - it doesn\u0027t filter based on which objects are actually used by the availability group databases. Use the exclusion parameters to limit scope when needed.", "Links": "https://dbatools.io/Sync-DbaAvailabilityGroup", "Synopsis": "Synchronizes server-level objects from primary to secondary replicas in availability groups", "Availability": "Windows, Linux, macOS", "Params": [ [ "Primary", "The primary replica SQL Server instance for the availability group. This is the source server from which all server-level objects will be copied.\r\nRequired when not using InputObject parameter. Server version must be SQL Server 2012 or higher.", "", false, "false", "", "" ], [ "PrimarySqlCredential", "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", "", "" ], [ "Secondary", "The secondary replica SQL Server instances where server-level objects will be copied to. Can specify multiple instances.\r\nIf not specified, the function will automatically discover all secondary replicas in the availability group. Server version must be SQL Server 2012 or higher.", "", false, "false", "", "" ], [ "SecondarySqlCredential", "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", "The name of the specific availability group to synchronize server objects for.\r\nWhen specified, the function will identify all replicas in this AG and sync objects from primary to all secondaries.", "", false, "false", "", "" ], [ "Exclude", "Excludes specific object types from being synchronized to avoid conflicts or reduce sync time.\r\nUseful when you need to manually manage certain objects or when some object types cause issues in your environment. Valid values:\nSpConfigure, CustomErrors, Credentials, DatabaseMail, LinkedServers, Logins, LoginPermissions,\r\nSystemTriggers, DatabaseOwner, AgentCategory, AgentOperator, AgentAlert, AgentProxy, AgentSchedule, AgentJob", "ExcludeType", false, "false", "", "AgentCategory,AgentOperator,AgentAlert,AgentProxy,AgentSchedule,AgentJob,Credentials,CustomErrors,DatabaseMail,DatabaseOwner,LinkedServers,Logins,LoginPermissions,SpConfigure,SystemTriggers" ], [ "Login", "Specifies which login accounts to synchronize to secondary replicas. Accepts an array of login names.\r\nUse this when you only need to sync specific service accounts or application logins rather than all logins on the server.", "", false, "false", "", "" ], [ "ExcludeLogin", "Specifies login accounts to skip during synchronization. Accepts an array of login names.\r\nCommonly used to exclude system accounts, sa, or logins that should remain unique per replica for monitoring or maintenance purposes.", "", false, "false", "", "" ], [ "Job", "Specifies which SQL Agent jobs to synchronize to secondary replicas. Accepts an array of job names.\r\nUse this when you only need to sync critical jobs like backup jobs or maintenance tasks rather than all jobs on the server.", "", false, "false", "", "" ], [ "ExcludeJob", "Specifies SQL Agent jobs to skip during synchronization. Accepts an array of job names.\r\nCommonly used to exclude replica-specific jobs like log shipping, local backups, or jobs that should only run on the primary replica.", "", false, "false", "", "" ], [ "DisableJobOnDestination", "Disables all synchronized jobs on secondary replicas after copying them from the primary.\r\nUse this when jobs should only run on the primary replica or when you need to manually control which jobs run on each replica after failover.", "", false, "false", "False", "" ], [ "InputObject", "Accepts availability group objects from Get-DbaAvailabilityGroup for pipeline processing.\r\nUse this to sync multiple availability groups at once or to process specific AGs returned by filtering commands.", "", false, "true (ByValue)", "", "" ], [ "Force", "Drops and recreates existing objects on secondary replicas instead of skipping them.\r\nUse this when you need to update objects that already exist on secondaries or when objects have configuration differences that need to be synchronized.", "", 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", "Password" ], "CommandName": "Sync-DbaLoginPassword", "Name": "Sync-DbaLoginPassword", "Author": "Shawn Melton (@wsmelton), http://www.wsmelton.com", "Syntax": "Sync-DbaLoginPassword [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-InputObject] \u003cObject[]\u003e] [[-Login] \u003cString[]\u003e] [[-ExcludeLogin] \u003cString[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per login password synchronized, whether successful or failed.\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- Login: The name of the login whose password was synced\r\n- Status: The result of the operation - either \"Success\" or \"Failed\"\r\n- Notes: Additional details about the operation; null for successful syncs, error message for failures", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSync-DbaLoginPassword -Source sql2016 -Destination sql2016ag1, sql2016ag2\nSyncs all SQL Server authentication login passwords from sql2016 to sql2016ag1 and sql2016ag2. Windows authentication logins are automatically skipped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSync-DbaLoginPassword -Source sql2016 -Destination sql2016ag1 -Login app_user, reports_user\nSyncs passwords only for the app_user and reports_user logins from sql2016 to sql2016ag1.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSync-DbaLoginPassword -Source sql2016 -Destination sql2016ag1 -ExcludeLogin sa, admin\nSyncs all SQL Server login passwords except for sa and admin accounts from sql2016 to sql2016ag1.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$splatSync = @{\n\u003e\u003e Source = \"sql2016\"\r\n\u003e\u003e Destination = \"sql2016ag1\", \"sql2016ag2\"\r\n\u003e\u003e SourceSqlCredential = $sourceCred\r\n\u003e\u003e DestinationSqlCredential = $destCred\r\n\u003e\u003e EnableException = $true\r\n\u003e\u003e }\r\nPS C:\\\u003e Sync-DbaLoginPassword @splatSync\nSyncs all SQL Server login passwords using SQL Authentication credentials for both source and destination connections. Throws exceptions on errors for easier scripting and automation.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaLogin -SqlInstance sql2016 | Where-Object LoginType -eq \"SqlLogin\" | Sync-DbaLoginPassword -Destination sql2016ag1\nGets all SQL Server authentication logins from sql2016 and syncs their passwords to sql2016ag1 using pipeline input.", "Description": "Syncs SQL Server authentication login passwords from a source to destination instance(s) without requiring knowledge of the actual passwords. Uses the same technique as Microsoft\u0027s sp_help_revlogin by extracting and applying hashed password values.\n\nThis is particularly useful for:\n- Maintaining consistent passwords across Availability Group replicas\n- Migrating logins between instances when users cannot provide their passwords\n- Disaster recovery scenarios where password synchronization is critical\n- Keeping development/test environments synchronized with production passwords\n\nThe function only works with SQL Server authentication logins. Windows authentication logins are automatically skipped since their authentication is handled by Active Directory. The login must already exist on the destination instance(s) - this function only updates passwords, it does not create new logins.", "Links": "https://dbatools.io/Sync-DbaLoginPassword", "Synopsis": "Synchronizes SQL Server login passwords between instances using hashed password values.", "Availability": "Windows, Linux, macOS", "Params": [ [ "Source", "Specifies the source SQL Server instance to read login passwords from. The login password hashes will be extracted from this instance.\r\nYou must have sysadmin access and the server version must be SQL Server 2000 or higher.", "", true, "false", "", "" ], [ "SourceSqlCredential", "Specifies alternative credentials to connect 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 credentials created with Get-Credential. Supports Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated.\r\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Destination", "Specifies the destination SQL Server instance(s) where login passwords will be updated. Accepts multiple instances to sync passwords to several servers simultaneously.\r\nThe logins must already exist on the destination - this function only syncs passwords, not the logins themselves. You must have sysadmin access and the server must be SQL Server 2005 or higher.", "", true, "false", "", "" ], [ "DestinationSqlCredential", "Specifies alternative credentials to connect to the destination SQL Server instance(s). Use this when your current Windows credentials don\u0027t have sysadmin access to the destination server(s).\r\nAccepts PowerShell credentials created with Get-Credential. Supports Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated.\r\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "InputObject", "Specifies login objects from the pipeline to sync passwords for. Accepts login objects from Get-DbaLogin.\r\nWhen using InputObject, only SQL Server authentication logins will be processed - Windows authentication logins are automatically filtered out.\r\nThis parameter enables pipeline scenarios where you can filter logins first and then sync their passwords.", "", false, "true (ByValue)", "", "" ], [ "Login", "Specifies which specific logins to sync passwords for. Use this when you only want to sync passwords for certain accounts rather than all SQL logins.\r\nAccepts multiple login names as an array. Only SQL Server authentication logins will be processed - Windows logins are automatically skipped.", "", false, "false", "", "" ], [ "ExcludeLogin", "Specifies login names to exclude from the password sync process. Use this to skip specific accounts that shouldn\u0027t have their passwords synced.\r\nCommonly used to exclude service accounts, application accounts, or logins with environment-specific passwords that should remain different between servers.", "", 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", "Login" ], "CommandName": "Sync-DbaLoginPermission", "Name": "Sync-DbaLoginPermission", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Sync-DbaLoginPermission [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter[]\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-Login] \u003cString[]\u003e] [[-ExcludeLogin] \u003cString[]\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject with TypeName MigrationObject\nReturns one object per login per destination server showing the result of the permission sync operation. Objects are output immediately as each login\u0027s permissions are synced, not collected at the \r\nend.\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- Name: The login name that was synced\r\n- Type: The operation type (always \"Login Permissions\")\r\n- Status: Result of the sync operation (Successful or Failed)\r\n- Notes: Error message details if Status is Failed, null if Successful\r\n- DateTime: DbaDateTime object representing when the sync was attempted", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eSync-DbaLoginPermission -Source sqlserver2014a -Destination sqlcluster\nSyncs only SQL Server login permissions, roles, etc. Does not add or drop logins or users. To copy logins and their permissions, use Copy-SqlLogin.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eSync-DbaLoginPermission -Source sqlserver2014a -Destination sqlcluster -Exclude realcajun -SourceSqlCredential $scred -DestinationSqlCredential $dcred\nCopies all login permissions except for realcajun using SQL Authentication to connect to each server. If a login already exists on the destination, the permissions will not be migrated.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eSync-DbaLoginPermission -Source sqlserver2014a -Destination sqlcluster -Login realcajun, netnerds\nCopies permissions ONLY for logins netnerds and realcajun.", "Description": "Syncs comprehensive login security settings from a source to destination SQL Server instance, ensuring logins have consistent permissions across environments. This function only modifies permissions for existing logins - it will not create or drop logins themselves.\n\nThe sync process handles server roles (sysadmin, bulkadmin, etc.), server-level permissions (Connect SQL, View any database, etc.), SQL Agent job ownership, credential mappings, database user mappings, database roles (db_owner, db_datareader, etc.), and database-level permissions. This is particularly useful for maintaining consistent security configurations across development, staging, and production environments, or when rebuilding servers and needing to restore login permissions without recreating the logins.\n\nIf a login exists on the source but not the destination, that login is skipped entirely. The function also protects against syncing permissions for system logins, host-based logins, and the currently connected login to prevent accidental lockouts.", "Links": "https://dbatools.io/Sync-DbaLoginPermission", "Synopsis": "Synchronizes login permissions and role memberships between SQL Server instances.", "Availability": "Windows, Linux, macOS", "Params": [ [ "Source", "Specifies the source SQL Server instance containing the login permissions to copy from. The login permissions, server roles, database roles, and security settings will be read from this instance.\r\nYou must have sysadmin access and the server version must be SQL Server 2000 or higher.", "", true, "true (ByValue)", "", "" ], [ "SourceSqlCredential", "Specifies alternative credentials to connect to the source SQL Server instance. Use this when your current Windows credentials don\u0027t have access to the source server.\r\nAccepts PowerShell credentials created with Get-Credential. Supports Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated.\r\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Destination", "Specifies the destination SQL Server instance(s) where login permissions will be applied. Accepts multiple instances to sync permissions to several servers simultaneously.\r\nThe logins must already exist on the destination - this function only syncs permissions, not the logins themselves. You must have sysadmin access and the server must be SQL Server 2000 or higher.", "", true, "false", "", "" ], [ "DestinationSqlCredential", "Specifies alternative credentials to connect to the destination SQL Server instance(s). Use this when your current Windows credentials don\u0027t have access to the destination server(s).\r\nAccepts PowerShell credentials created with Get-Credential. Supports Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated.\r\nFor MFA support, please use Connect-DbaInstance.", "", false, "false", "", "" ], [ "Login", "Specifies which specific logins to sync permissions for. Use this when you only want to sync permissions for certain accounts rather than all logins.\r\nAccepts multiple login names as an array. If not specified, permissions for all logins on the source server will be synced (excluding system and host-based logins).", "", false, "false", "", "" ], [ "ExcludeLogin", "Specifies login names to exclude from the permission sync process. Use this to skip specific accounts that shouldn\u0027t have their permissions synced.\r\nCommonly used to exclude service accounts, shared accounts, or logins with environment-specific permissions that should remain different between servers.", "", 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": [ "Agent", "Job", "Owner" ], "CommandName": "Test-DbaAgentJobOwner", "Name": "Test-DbaAgentJobOwner", "Author": "Michael Fal (@Mike_Fal), mikefal.net", "Syntax": "Test-DbaAgentJobOwner [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Job] \u003cObject[]\u003e] [[-ExcludeJob] \u003cObject[]\u003e] [[-Login] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Agent job found on the instance. By default, only jobs where the current owner does not match the target owner are returned. When -Job is specified, all matching jobs are \r\nreturned regardless of ownership status.\nProperties:\r\n- Server: The name of the SQL Server instance\r\n- Job: The name of the SQL Agent job\r\n- JobType: Type of job (Remote for remote jobs, LocalJob, or other job type values)\r\n- CurrentOwner: The login name that currently owns this job\r\n- TargetOwner: The expected login name that should own this job (default \u0027sa\u0027 or specified via -Login parameter)\r\n- OwnerMatch: Boolean indicating if the current owner matches the target owner", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaAgentJobOwner -SqlInstance localhost\nReturns all SQL Agent Jobs where the owner does not match \u0027sa\u0027.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaAgentJobOwner -SqlInstance localhost -ExcludeJob \u0027syspolicy_purge_history\u0027\nReturns SQL Agent Jobs except for the syspolicy_purge_history job\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaAgentJobOwner -SqlInstance localhost -Login DOMAIN\\account\nReturns all SQL Agent Jobs where the owner does not match DOMAIN\\account. Note\r\nthat Login must be a valid security principal that exists on the target server.", "Description": "This function audits SQL Agent job ownership by comparing each job\u0027s current owner against a target login, typically \u0027sa\u0027 or another sysadmin account. Jobs owned by inappropriate accounts can pose security risks, especially if those accounts are disabled, deleted, or have reduced permissions. By default, it checks against the \u0027sa\u0027 account (or renamed sysadmin), but you can specify any valid login for your organization\u0027s security standards. Returns only jobs that don\u0027t match the expected ownership, making it easy to identify compliance violations that need remediation.\n\nBest practice reference: https://www.itprotoday.com/sql-server-tip-assign-ownership-jobs-sysadmin-account", "Links": "https://dbatools.io/Test-DbaAgentJobOwner", "Synopsis": "Identifies SQL Agent jobs with incorrect ownership for security compliance auditing", "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", "", "" ], [ "Job", "Specifies specific SQL Agent jobs to check for ownership compliance. When provided, only these named jobs are evaluated against the target owner.\r\nUse this to focus on critical jobs or when troubleshooting specific ownership issues. If omitted, all jobs on the instance are processed.", "Jobs", false, "false", "", "" ], [ "ExcludeJob", "Excludes specific SQL Agent jobs from the ownership compliance check. Useful for skipping system jobs or jobs that legitimately require different owners.\r\nCommonly used to exclude jobs like \u0027syspolicy_purge_history\u0027 or maintenance jobs that run under service accounts by design.", "", false, "false", "", "" ], [ "Login", "Specifies the target login that should own SQL Agent jobs for security compliance. Must be an existing login on the server, cannot be a Windows Group.\r\nDefaults to \u0027sa\u0027 (or the renamed sysadmin account). Common alternatives include service accounts or dedicated job owner logins required by your organization\u0027s security policies.", "TargetLogin", 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": "Test-DbaAgSpn", "Name": "Test-DbaAgSpn", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Test-DbaAgSpn [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [[-AvailabilityGroup] \u003cString[]\u003e] [[-Listener] \u003cString[]\u003e] [[-InputObject] \u003cAvailabilityGroup[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SPN validation result. For each listener, two objects are returned - one for the SPN without port (e.g., MSSQLSvc/listener.domain.com) and one with port (e.g., \r\nMSSQLSvc/listener.domain.com:1433). The function queries Active Directory to verify SPN registration and reports the validation status.\nProperties:\r\n- ComputerName: The fully qualified network name of the computer hosting the SQL Server instance\r\n- SqlInstance: The SQL Server instance name\r\n- InstanceName: The instance name (defaults to MSSQLSERVER for default instance)\r\n- SqlProduct: The SQL Server product version string including edition and platform information\r\n- InstanceServiceAccount: The service account running SQL Server (may be modified if virtual or managed service account is detected)\r\n- RequiredSPN: The Service Principal Name that should be registered in Active Directory\r\n- IsSet: Boolean indicating whether the required SPN is currently registered in Active Directory (true if found, false if missing)\r\n- Cluster: Boolean indicating whether SQL Server is running in a clustered configuration\r\n- TcpEnabled: Boolean indicating whether TCP protocol is enabled (always true for AG listeners)\r\n- Port: The TCP port number the listener uses\r\n- DynamicPort: Boolean indicating whether dynamic port allocation is enabled (always false for AG listeners)\r\n- Warning: Reserved for warning messages; contains \"None\" unless a warning condition is detected\r\n- Error: Contains \"SPN missing\" if the SPN is not found in Active Directory, or \"None\" if the SPN is properly registered\nNote: The Credential and DomainName properties are excluded from the default display but remain accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbaAvailabilityGroup -SqlInstance sql01 -AvailabilityGroup SharePoint | Test-DbaAgSpn\nTests the SPNs for the SharePoint availability group listeners on sql01\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaAgSpn -SqlInstance sql01 -AvailabilityGroup SharePoint -Listener spag01\nTests the spag01 SPN for the SharePoint availability group listener on sql01\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaAgSpn -SqlInstance sql01 | Set-DbaSpn\nTests the SPNs for all availability group listeners on sql01 and sets them if they are not set", "Description": "Checks whether the required SPNs are properly registered in Active Directory for each Availability Group listener\u0027s service account. This function queries AD to verify that both the MSSQLSvc/listener.domain.com and MSSQLSvc/listener.domain.com:port SPNs exist, which are essential for Kerberos authentication to work correctly with AG listeners.\n\nUse this to troubleshoot client connectivity issues, validate SPN configuration before deployments, or audit security compliance. Missing SPNs will cause authentication failures when clients attempt to connect using integrated Windows authentication through the listener.\n\nhttps://learn.microsoft.com/en-us/sql/database-engine/availability-groups/windows/listeners-client-connectivity-application-failover?view=sql-server-ver16#SPNs was used as a guide", "Links": "https://dbatools.io/Test-DbaAgSpn", "Synopsis": "Validates Service Principal Name registration for Availability Group listeners in Active Directory", "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", "", "" ], [ "Credential", "Alternative credential for connecting to Active Directory.", "", false, "false", "", "" ], [ "AvailabilityGroup", "Specifies which availability groups to validate SPNs for by name. Use this when you need to check specific AGs instead of all AGs on the instance.\r\nIf not specified, all availability groups will be tested. Accepts multiple AG names for bulk validation.", "", false, "false", "", "" ], [ "Listener", "Specifies which AG listeners to validate SPNs for by listener name. Use this when troubleshooting specific listener connectivity issues.\r\nIf not specified, all listeners within the specified availability groups will be tested. Accepts multiple listener names.", "", false, "false", "", "" ], [ "InputObject", "Accepts availability group objects from Get-DbaAvailabilityGroup for pipeline processing. Use this to chain commands when working with specific AG objects.\r\nThis allows for filtering AGs before SPN validation without needing to specify instance and AG names separately.", "", 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": [ "AvailabilityGroup", "HA", "AG", "Test" ], "CommandName": "Test-DbaAvailabilityGroup", "Name": "Test-DbaAvailabilityGroup", "Author": "Andreas Jordan (@JordanOrdix), ordix.de", "Syntax": "Test-DbaAvailabilityGroup [-SqlInstance] \u003cDbaInstanceParameter\u003e [-SqlCredential \u003cPSCredential\u003e] -AvailabilityGroup \u003cString\u003e [-Secondary \u003cDbaInstanceParameter[]\u003e] [-SecondarySqlCredential \u003cPSCredential\u003e] [-AddDatabase \u003cString[]\u003e] [-SeedingMode \u003cString\u003e] [-SharedPath \u003cString\u003e] [-UseLastBackup] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nWithout the -AddDatabase parameter, returns one object per Availability Group tested with the following properties:\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- AvailabilityGroup: The name of the Availability Group being tested\nWith the -AddDatabase parameter, returns one object per database being added with the following properties:\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- AvailabilityGroupName: The name of the Availability Group\r\n- DatabaseName: The name of the database being added to the AG\r\n- AvailabilityGroupSMO: The Microsoft.SqlServer.Management.Smo.AvailabilityGroup object for the AG\r\n- DatabaseSMO: The Microsoft.SqlServer.Management.Smo.Database object for the database\r\n- PrimaryServerSMO: The Microsoft.SqlServer.Management.Smo.Server object for the primary replica\r\n- ReplicaServerSMO: A hashtable mapping secondary replica names to their Microsoft.SqlServer.Management.Smo.Server objects\r\n- RestoreNeeded: A hashtable mapping replica names to boolean values indicating if database restore is needed on that replica\r\n- Backups: An array of backup history objects from Get-DbaDbBackupHistory (when -UseLastBackup is specified)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaAvailabilityGroup -SqlInstance SQL2016 -AvailabilityGroup TestAG1\nTest Availability Group TestAG1 with SQL2016 as the primary replica.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaAvailabilityGroup -SqlInstance SQL2016 -AvailabilityGroup TestAG1 -AddDatabase AdventureWorks -SeedingMode Automatic\nTest if database AdventureWorks can be added to the Availability Group TestAG1 with automatic seeding.", "Description": "Verifies that all replicas in an Availability Group are connected and communicating properly by checking ConnectionState across all replicas from the primary\u0027s perspective. This helps you identify connectivity issues that could impact failover capabilities or data synchronization.\n\nWhen used with the AddDatabase parameter, performs comprehensive prerequisite validation before adding databases to an AG. Checks that target databases have Full recovery model, Normal status, and proper backup history. Also validates seeding mode compatibility, tests connectivity to secondary replicas, and ensures database restore requirements can be met.\n\nThis prevents common AG setup failures by catching configuration issues early, so you don\u0027t have to troubleshoot failed Add-DbaAgDatabase operations later.", "Links": "https://dbatools.io/Test-DbaAvailabilityGroup", "Synopsis": "Validates Availability Group replica connectivity and database prerequisites for AG operations", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The primary replica of the Availability Group.", "", 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 Availability Group name to validate for replica connectivity and database prerequisites.\r\nUse this to target a specific AG when testing health status or preparing to add databases.", "", true, "false", "", "" ], [ "Secondary", "Specifies secondary replica endpoints when they use non-standard ports or custom connection strings.\r\nThe function auto-discovers secondary replicas from the AG configuration, but use this when replicas listen on custom ports or require specific connection parameters.", "", false, "false", "", "" ], [ "SecondarySqlCredential", "Specifies credentials for connecting to secondary replica instances during validation.\r\nUse this when secondary replicas require different authentication than the primary replica, such as in cross-domain scenarios or when using SQL authentication on secondaries.", "", false, "false", "", "" ], [ "AddDatabase", "Specifies database names to validate for Availability Group addition prerequisites.\r\nTriggers comprehensive validation including recovery model, database status, backup history, and seeding compatibility checks. Use this to prevent Add-DbaAgDatabase failures by catching configuration \r\nissues early.", "", false, "false", "", "" ], [ "SeedingMode", "Specifies the database seeding method for validation when using AddDatabase parameter.\r\nUse \u0027Automatic\u0027 for SQL Server 2016+ environments or \u0027Manual\u0027 when you need to control backup/restore operations. This determines the prerequisite validation logic performed.", "", false, "false", "", "Automatic,Manual" ], [ "SharedPath", "Specifies the network path accessible by all replicas for backup and restore operations during manual seeding validation.\r\nRequired when AddDatabase uses manual seeding and databases need to be restored on secondary replicas. Must be accessible by all SQL Server service accounts.", "", false, "false", "", "" ], [ "UseLastBackup", "Validates that the most recent database backup chain can be used for AG database addition.\r\nEnables validation using existing backups instead of creating new ones, but requires the last backup to be a transaction log backup. Use this to test AG readiness with your current backup strategy.", "", 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": [ "Backups", "Encryption" ], "CommandName": "Test-DbaBackupEncrypted", "Name": "Test-DbaBackupEncrypted", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Test-DbaBackupEncrypted [[-SqlInstance] \u003cDbaInstanceParameter\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [-FilePath] \u003cString[]\u003e [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per backup file analyzed, containing encryption status and certificate information.\nProperties:\r\n- ComputerName (string) - The computer name of the SQL Server instance used for analysis\r\n- InstanceName (string) - The SQL Server instance name used for analysis\r\n- SqlInstance (string) - The full SQL Server instance name (computer\\instance)\r\n- FilePath (string) - The file path of the backup file that was analyzed\r\n- BackupName (string) - The logical name of the backup set from RESTORE HEADERONLY output\r\n- Encrypted (boolean) - Boolean indicating if the backup contains encryption from backup encryption or Transparent Data Encryption (TDE)\r\n- KeyAlgorithm (string) - The encryption key algorithm (e.g., \"AES128\", \"AES192\", \"AES256\", null if not encrypted via backup encryption)\r\n- EncryptorThumbprint (string) - The SHA-1 thumbprint of the backup encryption certificate (null if not encrypted via backup encryption)\r\n- EncryptorType (string) - The type of backup encryptor (e.g., \"Certificate\", \"Asymmetric Key\", null if no backup encryption)\r\n- TDEThumbprint (string) - The TDE thumbprint in hexadecimal format from FILELISTONLY (null if database was not encrypted with TDE)\r\n- Compressed (boolean) - Boolean indicating if the backup was created with compression enabled", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaBackupEncrypted -SqlInstance sql01 -Path /tmp/northwind.bak\nTest to see if /tmp/northwind.bak is encrypted\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-ChildItem \\\\nas\\sql\\backups | Test-DbaBackupEncrypted -SqlInstance sql01\nTest to see if all of the backups in \\\\nas\\sql\\backups are encrypted", "Description": "Examines SQL Server backup files to identify whether they contain encrypted data, either through backup encryption or Transparent Data Encryption (TDE). Uses RESTORE HEADERONLY and RESTORE FILELISTONLY commands to inspect backup headers and file metadata without actually restoring the database. This helps DBAs verify encryption compliance, troubleshoot restore issues, and maintain inventory of encrypted backups across their environment.", "Links": "https://dbatools.io/Test-DbaBackupEncrypted", "Synopsis": "Analyzes backup files to determine encryption status and retrieve encryption details", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", false, "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, "false", "", "" ], [ "FilePath", "Specifies the file path(s) to the backup files (.bak, .trn, .dif) that need to be analyzed for encryption status.\r\nAccepts multiple paths and supports pipeline input from Get-ChildItem or other file discovery commands.\r\nUse this to verify encryption compliance across backup files or troubleshoot restore failures caused by missing encryption certificates.", "FullName,Path", true, "true (ByPropertyName)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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", "Restore", "DisasterRecovery" ], "CommandName": "Test-DbaBackupInformation", "Name": "Test-DbaBackupInformation", "Author": "Stuart Moore (@napalmgram), stuart-moore.com", "Syntax": "Test-DbaBackupInformation [-BackupHistory] \u003cObject[]\u003e [[-SqlInstance] \u003cDbaInstanceParameter\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [-WithReplace] [-Continue] [-VerifyOnly] [-OutputScriptOnly] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "The same backup history object type provided as input, with an additional IsVerified property\nReturns one validated backup history object per input backup, with all original properties preserved and an added IsVerified property.\nProperties:\r\n- IsVerified (boolean) - Boolean indicating whether the backup history passed all validation tests. Set to $True for backups that passed all validation checks (LSN chain integrity, file \r\naccessibility, database conflicts, and path availability). Set to $False or left unchanged for backups with validation errors.\nAll original properties from the input backup history objects remain accessible (BackupName, Database, Type, Path, etc.). The function acts as a pass-through validator that marks backups with a \r\nverification status for filtering restoration candidates.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$BackupHistory | Test-DbaBackupInformation -SqlInstance MyInstance\nPS C:\\\u003e $PassedDbs = $BackupHistory | Where-Object {$_.IsVerified -eq $True}\r\nPS C:\\\u003e $FailedDbs = $BackupHistory | Where-Object {$_.IsVerified -ne $True}\nPass in a BackupHistory object to be tested against MyInstance.\r\nThose records that pass are marked as verified. We can then use the IsVerified property to divide the failures and successes", "Description": "Performs comprehensive pre-restore validation on backup history objects to prevent restore failures before they occur. Input is typically from Format-DbaBackupInformation and gets parsed to verify restore readiness.\n\nThis function runs critical validation tests including LSN chain integrity for transaction log backups, backup file accessibility by the SQL Server service account, database existence conflicts, and file path availability. It also creates necessary target directories and prevents file conflicts with existing databases.\n\nUse this before running Restore-DbaDatabase to catch configuration issues early, saving time during maintenance windows or disaster recovery scenarios. Validated backup sets are marked with IsVerified = $True so you can easily filter successful candidates for restoration.\n\nTests performed include:\n - Checking unbroken LSN chain for transaction log backups\n - Verifying target database doesn\u0027t exist unless WithReplace is specified\n - Ensuring backup files exist and are accessible by SQL Server service account\n - Validating no file conflicts with existing databases\n - Creating required target directories for database files\n - Confirming backup files can be read from the specified locations", "Links": "https://dbatools.io/Test-DbaBackupInformation", "Synopsis": "Validates backup history objects to ensure successful database restoration", "Availability": "Windows, Linux, macOS", "Params": [ [ "BackupHistory", "Backup history objects containing restore chain information, typically generated by Format-DbaBackupInformation. Each object represents a backup file with metadata needed for validation including \r\ndatabase name, backup type, LSN values, and file paths.\r\nPass the output from Format-DbaBackupInformation to validate the entire restore sequence before attempting restoration.", "", true, "true (ByValue)", "", "" ], [ "SqlInstance", "The Sql Server instance that wil be performing the restore", "", 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", "", "" ], [ "WithReplace", "Allows restoration over an existing database with the same name. Without this switch, validation fails if the target database already exists on the destination instance.\r\nUse this when performing disaster recovery or refresh scenarios where you need to replace the current database with backup data.", "", false, "false", "False", "" ], [ "Continue", "Indicates this is a continuation of an existing restore operation, typically used when applying additional transaction log backups. Skips LSN chain validation and allows restoration to databases that \r\nalready exist in RESTORING state.\r\nUse this when performing point-in-time recovery scenarios where you\u0027re applying additional log backups after an initial restore.", "", false, "false", "False", "" ], [ "VerifyOnly", "Performs limited validation focusing only on backup file accessibility and readability. Skips database existence checks, file path conflicts, and directory creation since no actual restore will occur.\r\nUse this when you only need to verify that backup files are valid and accessible without testing restore feasibility to the target instance.", "", false, "false", "False", "" ], [ "OutputScriptOnly", "Prevents automatic creation of missing target directories during validation. Missing paths generate warnings instead of being created automatically.\r\nUse this for testing restore scenarios without making changes to the file system, or when you need to verify permissions before allowing directory 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", "" ], [ "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": [ "SqlBuild", "Version", "Utility" ], "CommandName": "Test-DbaBuild", "Name": "Test-DbaBuild", "Author": "Simone Bizzotto (@niphold) | Friedrich Weinmann (@FredWeinmann)", "Syntax": "Test-DbaBuild [[-Build] \u003cVersion[]\u003e] [[-MinimumBuild] \u003cVersion\u003e] [[-MaxBehind] \u003cString\u003e] [-Latest] [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [-Update] [-Quiet] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.Boolean (when -Quiet parameter is specified)\nReturns only the compliance result: $true if the build is compliant, $false if non-compliant. Designed for automated scripts and monitoring system integration.\nPSCustomObject (default)\nReturns one build compliance object per build version tested. The object includes build information and compliance status with the following properties:\nAlways included:\r\n- Build: The SQL Server build version being tested\r\n- MatchType: How the build was matched - \"Exact\" for recognized builds or \"Approximate\" for unrecognized versions\r\n- Compliant: Boolean indicating if the build meets the specified compliance requirement ($true or $false)\nWhen -MinimumBuild is specified:\r\n- MinimumBuild: The baseline build version that was used for comparison\r\n- SPTarget, CUTarget, BuildTarget: Hidden (not shown by default)\nWhen -MaxBehind or -Latest is specified:\r\n- MaxBehind: The maximum allowed gap specification (e.g., \"1SP\", \"2CU\", \"1SP 1CU\") or empty for -Latest\r\n- SPTarget: Target Service Pack level required for compliance (null when -Latest or -MaxBehind uses only CU specification)\r\n- CUTarget: Target Cumulative Update level required for compliance (null when -Latest or -MaxBehind uses only SP specification)\r\n- BuildTarget: The target build version that represents the compliance threshold\r\n- MinimumBuild: Hidden (not shown by default)\nWhen -SqlInstance is specified (instead of -Build):\r\n- SqlInstance: The source SQL Server instance where the build was discovered\nWhen -SqlInstance is not specified (using -Build):\r\n- SqlInstance: Hidden (not shown by default)\nAll properties can be accessed using Select-Object * regardless of the default display.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaBuild -Build \"12.0.5540\" -MinimumBuild \"12.0.5557\"\nReturns information about a build identified by \"12.0.5540\" (which is SQL 2014 with SP2 and CU4), which is not compliant as the minimum required\r\nbuild is \"12.0.5557\" (which is SQL 2014 with SP2 and CU8).\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaBuild -Build \"12.0.5540\" -MaxBehind \"1SP\"\nReturns information about a build identified by \"12.0.5540\", making sure it is AT MOST 1 Service Pack \"behind\". For that version,\r\nthat identifies an SP2, means accepting as the lowest compliance version as \"12.0.4110\", that identifies 2014 with SP1.\nOutput column CUTarget is not relevant (empty). SPTarget and BuildTarget are filled in the result.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaBuild -Build \"12.0.5540\" -MaxBehind \"1SP 1CU\"\nReturns information about a build identified by \"12.0.5540\", making sure it is AT MOST 1 Service Pack \"behind\", plus 1 CU \"behind\". For that version,\r\nthat identifies an SP2 and CU, rolling back 1 SP brings you to \"12.0.4110\", but given the latest CU for SP1 is CU13, the target \"compliant\" build\r\nwill be \"12.0.4511\", which is 2014 with SP1 and CU12.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eTest-DbaBuild -Build \"12.0.5540\" -MaxBehind \"0CU\"\nReturns information about a build identified by \"12.0.5540\", making sure it is the latest CU release.\nOutput columns CUTarget, SPTarget and BuildTarget are relevant. If the latest build is a service pack (not a CU), CUTarget will be empty.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eTest-DbaBuild -Build \"12.0.5540\" -Latest\nReturns information about a build identified by \"12.0.5540\", making sure it is the latest build available.\nOutput columns CUTarget and SPTarget are not relevant (empty), only the BuildTarget is.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eTest-DbaBuild -Build \"12.00.4502\" -MinimumBuild \"12.0.4511\" -Update\nSame as before, but tries to fetch the most up to date index online. When the online version is newer, the local one gets overwritten.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eTest-DbaBuild -Build \"12.0.4502\",\"10.50.4260\" -MinimumBuild \"12.0.4511\"\nReturns information builds identified by these versions strings.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eGet-DbaRegServer -SqlInstance sqlserver2014a | Test-DbaBuild -MinimumBuild \"12.0.4511\"\nIntegrate with other cmdlets to have builds checked for all your registered servers on sqlserver2014a.", "Description": "Evaluates SQL Server instances or build versions against organizational patching policies to determine compliance status. Returns detailed build information including service pack level, cumulative update, reference KB, and end-of-support dates with a compliance flag. Helps DBAs audit patch levels across environments and identify instances that fall below minimum security or stability requirements. You can test against specific minimum builds, relative currency policies (like \"no more than 1 SP behind\"), or require the latest available build.", "Links": "https://dbatools.io/Test-DbaBuild", "Synopsis": "Tests SQL Server build versions against patching compliance requirements", "Availability": "Windows, Linux, macOS", "Params": [ [ "Build", "Specifies one or more SQL Server build version numbers to test for compliance instead of connecting to live instances.\r\nUse this when you want to check specific build versions like \"12.0.5540\" without querying actual servers.\r\nAccepts version strings in the format major.minor.build or major.minor.build.revision.", "", false, "false", "", "" ], [ "MinimumBuild", "Sets the baseline build version that defines compliance requirements for your environment.\r\nAny SQL Server instance running a build version below this threshold will be flagged as non-compliant.\r\nCommonly used to enforce minimum security patch levels across your SQL Server estate.", "", false, "false", "", "" ], [ "MaxBehind", "Defines compliance based on how many service packs or cumulative updates behind the latest release is acceptable.\r\nUse format like \"1SP\", \"2CU\", or \"1SP 1CU\" to specify maximum allowed gaps from current releases.\r\nThis approach automatically adjusts compliance targets as new patches are released, unlike fixed MinimumBuild values.", "", false, "false", "", "" ], [ "Latest", "Requires SQL Server instances to be running the most current build available for their version.\r\nUse this for environments with strict currency requirements where any outdated build is considered non-compliant.\r\nAutomatically determines the latest available build for each SQL Server major version.", "", false, "false", "False", "" ], [ "SqlInstance", "Target any number of instances, in order to return their compliance 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", "Downloads the latest SQL Server build reference data from online sources before performing compliance checks.\r\nUse this periodically to ensure your compliance testing includes recently released patches and cumulative updates.\r\nThe updated reference data is cached locally for subsequent function calls.", "", false, "false", "False", "" ], [ "Quiet", "Returns only boolean compliance results ($true/$false) instead of detailed build information objects.\r\nDesigned for use in automated scripts where you only need to know pass/fail status.\r\nUseful for integration with monitoring systems or compliance dashboards.", "", 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": [ "ComputerManagement", "CIM" ], "CommandName": "Test-DbaCmConnection", "Name": "Test-DbaCmConnection", "Author": "Friedrich Weinmann (@FredWeinmann)", "Syntax": "Test-DbaCmConnection [[-ComputerName] \u003cDbaCmConnectionParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-Type] {None | CimRM | CimDCOM | Wmi | PowerShellRemoting}] [-Force] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Dataplat.Dbatools.Connection.ConnectionManager\nReturns one connection manager object containing the results of connectivity testing across all requested management protocols.\nDefault properties displayed:\r\n- ComputerName: The target computer name being tested (lowercase format)\r\n- CimRM: Result of CIM over WinRM connectivity test (\"Success\" or \"Error\")\r\n- CimDCOM: Result of CIM over DCOM connectivity test (\"Success\" or \"Error\")\r\n- Wmi: Result of WMI connectivity test (\"Success\" or \"Error\")\r\n- PowerShellRemoting: Result of PowerShell Remoting connectivity test (\"Success\" or \"Error\")\nAdditional properties available (from ConnectionManager object):\r\n- LastCimRM: DateTime of the most recent CIM over WinRM connectivity test\r\n- LastCimDCOM: DateTime of the most recent CIM over DCOM connectivity test\r\n- LastWmi: DateTime of the most recent WMI connectivity test\r\n- LastPowerShellRemoting: DateTime of the most recent PowerShell Remoting test\r\n- KnownBadCredentials: Collection of credentials that have failed in previous tests\r\n- DisableBadCredentialCache: Boolean indicating if bad credential caching is disabled\nThe returned object is automatically cached by dbatools for optimization of future connections using Get-DbaCmObject and Invoke-DbaCmMethod.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaCmConnection -ComputerName sql2014\nPerforms a full-spectrum connection test against the computer sql2014. The results will be reported and registered. Future calls from Get-DbaCmObject will recognize the results and optimize the query.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaCmConnection -ComputerName sql2014 -Credential $null -Type CimDCOM, CimRM\nThis test will run a connectivity test of CIM over DCOM and CIM over WinRM against the computer sql2014 using Windows Authentication.\nThe results will be reported and registered. Future calls from Get-DbaCmObject will recognize the results and optimize the query.", "Description": "Tests remote computer connectivity across four different management protocols to determine the most reliable connection method for SQL Server administration tasks.\n\nThis function evaluates connectivity for:\n- CIM over WinRM (Windows Remote Management)\n- CIM over DCOM (Distributed Component Object Model)\n- WMI (Windows Management Instrumentation)\n- PowerShell Remoting\n\nResults are cached and automatically used by other dbatools commands like Get-DbaCmObject and Invoke-DbaCmMethod to optimize future connections. This eliminates the need to test connectivity repeatedly and ensures faster execution of subsequent operations. The connectivity cache is dynamically updated as other dbatools commands discover working or failing connection methods.\n\nThis function bypasses global configuration settings that might restrict certain protocols, allowing you to test all available connection types regardless of your dbatools configuration.", "Links": "https://dbatools.io/Test-DbaCmConnection", "Synopsis": "Tests remote computer management connectivity using multiple protocols and caches optimal connection methods", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the target computers to test management connectivity against. Accepts computer names, IP addresses, or FQDN formats.\r\nUse this to validate which remote management protocols work before running other dbatools commands that require computer management access.\r\nDefaults to the local computer if not specified.", "", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "The credentials to use when running the test. Bad credentials are automatically cached as non-working. This behavior can be disabled by the \u0027Cache.Management.Disable.BadCredentialList\u0027 configuration.", "", false, "false", "", "" ], [ "Type", "Specifies which remote management protocols to test for connectivity. Tests all four protocols by default.\r\nUse this to focus testing on specific protocols when troubleshooting connectivity issues or when you know certain protocols are blocked in your environment.\r\nAvailable options: CimRM (CIM over WinRM), CimDCOM (CIM over DCOM), Wmi (legacy WMI), PowerShellRemoting.", "", false, "false", "@(\"CimRM\", \"CimDCOM\", \"Wmi\", \"PowerShellRemoting\")", "" ], [ "Force", "Forces testing even when credentials are cached as previously failed. Removes bad credential cache entries and retests connectivity.\r\nUse this when credentials have been updated or when network connectivity issues have been resolved since the last test.", "", 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": "Test-DbaComputerCertificateExpiration", "Name": "Test-DbaComputerCertificateExpiration", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Test-DbaComputerCertificateExpiration [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-Store] \u003cString[]\u003e] [[-Folder] \u003cString[]\u003e] [[-Type] \u003cString\u003e] [[-Path] \u003cString\u003e] [[-Thumbprint] \u003cString[]\u003e] [[-Threshold] \u003cInt32\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Certificate objects with added properties\nReturns certificate objects from either Get-DbaNetworkCertificate or Get-DbaComputerCertificate for any certificates that are expired or will expire within the threshold period. If no certificates \r\nmeet the expiration criteria, nothing is returned.\nDisplayed properties (via Select-DefaultView):\r\n- ComputerName: The name of the computer where the certificate is stored\r\n- Store: The certificate store location (LocalMachine, CurrentUser, etc.)\r\n- Folder: The certificate folder within the store (My, Root, CA, etc.)\r\n- Name: The friendly name of the certificate\r\n- DnsNameList: Array of DNS names associated with the certificate (Subject Alternative Names)\r\n- Thumbprint: The SHA-1 hash of the certificate used for identification\r\n- NotBefore: DateTime when the certificate becomes valid (validity start date)\r\n- NotAfter: DateTime when the certificate expires (validity end date)\r\n- Subject: The certificate subject Distinguished Name (DN)\r\n- Issuer: The certificate issuer Distinguished Name (DN)\r\n- Algorithm: The signature algorithm used by the certificate (e.g., sha256RSA)\r\n- ExpiredOrExpiring: Boolean value indicating the certificate is expired or expiring (always $true for returned objects)\r\n- Note: Human-readable description of the expiration status (e.g., \"This certificate expires in 15 days\" or \"This certificate has expired and is no longer valid\")\nAll standard X.509 certificate properties are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaComputerCertificateExpiration\nGets computer certificates on localhost that are candidates for using with SQL Server\u0027s network encryption then checks to see if they\u0027ll be expiring within 30 days\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaComputerCertificateExpiration -ComputerName sql2016 -Threshold 90\nGets computer certificates on sql2016 that are candidates for using with SQL Server\u0027s network encryption then checks to see if they\u0027ll be expiring within 90 days\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaComputerCertificateExpiration -ComputerName sql2016 -Thumbprint 8123472E32AB412ED4288888B83811DB8F504DED, 04BFF8B3679BB01A986E097868D8D494D70A46D6\nGets computer certificates on sql2016 that match thumbprints 8123472E32AB412ED4288888B83811DB8F504DED or 04BFF8B3679BB01A986E097868D8D494D70A46D6 then checks to see if they\u0027ll be expiring within 30 \r\ndays", "Description": "Scans computer certificate stores to find certificates that are expired or will expire within a specified timeframe. This function focuses on certificates used for SQL Server network encryption, helping DBAs proactively identify potential connection failures before they occur.\n\nBy default, it examines certificates that are candidates for SQL Server\u0027s network encryption feature. You can also check certificates currently in use by SQL Server instances or scan all certificates in the specified store. The function compares each certificate\u0027s expiration date against a configurable threshold (30 days by default) and returns detailed information about any certificates requiring attention.\n\nThis is essential for maintaining secure SQL Server connections and preventing unexpected service disruptions caused by expired certificates.", "Links": "https://dbatools.io/Test-DbaComputerCertificateExpiration", "Synopsis": "Identifies SSL/TLS certificates that are expired or expiring soon on SQL Server computers", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "The target SQL Server instance or instances. Defaults to localhost. If target is a cluster, you must specify the distinct nodes.", "", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Allows you to login to $ComputerName using alternative credentials.", "", false, "false", "", "" ], [ "Store", "Specifies the certificate store to scan for certificates. Defaults to LocalMachine which contains system-wide certificates.\r\nUse this when you need to check certificates in different stores like CurrentUser for user-specific certificates.", "", false, "false", "LocalMachine", "" ], [ "Folder", "Specifies the certificate folder within the store to examine. Defaults to My (Personal) where SSL certificates are typically stored.\r\nCommon folders include My for personal certificates, Root for trusted root authorities, and CA for intermediate certificate authorities.", "", false, "false", "My", "" ], [ "Type", "Determines which certificates to examine based on their intended use. Defaults to Service which finds certificates suitable for SQL Server.\r\nService finds certificates that meet SQL Server\u0027s requirements but may also be used by other services like IIS. SQL Server returns only certificates currently configured for use by SQL Server \r\ninstances. All examines every certificate in the specified store regardless of suitability.", "", false, "false", "Service", "All,Service,SQL Server" ], [ "Path", "Specifies the file system path to a specific certificate file to examine instead of scanning certificate stores.\r\nUse this when you have certificate files (.cer, .crt, .pfx) on disk that you want to check for expiration.", "", false, "false", "", "" ], [ "Thumbprint", "Filters results to certificates matching the specified thumbprint values. Accepts multiple thumbprints as an array.\r\nUse this when you need to check specific certificates you\u0027ve identified through other means or are monitoring for compliance.", "", false, "false", "", "" ], [ "Threshold", "Sets the number of days before expiration to trigger a warning. Defaults to 30 days.\r\nAdjust this based on your certificate renewal process - use 90 days if you need longer lead times for procurement and testing.", "", false, "false", "30", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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": "Test-DbaConnection", "Name": "Test-DbaConnection", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Test-DbaConnection [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [-SkipPSRemoting] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance with comprehensive connection and environment diagnostics.\nProperties:\r\n- ComputerName: The resolved computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name (MSSQLSERVER for default instance)\r\n- SqlInstance: The full SMO instance name (computer\\instance format)\r\n- SqlVersion: The SQL Server version number (e.g., 13.0.4001 for SQL Server 2016)\r\n- ConnectingAsUser: The login name used to establish the SQL connection\r\n- ConnectSuccess: Boolean indicating whether the SQL Server connection was successful\r\n- AuthType: The type of authentication used (Windows Authentication or SQL Authentication)\r\n- AuthScheme: The authentication scheme (KERBEROS, NTLM, SQL, etc.) or error if retrieval failed\r\n- TcpPort: The TCP port number used by the SQL Server instance; contains error details if port detection failed\r\n- IPAddress: The IP address of the target server\r\n- NetBiosName: The fully qualified domain name (FQDN) of the server\r\n- IsPingable: Boolean indicating whether the server responds to ICMP ping requests\r\n- PSRemotingAccessible: Boolean indicating PSRemoting connectivity status; contains error details if test failed or skipped\r\n- DomainName: The Active Directory domain name\r\n- LocalWindows: The Windows OS version on the local machine where the command runs\r\n- LocalPowerShell: The PowerShell version on the local machine\r\n- LocalCLR: The CLR (Common Language Runtime) version on the local machine\r\n- LocalSMOVersion: The SQL Server Management Objects (SMO) version on the local machine\r\n- LocalDomainUser: Boolean indicating whether the local session is running as a domain user\r\n- LocalRunAsAdmin: Boolean indicating whether the local session is running with administrator privileges\r\n- LocalEdition: The PowerShell edition (Desktop or Core)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaConnection SQL2016\nComputerName : SQL2016\r\nInstanceName : MSSQLSERVER\r\nSqlInstance : sql2016\r\nSqlVersion : 13.0.4001\r\nConnectingAsUser : BASE\\ctrlb\r\nConnectSuccess : True\r\nAuthType : Windows Authentication\r\nAuthScheme : KERBEROS\r\nTcpPort : 1433\r\nIPAddress : 10.2.1.5\r\nNetBiosName : sql2016.base.local\r\nIsPingable : True\r\nPSRemotingAccessible : True\r\nDomainName : base.local\r\nLocalWindows : 10.0.15063.0\r\nLocalPowerShell : 5.1.15063.502\r\nLocalCLR : 4.0.30319.42000\r\nLocalSMOVersion : 13.0.0.0\r\nLocalDomainUser : True\r\nLocalRunAsAdmin : False\r\nLocalEdition : Desktop\nTest connection to SQL2016 and outputs information collected\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$winCred = Get-Credential sql2017\\Administrator\nPS C:\\\u003e $sqlCred = Get-Credential sa\r\nPS C:\\\u003e Test-DbaConnection SQL2017 -SqlCredential $sqlCred -Credential $winCred\nComputerName : SQL2017\r\nInstanceName : MSSQLSERVER\r\nSqlInstance : sql2017\r\nSqlVersion : 14.0.3356\r\nConnectingAsUser : sa\r\nConnectSuccess : True\r\nAuthType : SQL Authentication\r\nAuthScheme : SQL\r\nTcpPort : 50164\r\nIPAddress : 10.10.10.15\r\nNetBiosName : sql2017.company.local\r\nIsPingable : True\r\nPSRemotingAccessible : True\r\nDomainName : company.local\r\nLocalWindows : 10.0.15063.0\r\nLocalPowerShell : 5.1.19041.610\r\nLocalCLR : 4.0.30319.42000\r\nLocalSMOVersion : 15.100.0.0\r\nLocalDomainUser : True\r\nLocalRunAsAdmin : False\r\nLocalEdition : Desktop\nTest connection to SQL2017 instance and collecting information on SQL Server using the sa login, local Administrator account is used to collect port information", "Description": "Tests SQL Server instance connectivity while collecting detailed connection and environment information for troubleshooting. Returns authentication details, network configuration, TCP ports, and local PowerShell environment data. Essential for diagnosing connectivity issues before running automation scripts or validating access across multiple instances. Combines SQL connection testing with network diagnostics including ping status, PSRemoting access, and DNS resolution.", "Links": "https://dbatools.io/Test-DbaConnection", "Synopsis": "Validates SQL Server connectivity and gathers comprehensive connection diagnostics", "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)", "", "" ], [ "Credential", "Windows credentials for computer-level access to the target server. Required for PSRemoting tests and TCP port detection when running under a different security context.\r\nUse this when your current Windows account lacks administrative privileges on the target server or when testing across domain boundaries.", "", 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", "", "" ], [ "SkipPSRemoting", "Skips the PowerShell remoting connectivity test during the connection assessment.\r\nUse this when PSRemoting is disabled or blocked by firewall rules but you still want to test SQL connectivity and gather other diagnostic information.", "", 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": [ "SPN", "Kerberos" ], "CommandName": "Test-DbaConnectionAuthScheme", "Name": "Test-DbaConnectionAuthScheme", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Test-DbaConnectionAuthScheme [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Kerberos] [-Ntlm] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nDefault output (no -Kerberos or -Ntlm switch):\r\nReturns one object per instance queried showing the current connection details from sys.dm_exec_connections.\nDefault display properties:\r\n- ComputerName: The computer name from SERVERPROPERTY\r\n- InstanceName: The instance name from SERVERPROPERTY\r\n- SqlInstance: The server name from SERVERPROPERTY\r\n- Transport: Network transport type (TCP, Named Pipes, Shared Memory, etc.)\r\n- AuthScheme: Authentication scheme used (Kerberos or NTLM)\nAdditional properties available (via Select-Object *):\r\n- SessionId: Current session ID\r\n- MostRecentSessionId: Most recent session ID\r\n- ConnectTime: DateTime when the connection was established\r\n- ProtocolType: Type of protocol used\r\n- ProtocolVersion: Version of the protocol\r\n- EndpointId: Endpoint identifier\r\n- EncryptOption: Encryption option setting\r\n- NodeAffinity: Node affinity setting\r\n- NumReads: Number of read operations\r\n- NumWrites: Number of write operations\r\n- LastRead: DateTime of last read operation\r\n- LastWrite: DateTime of last write operation\r\n- PacketSize: Network packet size in bytes\r\n- ClientNetworkAddress: Client network address\r\n- ClientTcpPort: Client TCP port number\r\n- ServerNetworkAddress: Server network address\r\n- ServerTcpPort: Server TCP port number\r\n- ConnectionId: Connection identifier\r\n- ParentConnectionId: Parent connection identifier\r\n- MostRecentSqlHandle: Most recent SQL handle\nWith -Kerberos or -Ntlm switch:\r\nReturns a filtered object with these properties:\r\n- ComputerName: The computer name\r\n- InstanceName: The instance name\r\n- SqlInstance: The server instance name\r\n- Result: Boolean indicating if the connection uses the specified authentication scheme ($true if using Kerberos or NTLM as specified, $false otherwise)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaConnectionAuthScheme -SqlInstance sqlserver2014a, sql2016\nReturns ConnectName, ServerName, Transport and AuthScheme for sqlserver2014a and sql2016.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaConnectionAuthScheme -SqlInstance sqlserver2014a -Kerberos\nReturns $true or $false depending on if the connection is Kerberos or not.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaConnectionAuthScheme -SqlInstance sqlserver2014a | Select-Object *\nReturns the results of \"SELECT * from sys.dm_exec_connections WHERE session_id = @@SPID\"", "Description": "This command queries sys.dm_exec_connections to retrieve authentication and transport details for your current SQL Server session. By default, it returns key connection properties including ServerName, Transport protocol, and AuthScheme (Kerberos or NTLM).\n\nThis is particularly valuable for troubleshooting authentication issues when you expect Kerberos but are getting NTLM instead. The ServerName returned shows what SQL Server reports as its @@SERVERNAME, which must match your connection name for proper SPN registration and Kerberos authentication.\n\nWhen used with -Kerberos or -Ntlm switches, the command returns simple $true/$false results to verify specific authentication methods. This makes it ideal for automated checks and scripts that need to validate authentication schemes across multiple servers.\n\nCommon scenarios include diagnosing SPN configuration problems, security auditing of connection protocols, and verifying that domain authentication is working as expected in your environment.", "Links": "https://dbatools.io/Test-DbaConnectionAuthScheme", "Synopsis": "Tests and reports authentication scheme and transport protocol details for SQL Server 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", "", "" ], [ "Kerberos", "Returns $true if the connection uses Kerberos authentication, $false otherwise.\r\nUse this switch when you need to verify that domain authentication is working properly and not falling back to NTLM.", "", false, "false", "False", "" ], [ "Ntlm", "Returns $true if the connection uses NTLM authentication, $false otherwise.\r\nUse this switch to confirm when connections are using NTLM instead of the preferred Kerberos authentication method.", "", 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": [ "Database", "Collation" ], "CommandName": "Test-DbaDbCollation", "Name": "Test-DbaDbCollation", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Test-DbaDbCollation [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database on the specified instance(s) 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: Name of the database being tested\r\n- ServerCollation: The default collation of the SQL Server instance\r\n- DatabaseCollation: The collation setting of the database\r\n- IsEqual: Boolean indicating if the database collation matches the server\u0027s default collation ($true if match, $false if different)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaDbCollation -SqlInstance sqlserver2014a\nReturns server name, database name and true/false if the collations match for all databases on sqlserver2014a.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaDbCollation -SqlInstance sqlserver2014a -Database db1, db2\nReturns information for the db1 and db2 databases on sqlserver2014a.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaDbCollation -SqlInstance sqlserver2014a, sql2016 -Exclude db1\nReturns information for database and server collations for all databases except db1 on sqlserver2014a and sql2016.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaRegServer -SqlInstance sql2016 | Test-DbaDbCollation\nReturns db/server collation information for every database on every server listed in the Central Management Server on sql2016.", "Description": "Compares each database\u0027s collation against the SQL Server instance\u0027s default collation to identify mismatches. Database collation mismatches can cause string comparison issues, join failures, and stored procedure errors when working across databases. This function helps you audit collation consistency across your databases, which is especially important before migrations, mergers, or when troubleshooting application issues related to character sorting and comparison behavior.", "Links": "https://dbatools.io/Test-DbaDbCollation", "Synopsis": "Identifies databases with collations that differ from the SQL Server instance default collation", "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 collation mismatches against the server\u0027s default collation. Accepts wildcards for pattern matching.\r\nUse this when you need to focus collation testing on specific databases rather than scanning all databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies which databases to skip during collation testing. Useful for excluding system databases or databases you know have intentional collation differences.\r\nCommon scenarios include skipping databases with different language requirements or legacy databases scheduled for decommission.", "", 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", "Compatibility" ], "CommandName": "Test-DbaDbCompatibility", "Name": "Test-DbaDbCompatibility", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Test-DbaDbCompatibility [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database processed. The number of objects depends on the number of databases on the instance and any filtering applied via -Database or -ExcludeDatabase parameters.\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- ServerLevel: The SQL Server instance\u0027s compatibility level (CompatibilityLevel enum value like Version140, Version150, etc.)\r\n- Database: The name of the database being evaluated\r\n- DatabaseCompatibility: The database\u0027s current compatibility level (CompatibilityLevel enum value)\r\n- IsEqual: Boolean indicating whether the database compatibility level matches the server\u0027s maximum compatibility level", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaDbCompatibility -SqlInstance sqlserver2014a\nReturns server name, database name and true/false if the compatibility level match for all databases on sqlserver2014a.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaDbCompatibility -SqlInstance sqlserver2014a -Database db1, db2\nReturns detailed information for database and server compatibility level for the db1 and db2 databases on sqlserver2014a.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaDbCompatibility -SqlInstance sqlserver2014a, sql2016 -Exclude db1\nReturns detailed information for database and server compatibility level for all databases except db1 on sqlserver2014a and sql2016.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaRegServer -SqlInstance sql2014 | Test-DbaDbCompatibility\nReturns db/server compatibility information for every database on every server listed in the Central Management Server on sql2016.", "Description": "Compares each database\u0027s compatibility level against the SQL Server instance\u0027s maximum supported compatibility level. This helps identify databases that may not be leveraging newer SQL Server features and performance improvements available after an instance upgrade. Returns detailed comparison results showing which databases could benefit from compatibility level updates to match the server version.", "Links": "https://dbatools.io/Test-DbaDbCompatibility", "Synopsis": "Identifies databases running at lower compatibility levels than the SQL Server instance supports", "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 test for compatibility level mismatches. Accepts database names, wildcards, or arrays.\r\nUse this when you need to check specific databases instead of testing all databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies which databases to skip during compatibility level testing. Accepts database names, wildcards, or arrays.\r\nUse this to exclude system databases, maintenance databases, or any databases you don\u0027t want included in the 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": [ "Compression", "Table" ], "CommandName": "Test-DbaDbCompression", "Name": "Test-DbaDbCompression", "Author": "Jason Squires (@js_0505), jstexasdba@gmail.com", "Syntax": "Test-DbaDbCompression [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-ExcludeDatabase] \u003cString[]\u003e] [[-Schema] \u003cString[]\u003e] [[-Table] \u003cString[]\u003e] [[-ResultSize] \u003cInt32\u003e] [[-Rank] \u003cString\u003e] [[-FilterBy] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per table/index/partition analyzed (depending on -FilterBy parameter), providing compression analysis recommendations and estimated space savings.\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- Database: Name of the database analyzed\r\n- Schema: Name of the schema containing the table\r\n- TableName: Name of the table being analyzed\r\n- IndexName: Name of the index; null for heap analysis or when FilterBy is \u0027Table\u0027\r\n- Partition: Partition number; 0 when FilterBy is \u0027Table\u0027 or \u0027Index\u0027, otherwise partition number\r\n- IndexID: Index ID number; 0 when FilterBy is \u0027Table\u0027, internal SQL Server index ID for other FilterBy values\r\n- IndexType: Type of index structure (Heap, ClusteredIndex, NonClusteredIndex, etc.)\r\n- PercentScan: Percentage of operations that are scans (0-100); higher values indicate PAGE compression suitability\r\n- PercentUpdate: Percentage of operations that are updates (0-100); higher values indicate ROW compression suitability\r\n- RowEstimatePercentOriginal: Estimated size with ROW compression as percentage of original size\r\n- PageEstimatePercentOriginal: Estimated size with PAGE compression as percentage of original size\r\n- CompressionTypeRecommendation: Recommended compression type (ROW, PAGE, NO_GAIN, or ? when undetermined)\r\n- SizeCurrent: Current size in bytes; dbasize object (displays as B, KB, MB, GB, or TB)\r\n- SizeRequested: Estimated size after applying recommended compression type\r\n- PercentCompression: Percentage of space savings with recommended compression (0-100 range)\nGranularity and filtering controlled by parameters:\r\n- When -FilterBy is \u0027Partition\u0027 (default): One object per partition per index\r\n- When -FilterBy is \u0027Index\u0027: One object per index grouped across partitions\r\n- When -FilterBy is \u0027Table\u0027: One object per table grouped across all indexes and partitions\r\n- When -ResultSize is specified: Only top N objects by -Rank (TotalPages, UsedPages, or TotalRows) are returned per database", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaDbCompression -SqlInstance localhost\nReturns results of all potential compression options for all databases for the default instance on the local host. Returns a recommendation of either Page, Row or NO_GAIN\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaDbCompression -SqlInstance ServerA\nReturns results of all potential compression options for all databases on the instance ServerA\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaDbCompression -SqlInstance ServerA -Database DBName | Out-GridView\nReturns results of all potential compression options for a single database DBName with the recommendation of either Page or Row or NO_GAIN in a nicely formatted GridView\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Test-DbaDbCompression -SqlInstance ServerA -ExcludeDatabase MyDatabase -SqlCredential $cred\nReturns results of all potential compression options for all databases except MyDatabase on instance ServerA using SQL credentials to authentication to ServerA.\r\nReturns the recommendation of either Page, Row or NO_GAIN\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eTest-DbaDbCompression -SqlInstance ServerA -Schema Test -Table MyTable\nReturns results of all potential compression options for the Table Test.MyTable in instance ServerA on ServerA and ServerB.\r\nReturns the recommendation of either Page, Row or NO_GAIN.\r\nReturns a result for each partition of any Heap, Clustered or NonClustered index.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eTest-DbaDbCompression -SqlInstance ServerA, ServerB -ResultSize 10\nReturns results of all potential compression options for all databases on ServerA and ServerB.\r\nReturns the recommendation of either Page, Row or NO_GAIN.\r\nReturns results for the top 10 partitions by TotalPages used per database.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eServerA | Test-DbaDbCompression -Schema Test -ResultSize 10 -Rank UsedPages -FilterBy Table\nReturns results of all potential compression options for all databases on ServerA containing a schema Test\r\nReturns results for the top 10 Tables by Used Pages per database.\r\nResults are split by Table, Index and Partition so more than 10 results may be returned.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003e$servers = \u0027Server1\u0027,\u0027Server2\u0027\nPS C:\\\u003e $servers | Test-DbaDbCompression -Database DBName | Out-GridView\nReturns results of all potential compression options for a single database DBName on Server1 or Server2\r\nReturns the recommendation of either Page, Row or NO_GAIN in a nicely formatted GridView\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003e$cred = Get-Credential sqladmin\nPS C:\\\u003e Test-DbaDbCompression -SqlInstance ServerA -Database MyDB -SqlCredential $cred -Schema Test -Table Test1, Test2\nReturns results of all potential compression options for objects in Database MyDb on instance ServerA using SQL credentials to authentication to ServerA.\r\nReturns the recommendation of either Page, Row or NO_GAIN for tables with Schema Test and name in Test1 or Test2\n-------------------------- EXAMPLE 10 --------------------------\nPS C:\\\u003e$servers = \u0027Server1\u0027,\u0027Server2\u0027\nPS C:\\\u003e foreach ($svr in $servers) {\r\n\u003e\u003e Test-DbaDbCompression -SqlInstance $svr | Export-Csv -Path C:\\temp\\CompressionAnalysisPAC.csv -Append\r\n\u003e\u003e }\nThis produces a full analysis of all your servers listed and is pushed to a csv for you to analyze.", "Description": "Performs comprehensive compression analysis on user tables and indexes to help DBAs identify storage optimization opportunities. Uses SQL Server\u0027s sp_estimate_data_compression_savings system procedure combined with workload pattern analysis to recommend the most effective compression type for each object.\n\nThis function analyzes your database workload patterns (scan vs update ratios) and calculates potential space savings to recommend ROW compression, PAGE compression, or no compression. Longer server uptime provides more accurate workload statistics, so consider running Get-DbaUptime first to verify sufficient data collection time.\n\nThe analysis examines operational statistics from sys.dm_db_index_operational_stats to determine usage patterns:\n- Percent_Update shows the percentage of update operations relative to total operations. Lower update percentages indicate better candidates for page compression.\n- Percent_Scan shows the percentage of scan operations relative to total operations. Higher scan percentages indicate better candidates for page compression.\n- Compression_Type_Recommendation provides specific guidance: \u0027PAGE\u0027, \u0027ROW\u0027, \u0027NO_GAIN\u0027 or \u0027?\u0027 when the algorithm cannot determine the best option.\n\nThe function automatically excludes tables that cannot be compressed: memory-optimized tables (SQL 2014+), tables with encrypted columns (SQL 2016+), graph tables (SQL 2017+), tables with sparse columns, tables with FileStream columns, and FileTables (SQL 2012+). It only analyzes user tables with no existing compression and requires SQL Server 2016 SP1 or higher for non-Enterprise editions.\n\nTest-DbaDbCompression script derived from GitHub and the Tiger Team\u0027s repository: (https://github.com/Microsoft/tigertoolbox/tree/master/Evaluate-Compression-Gains)\n\nBe aware this may take considerable time on large databases as sp_estimate_data_compression_savings requires shared locks that can be blocked by concurrent activity. The analysis covers only ROW and PAGE compression options, not columnstore compression.", "Links": "https://dbatools.io/Test-DbaDbCompression", "Synopsis": "Analyzes user tables and indexes to recommend optimal compression settings for storage space reduction.", "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 opportunities. Accepts multiple database names and supports wildcards.\r\nUse this to focus analysis on specific databases rather than scanning all user databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies databases to skip during compression analysis. Helpful when you want to analyze most databases but exclude specific ones.\r\nCommonly used to skip databases that are already compressed, read-only, or contain sensitive data requiring separate analysis.", "", false, "false", "", "" ], [ "Schema", "Filters analysis to specific database schemas only. Accepts multiple schema names for targeted analysis.\r\nUse this when you need compression recommendations for tables in specific schemas like \u0027dbo\u0027, \u0027sales\u0027, or custom application schemas.", "", false, "false", "", "" ], [ "Table", "Filters analysis to specific table names only. Accepts multiple table names for focused compression analysis.\r\nUse this when investigating compression opportunities for known large tables or when validating compression recommendations for specific objects.", "", false, "false", "", "" ], [ "ResultSize", "Limits the number of objects analyzed per database to control analysis scope and execution time. No limit applied when unspecified.\r\nUse this on large databases to focus on the biggest storage consumers first, as compression analysis can be time-intensive on systems with thousands of tables.", "", false, "false", "0", "" ], [ "Rank", "Determines how objects are prioritized when ResultSize limits are applied. Options are TotalPages (default), UsedPages, or TotalRows.\r\nTotalPages focuses on allocated storage, UsedPages targets actual data consumption, and TotalRows prioritizes by record count for different optimization strategies.", "", false, "false", "TotalPages", "TotalPages,UsedPages,TotalRows" ], [ "FilterBy", "Sets the granularity level for ResultSize filtering. Options are Partition (default), Index, or Table level filtering.\r\nPartition level provides most detailed analysis per partition, Index level groups by index, and Table level gives broader table-focused results.", "", false, "false", "Partition", "Partition,Index,Table" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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": "Test-DbaDbDataGeneratorConfig", "Name": "Test-DbaDbDataGeneratorConfig", "Author": "Sander Stad (@sqlstad), sqlstad.nl", "Syntax": "Test-DbaDbDataGeneratorConfig [-FilePath] \u003cString\u003e [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns validation error objects for any configuration issues found. If the configuration file is valid with no errors, no output is returned.\nEach error object contains the following properties:\n- Table (string): Name of the table in the configuration where the error was found\r\n- Column (string): Name of the column in the table where the error was found\r\n- Value (string): The problematic value or comma-separated list of property names causing the error\r\n- Error (string): Description of the validation error encountered\nCommon validation errors include:\r\n- Missing required column properties (CharacterString, ColumnType, Composite, ForeignKey, Identity, MaskingType, MaxValue, MinValue, Name, Nullable, SubType)\r\n- Additional properties in columns that are not in the required properties list\r\n- Invalid column data types (unsupported by SQL Server or the Bogus data generation library)\r\n- Invalid masking types (not available in the Bogus randomization library)\r\n- Invalid masking subtypes (not available for the specified masking type)\nThe validation errors help identify configuration issues before attempting to generate test data with Invoke-DbaDbDataGenerator, preventing runtime failures.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaDbDataGeneratorConfig -FilePath C:\\temp\\_datamasking\\db1.json\nTest the configuration file", "Description": "Validates JSON configuration files created by New-DbaDbDataGeneratorConfig before using them with Invoke-DbaDbDataGenerator to populate tables with realistic fake data. The function performs comprehensive validation including checking for required column properties, verifying data types are supported, confirming masking types exist in the Bogus library, and validating subtypes are available.\n\nThis validation step prevents runtime errors during data generation and helps catch configuration issues early in the test data creation workflow. Returns detailed error information for any invalid configurations, showing exactly which tables and columns have problems so you can fix them before attempting to generate data.", "Links": "https://dbatools.io/Test-DbaDbDataGeneratorConfig", "Synopsis": "Validates JSON configuration files used for generating realistic test data in SQL Server databases", "Availability": "Windows, Linux, macOS", "Params": [ [ "FilePath", "Specifies the path to the JSON configuration file created by New-DbaDbDataGeneratorConfig that needs validation.\r\nUse this to verify your data generation configuration before running Invoke-DbaDbDataGenerator to avoid runtime errors.", "", 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", "" ] ] }, { "Tags": [ "Masking", "DataMasking" ], "CommandName": "Test-DbaDbDataMaskingConfig", "Name": "Test-DbaDbDataMaskingConfig", "Author": "Sander Stad (@sqlstad), sqlstad.nl", "Syntax": "Test-DbaDbDataMaskingConfig [-FilePath] \u003cString\u003e [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns validation error objects for any configuration issues found. If the configuration file is valid with no errors, no output is returned.\nEach error object contains the following properties:\n- Table (string): Name of the table in the configuration where the error was found\r\n- Column (string): Name of the column in the table where the error was found\r\n- Value (string): The problematic value or comma-separated list of property names causing the error\r\n- Error (string): Description of the validation error encountered\nCommon validation errors include:\r\n- Missing required column properties (Action, CharacterString, ColumnType, Composite, Deterministic, Format, MaskingType, MaxValue, MinValue, Name, Nullable, KeepNull, SubType)\r\n- Invalid column data types (unsupported by SQL Server or dbatools)\r\n- Invalid masking types or subtypes (not available in dbatools randomization library)\r\n- Unsupported action categories, types, or subcategories\r\n- Invalid date range values or missing required min/max values for \u0027Between\u0027 subtype\r\n- Missing required action properties (Category, Type, Value for datetime actions; Category, Type, Value for number actions)\r\n- Action category incompatibility with column data type\r\n- Additional properties in columns that are not in the allowed properties list", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaDbDataMaskingConfig -FilePath C:\\temp\\_datamasking\\db1.json\nTest the configuration file", "Description": "Validates data masking configuration JSON files by checking column properties, data types, masking types, and action configurations against dbatools requirements.\nReturns detailed error information for any tables and columns that fail validation, helping you identify configuration issues before running data masking operations.\nChecks include required/allowed column properties, supported SQL Server data types, valid masking and subtype combinations, date range validations, and action property requirements.\nEssential for troubleshooting complex masking configurations and ensuring they\u0027ll execute successfully without runtime errors.", "Links": "https://dbatools.io/Test-DbaDbDataMaskingConfig", "Synopsis": "Validates data masking configuration JSON files for structural and logical errors", "Availability": "Windows, Linux, macOS", "Params": [ [ "FilePath", "Specifies the full path to the data masking configuration JSON file to validate.\r\nUse this to verify your masking configuration before running New-DbaDbDataMaskingConfig or Invoke-DbaDbDataMasking to catch errors early.", "", 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", "" ] ] }, { "Tags": "LogShipping", "CommandName": "Test-DbaDbLogShipStatus", "Name": "Test-DbaDbLogShipStatus", "Author": "Sander Stad (@sqlstad), sqlstad.nl", "Syntax": "Test-DbaDbLogShipStatus [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString[]\u003e] [[-ExcludeDatabase] \u003cString[]\u003e] [-Simple] [-Primary] [-Secondary] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per log-shipped database configured on the monitoring instance. Output structure varies based on the -Simple parameter.\nDefault output (without -Simple) includes all 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 log-shipped database\r\n- InstanceType: The role of the instance - either \"Primary Instance\" (backup/copy operations) or \"Secondary Instance\" (restore operations)\r\n- TimeSinceLastBackup: DateTime of the most recent backup operation (or \"N/A\" if never executed)\r\n- LastBackupFile: The name of the file involved in the last backup operation\r\n- BackupThreshold: The configured threshold in minutes for maximum acceptable time between backups\r\n- IsBackupAlertEnabled: Boolean indicating whether alerting is enabled for backup operation failures\r\n- TimeSinceLastCopy: DateTime of the most recent copy operation (or \"N/A\" if never executed); only relevant on secondary instances\r\n- LastCopiedFile: The name of the file involved in the last copy operation\r\n- TimeSinceLastRestore: DateTime of the most recent restore operation (or \"N/A\" if never executed); only relevant on secondary instances\r\n- LastRestoredFile: The name of the file involved in the last restore operation\r\n- LastRestoredLatency: The delay in seconds between the backup and restore operations (latency between primary and secondary)\r\n- RestoreThreshold: The configured threshold in minutes for maximum acceptable time between restore operations\r\n- IsRestoreAlertEnabled: Boolean indicating whether alerting is enabled for restore operation failures\r\n- Status: String containing operational status - \"All OK\" for healthy operations or detailed error message(s) describing any issues (e.g., \"The backup has not been executed in the last 60 minutes\")\nWhen -Simple is specified:\r\n- Only four properties are returned: SqlInstance, Database, InstanceType, and Status\r\n- This provides a quick health overview without detailed timing information\nWhen -Primary is specified:\r\n- Only databases acting as primary instances are returned; backup-related properties are populated\r\n- Copy and restore properties may be empty or N/A since those operations occur on secondaries\nWhen -Secondary is specified:\r\n- Only databases acting as secondary instances are returned; copy and restore properties are populated\r\n- Backup properties may be empty or N/A since backup operations occur on primaries", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaDbLogShipStatus -SqlInstance sql1\nRetrieves the log ship information from sql1 and displays all the information present including the status.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaDbLogShipStatus -SqlInstance sql1 -Database AdventureWorks2014\nRetrieves the log ship information for just the database AdventureWorks.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaDbLogShipStatus -SqlInstance sql1 -Primary\nRetrieves the log ship information and only returns the information for the databases on the primary instance.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eTest-DbaDbLogShipStatus -SqlInstance sql1 -Secondary\nRetrieves the log ship information and only returns the information for the databases on the secondary instance.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eTest-DbaDbLogShipStatus -SqlInstance sql1 -Simple\nRetrieves the log ship information and only returns the columns SQL Instance, Database, Instance Type and Status", "Description": "Queries the log shipping monitoring system to check the health of your log shipping configuration across primary and secondary instances.\nThis function connects to your log shipping monitoring instance and examines backup, copy, and restore operations to identify any issues or delays.\n\nMake sure you\u0027re connecting to the monitoring instance of your log shipping infrastructure, as this is where SQL Server stores the consolidated monitoring data.\n\nThe function analyzes timing thresholds for each operation and reports specific problems like missed backups, copy delays, or restore failures.\nWhen everything is functioning normally, you\u0027ll see \"All OK\" in the status output.\nProblem databases will show detailed messages about which operations are behind schedule or failing entirely.", "Links": "https://dbatools.io/Test-DbaDbLogShipStatus", "Synopsis": "Retrieves log shipping status and health information from the monitoring 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 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 log shipped databases to check by exact name. Accepts multiple database names as a comma-separated list.\r\nUse this when you want to focus on specific databases instead of checking all log shipped databases on the monitoring instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific log shipped databases from the status check by exact name. Accepts multiple database names as a comma-separated list.\r\nUse this when you want to check most databases but skip certain ones, such as test or development log shipping configurations.", "", false, "false", "", "" ], [ "Simple", "Returns only essential columns: SqlInstance, Database, InstanceType, and Status instead of all detailed timing information.\r\nUse this for quick health overviews when you don\u0027t need the full backup/copy/restore timing details.", "", false, "false", "False", "" ], [ "Primary", "Returns only status information for databases acting as primary instances in log shipping configurations.\r\nUse this when you want to focus specifically on backup operations and primary-side health monitoring.", "", false, "false", "False", "" ], [ "Secondary", "Returns only status information for databases acting as secondary instances in log shipping configurations.\r\nUse this when you want to focus specifically on copy and restore operations and secondary-side 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": [ "Database", "Owner", "DbOwner" ], "CommandName": "Test-DbaDbOwner", "Name": "Test-DbaDbOwner", "Author": "Michael Fal (@Mike_Fal), mikefal.net", "Syntax": "Test-DbaDbOwner [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject[]\u003e] [-ExcludeDatabase \u003cObject[]\u003e] [-TargetLogin \u003cString\u003e] [-InputObject \u003cDatabase[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database that does not match the target owner. Each object contains the following properties:\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 being checked\r\n- DBState: The current database state (Online, Offline, Restoring, etc.)\r\n- CurrentOwner: The login name of the current database owner\r\n- TargetOwner: The login name of the expected database owner (the compliance target)\r\n- OwnerMatch: Boolean indicating whether the current owner matches the target owner (False for all returned objects, since only non-matching databases are returned)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaDbOwner -SqlInstance localhost\nReturns all databases where the owner does not match \u0027sa\u0027.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaDbOwner -SqlInstance localhost -TargetLogin \u0027DOMAIN\\account\u0027\nReturns all databases where the owner does not match \u0027DOMAIN\\account\u0027.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance localhost -OnlyAccessible | Test-DbaDbOwner\nGets only accessible databases and checks where the owner does not match \u0027sa\u0027.", "Description": "This function compares the current owner of each database against a target login and returns only databases that do NOT match the expected owner. By default, it checks against \u0027sa\u0027 (or the renamed sysadmin account if \u0027sa\u0027 was changed), but you can specify any valid login.\n\nThis addresses a common security compliance requirement where databases should be owned by a specific account rather than individual user accounts. Mismatched ownership can cause issues with scheduled jobs, maintenance plans, and security policies.\n\nThe function automatically detects if the \u0027sa\u0027 account was renamed and uses the actual sysadmin login name. It returns detailed information including current owner, target owner, and ownership status for easy identification of databases requiring ownership changes.\n\nBest Practice reference: http://weblogs.sqlteam.com/dang/archive/2008/01/13/Database-Owner-Troubles.aspx", "Links": "https://dbatools.io/Test-DbaDbOwner", "Synopsis": "Identifies databases with incorrect ownership for security compliance and best practice enforcement.", "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 check for ownership compliance. Accepts wildcards for pattern matching.\r\nUse this when you need to audit ownership for specific databases rather than all databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies databases to skip during the ownership compliance check. Accepts wildcards for pattern matching.\r\nUseful for excluding system databases or databases with intentionally different ownership from standard policy.", "", false, "false", "", "" ], [ "TargetLogin", "Specifies the expected database owner login for compliance checking. Defaults to \u0027sa\u0027 or the renamed sysadmin account if \u0027sa\u0027 was changed.\r\nUse this to enforce organizational standards where databases should be owned by a service account or specific login rather than individual users.", "", false, "false", "", "" ], [ "InputObject", "Accepts database objects piped from Get-DbaDatabase for ownership verification.\r\nUse this to check ownership on a pre-filtered set of databases or when chaining with other database 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", "QueryStore" ], "CommandName": "Test-DbaDbQueryStore", "Name": "Test-DbaDbQueryStore", "Author": "Jess Pomfret (@jpomfret), jesspomfret.com", "Syntax": "Test-DbaDbQueryStore [[-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 Query Store configuration property per database, plus one object per enabled trace flag per instance (on non-Azure servers only).\nQuery Store Configuration Properties (returned for each evaluated database):\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 being evaluated\r\n- Name: The configuration property name (e.g., ActualState, MaxStorageSizeInMB, StaleQueryThresholdInDays)\r\n- Value: The current value of the configuration property\r\n- RecommendedValue: The recommended value for this property based on best practices\r\n- IsBestPractice: Boolean indicating if the current value matches the recommended value (true = best practice compliant)\r\n- Justification: Explanation of why the recommended value is best practice\nTrace Flag Status (returned only on SQL Server instances that are not Azure SQL Database):\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\r\n- Name: The trace flag name (e.g., \"Trace Flag 7745 Enabled\", \"Trace Flag 7752 Enabled\")\r\n- Value: The status of the trace flag (Enabled or Disabled)\r\n- RecommendedValue: The trace flag number (7745 or 7752)\r\n- IsBestPractice: Boolean indicating if the trace flag is enabled as recommended\r\n- Justification: Explanation of why the trace flag should be enabled\nOutput volume: One object per configuration property per database, typically resulting in 9-10 objects per database evaluated (Query Store configuration + trace flags on non-Azure instances).", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaDbQueryStore -SqlInstance localhost\nChecks that Query Store is enabled and meets best practices for all user databases on the localhost machine.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaDbQueryStore -SqlInstance localhost -Database AdventureWorks2017\nChecks that Query Store is enabled and meets best practices for the AdventureWorks2017 database on the localhost machine.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaDbQueryStore -SqlInstance localhost -ExcludeDatabase AdventureWorks2017\nChecks that Query Store is enabled and meets best practices for all user databases except AdventureWorks2017 on the localhost machine.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$databases = Get-DbaDatabase -SqlInstance localhost\nPS C:\\\u003e $databases | Test-DbaDbQueryStore\nChecks that Query Store is enabled and meets best practices for all databases that are piped on the localhost machine.", "Description": "Evaluates Query Store against a set of rules to match best practices. The rules are:\n\n* ActualState = ReadWrite (This means Query Store is enabled and collecting data.)\n* DataFlushIntervalInSeconds = 900 (Recommended to leave this at the default of 900 seconds (15 mins).)\n* MaxPlansPerQuery = 200 (Number of distinct plans per query. 200 is a good starting point for most environments.)\n* MaxStorageSizeInMB = 2048 (How much disk space Query Store will use. 2GB is a good starting point.)\n* QueryCaptureMode = Auto (With auto, queries that are insignificant from a resource utilization perspective, or executed infrequently, are not captured.)\n* SizeBasedCleanupMode = Auto (With auto, as Query Store gets close to out of space it will automatically purge older data.)\n* StaleQueryThresholdInDays = 30 (Determines how much historic data to keep. 30 days is a good value here.)\n* StatisticsCollectionIntervalInMinutes = 30 (Time window that runtime stats will be aggregated. Use 30 unless you have space concerns, then leave at the default (60).)\n* WaitStatsCaptureMode = ON (Adds valuable data when troubleshooting.)\n* Trace Flag 7745 enabled\n* Trace Flag 7752 enabled", "Links": "https://dbatools.io/Test-DbaDbQueryStore", "Synopsis": "Compares Query Store settings against best practices.", "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 test for Query Store best practices. Accepts wildcards for pattern matching.\r\nUse this when you need to evaluate Query Store settings for specific databases instead of all user databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Excludes specific databases from Query Store evaluation. System databases (master, model, tempdb) are automatically excluded.\r\nUse this when you want to test most databases but skip certain ones like development or temporary databases.", "", false, "false", "", "" ], [ "InputObject", "Accepts database objects piped from Get-DbaDatabase, server objects, or instance parameters for testing.\r\nUse this when you want to test Query Store settings on a pre-filtered set of databases or work within 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": [ "DisasterRecovery", "Backup" ], "CommandName": "Test-DbaDbRecoveryModel", "Name": "Test-DbaDbRecoveryModel", "Author": "Claudio Silva (@ClaudioESSilva)", "Syntax": "Test-DbaDbRecoveryModel [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-RecoveryModel] \u003cObject\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database evaluated, providing recovery model configuration and current operational status comparison.\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: The name of the database being validated\r\n- ConfiguredRecoveryModel: The recovery model configured on the database (FULL, SIMPLE, or BULK_LOGGED)\r\n- ActualRecoveryModel: The actual operational recovery model (may differ from configured; FULL databases without a log backup chain report as SIMPLE)\nFor FULL recovery databases, the ActualRecoveryModel will be \"SIMPLE\" if no log backup chain has been established (no backup has been taken since switching to FULL recovery). All other recovery \r\nmodels report their configured value as the actual value.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaDbRecoveryModel -SqlInstance sql2005\nShows all databases where the configured recovery model is FULL and indicates whether or not they are really in FULL recovery model.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaDbRecoveryModel -SqlInstance . | Where-Object {$_.ActualRecoveryModel -ne \"FULL\"}\nOnly shows the databases that are functionally in \u0027simple\u0027 mode.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaDbRecoveryModel -SqlInstance sql2008 -RecoveryModel Bulk_Logged | Sort-Object Server -Descending\nShows all databases where the configured recovery model is BULK_LOGGED and sort them by server name descending\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eTest-DbaDbRecoveryModel -SqlInstance localhost | Select-Object -Property *\nShows all of the properties for the databases that have Full Recovery Model", "Description": "When you switch a database into FULL recovery model, it will behave like a SIMPLE recovery model until a full backup is taken in order to begin a log backup chain. This function identifies the gap between configured and actual recovery model behavior.\n\nFor FULL recovery databases, the function checks if a log backup chain has been established by examining the last_log_backup_lsn in sys.database_recovery_status. Databases without this value are functionally operating in SIMPLE mode despite being configured for FULL recovery.\n\nThis validation is critical for DBAs who need to ensure point-in-time recovery capabilities are actually available, not just configured. It also allows validation of SIMPLE or BULK_LOGGED recovery models on an instance.\n\nInspired by Paul Randal\u0027s post (http://www.sqlskills.com/blogs/paul/new-script-is-that-database-really-in-the-full-recovery-mode/)", "Links": "https://dbatools.io/Test-DbaDbRecoveryModel", "Synopsis": "Validates whether databases are truly operating in their configured recovery model", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "Database", "Specifies which databases to test for recovery model validation. Accepts multiple database names and supports wildcards.\r\nWhen specified, only these databases will be evaluated instead of all databases on the instance.\r\nUseful when you need to verify recovery model behavior for specific databases or troubleshoot particular applications.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies which databases to skip during recovery model validation. Accepts multiple database names and supports wildcards.\r\nUse this to exclude system databases, test databases, or databases you know are properly configured when testing large 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", "", "" ], [ "RecoveryModel", "Specifies which recovery model to validate against configured settings. Valid values are Full, Simple, or Bulk_Logged.\r\nDefaults to Full recovery model, which also checks if databases have established a log backup chain for true point-in-time recovery.\r\nUse Simple or Bulk_Logged when auditing databases that should be configured for those specific recovery models.", "", false, "false", "", "Full,Simple,Bulk_Logged" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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", "OS" ], "CommandName": "Test-DbaDiskAlignment", "Name": "Test-DbaDiskAlignment", "Author": "Constantine Kokkinos (@mobileck), constantinekokkinos.com", "Syntax": "Test-DbaDiskAlignment [-ComputerName] \u003cDbaInstanceParameter[]\u003e [[-Credential] \u003cPSCredential\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [-NoSqlCheck] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns multiple objects per partition (one object per stripe unit tested) for each disk partition on the target server(s).\nProperties:\r\n- ComputerName: Computer name of the target server\r\n- Name: Partition name or drive letter (e.g., \"C:\", \"D:\")\r\n- PartitionSize: Total size of the partition in bytes (DbaSize object providing automatic unit conversion)\r\n- PartitionType: Type of partition (e.g., \"Basic\", \"Logical Disk Manager\" for dynamic disks)\r\n- TestingStripeSize: Stripe unit size being tested in this result (64KB, 128KB, 256KB, 512KB, or 1024KB; DbaSize object)\r\n- OffsetModuluCalculation: Result of (partition offset modulo stripe size) for alignment verification (DbaSize object)\r\n- StartingOffset: Partition starting offset in bytes (DbaSize object; best practice is 1MB/1048576 bytes)\r\n- IsOffsetBestPractice: Boolean indicating if the offset matches a best practice value (64, 128, 256, 512, or 1024 KB)\r\n- IsBestPractice: Boolean indicating if this partition aligns with the tested stripe size (offset % stripe size == 0)\r\n- NumberOfBlocks: Number of blocks in the partition (from Win32_DiskPartition)\r\n- BootPartition: Boolean indicating if this is the system boot partition\r\n- PartitionBlockSize: Block size of the partition in bytes\r\n- IsDynamicDisk: Boolean indicating if disk is managed by Windows Logical Disk Manager; results may be unreliable for dynamic disks\nNote: Multiple objects are returned per partition because the command tests 5 common stripe unit sizes (64KB, 128KB, 256KB, 512KB, 1024KB) for each partition. A single partition returns 5 objects. \r\nThe IsBestPractice property will be true for each stripe size that the partition aligns with.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaDiskAlignment -ComputerName sqlserver2014a\nTests the disk alignment of a single server named sqlserver2014a\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaDiskAlignment -ComputerName sqlserver2014a, sqlserver2014b, sqlserver2014c\nTests the disk alignment of multiple servers", "Description": "Tests disk partition alignment by checking if partition starting offsets align properly with common stripe unit sizes (64KB, 128KB, 256KB, 512KB, 1024KB). Misaligned disk partitions can cause significant SQL Server I/O performance degradation, particularly on high-transaction systems.\n\nThe function connects to Windows computers via CIM and examines each disk partition\u0027s starting offset. It can optionally focus only on partitions that contain SQL Server data or log files. Results show whether each partition follows alignment best practices and calculates the modulo for common stripe sizes.\n\nReturns detailed alignment analysis including partition size, offset calculations, and recommendations. This helps identify storage configuration issues before they impact database performance.\n\nPlease refer to your storage vendor best practices before following any advice below.\n\nBy default issues with disk alignment should be resolved by a new installation of Windows Server 2008, Windows Vista, or later operating systems, but verifying disk alignment continues to be recommended as a best practice.\nWhile some versions of Windows use different starting alignments, if you are starting anew 1MB is generally the best practice offset for current operating systems (because it ensures that the partition offset % common stripe unit sizes == 0 )\n\nCaveats:\n* Dynamic drives (or those provisioned via third party software) may or may not have accurate results when polled by any of the built in tools, see your vendor for details.\n* Windows does not have a reliable way to determine stripe unit Sizes. These values are obtained from vendor disk management software or from your SAN administrator.\n* System drives in versions previous to Windows Server 2008 cannot be aligned, but it is generally not recommended to place SQL Server databases on system drives.", "Links": "https://dbatools.io/Test-DbaDiskAlignment", "Synopsis": "Tests disk partition alignment to identify I/O performance issues that can impact SQL Server.", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the Windows computer(s) to test for disk partition alignment issues. Accepts multiple server names for batch processing.\r\nUse this to identify storage configuration problems that could impact SQL Server I/O performance across your environment.", "", true, "true (ByValue)", "", "" ], [ "Credential", "Specifies an alternate Windows account to use when enumerating drives on the server. May require Administrator privileges. To use:\n$cred = Get-Credential, then pass $cred object to the -Credential parameter.", "", 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", "", "" ], [ "NoSqlCheck", "Tests alignment on all disk partitions instead of limiting the check to only those containing SQL Server data or log files.\r\nUse this when you want a comprehensive disk alignment assessment for the entire server, not just SQL Server storage.", "", 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", "Disk", "OS" ], "CommandName": "Test-DbaDiskAllocation", "Name": "Test-DbaDiskAllocation", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Test-DbaDiskAllocation [-ComputerName] \u003cObject[]\u003e [-NoSqlCheck] [[-SqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per NTFS volume found on the target server.\nDefault properties (when -NoSqlCheck is not specified):\r\n- Server: Computer name of the target server\r\n- Name: Drive letter or volume name (e.g., \"C:\", \"D:\")\r\n- Label: Volume label or name assigned to the drive\r\n- BlockSize: Allocation unit size in bytes (65536 = 64KB is best practice)\r\n- IsSqlDisk: Boolean indicating if the volume contains SQL Server database or log files\r\n- IsBestPractice: Boolean indicating if BlockSize equals 65536 (64KB) - false for system drives\nWhen -NoSqlCheck is specified, the IsSqlDisk property is omitted:\r\n- Server: Computer name of the target server\r\n- Name: Drive letter or volume name\r\n- Label: Volume label\r\n- BlockSize: Allocation unit size in bytes\r\n- IsBestPractice: Boolean indicating if BlockSize equals 65536 (64KB)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaDiskAllocation -ComputerName sqlserver2014a\nScans all disks on server sqlserver2014a for best practice allocation unit size.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaDiskAllocation -ComputerName sqlserver2014 | Select-Output *\nScans all disks on server sqlserver2014a for allocation unit size and returns detailed results for each.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaDiskAllocation -ComputerName sqlserver2014a -NoSqlCheck\nScans all disks not hosting SQL Server data or log files on server sqlserver2014a for best practice allocation unit size.", "Description": "Examines all NTFS volumes on target servers to verify they are formatted with 64KB allocation units, which is the recommended cluster size for optimal SQL Server performance. When checking a single server, returns a simple true/false result. For multiple servers, returns detailed information including server name, disk details, and compliance status for each volume.\n\nThe function can automatically detect SQL Server instances and identify which disks contain database files, helping you focus on storage that directly impacts SQL Server performance. System drives are automatically excluded from best practice validation since they typically don\u0027t require the 64KB allocation unit size.\n\nThis validation is essential during SQL Server deployment planning and storage configuration audits, as improper allocation unit sizes can significantly impact database I/O performance.\n\nReferences:\nhttps://technet.microsoft.com/en-us/library/dd758814(v=sql.100).aspx - \"The performance question here is usually not one of correlation per the formula, but whether the cluster size has been explicitly defined at 64 KB, which is a best practice for SQL Server.\"", "Links": "https://dbatools.io/Test-DbaDiskAllocation", "Synopsis": "Validates disk allocation unit sizes against SQL Server best practice recommendations.", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the target server(s) to examine for disk allocation unit compliance. Accepts multiple server names for bulk validation.\r\nUse this to verify storage configuration across your SQL Server environment during deployment or storage audits.", "", true, "true (ByValue)", "", "" ], [ "NoSqlCheck", "Skips detection of SQL Server database files and examines all NTFS volumes regardless of their SQL Server usage.\r\nUse this when you want to validate allocation units on all drives, not just those containing SQL Server data or log files.", "", false, "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", "Specifies an alternate Windows account to use when enumerating drives on the server. May require Administrator privileges. 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": [ "Diagnostic", "Performance" ], "CommandName": "Test-DbaDiskSpeed", "Name": "Test-DbaDiskSpeed", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Test-DbaDiskSpeed [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-AggregateBy] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns I/O performance statistics aggregated at the file, database, or disk level based on the -AggregateBy parameter. Properties vary by aggregation level.\nDefault properties (all aggregation levels):\r\n- ComputerName: The computer name\r\n- InstanceName: The SQL Server instance name\r\n- SqlInstance: The full SQL instance name (computer\\instance)\r\n- Reads: Number of read operations (summed across files at database/disk level)\r\n- AverageReadStall: Average read latency in milliseconds\r\n- ReadPerformance: Performance rating based on read latency - \"Very Good\" (\u003c 10ms), \"OK\" (\u003c 20ms), \"Slow, Needs Attention\" (\u003c 50ms), or \"Serious I/O Bottleneck\" (\u003e= 50ms)\r\n- Writes: Number of write operations (summed across files at database/disk level)\r\n- AverageWriteStall: Average write latency in milliseconds\r\n- WritePerformance: Performance rating based on write latency - \"Very Good\", \"OK\", \"Slow, Needs Attention\", or \"Serious I/O Bottleneck\"\r\n- Avg Overall Latency: Average combined read/write latency in milliseconds\r\n- Avg Bytes/Read: Average bytes per read operation\r\n- Avg Bytes/Write: Average bytes per write operation\r\n- Avg Bytes/Transfer: Average bytes per I/O transfer operation\nAdditional properties by aggregation level:\nWhen -AggregateBy \u0027File\u0027 (default):\r\n- Database: Database name\r\n- SizeGB: File size in gigabytes\r\n- FileName: File name (Windows: letter+name like \"C:\\...\\file.mdf\", Linux: full path)\r\n- FileID: File ID within the database\r\n- FileType: Type of file - \"Log\" for transaction log, \"Data\" for data files\nWhen -AggregateBy \u0027Database\u0027:\r\n- Database: Database name (aggregated across all files in the database)\nWhen -AggregateBy \u0027Disk\u0027:\r\n- DiskLocation: Disk identifier - Windows letter like \"C\", \"D\"; Linux path prefix like \"/var/opt/mssql\"", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaDiskSpeed -SqlInstance sql2008, sqlserver2012\nTests how disks are performing on sql2008 and sqlserver2012.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaDiskSpeed -SqlInstance sql2008 -Database tempdb\nTests how disks storing tempdb files on sql2008 are performing.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaDiskSpeed -SqlInstance sql2008 -AggregateBy \"File\" -Database tempdb\nReturns the statistics aggregated to the file level. This is the default aggregation level if the -AggregateBy param is omitted. The -Database or -ExcludeDatabase params can be used to filter for \r\nspecific databases.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eTest-DbaDiskSpeed -SqlInstance sql2008 -AggregateBy \"Database\"\nReturns the statistics aggregated to the database/disk level. The -Database or -ExcludeDatabase params can be used to filter for specific databases.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eTest-DbaDiskSpeed -SqlInstance sql2008 -AggregateBy \"Disk\"\nReturns the statistics aggregated to the disk level. The -Database or -ExcludeDatabase params can be used to filter for specific databases.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e$results = @(instance1, instance2) | Test-DbaDiskSpeed\nReturns the statistics for instance1 and instance2 as part of a pipeline command\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003e$databases = @(\u0027master\u0027, \u0027model\u0027)\n$results = Test-DbaDiskSpeed -SqlInstance sql2019 -Database $databases\nReturns the statistics for more than one database specified.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003e$excludedDatabases = @(\u0027master\u0027, \u0027model\u0027)\n$results = Test-DbaDiskSpeed -SqlInstance sql2019 -ExcludeDatabase $excludedDatabases\nReturns the statistics for databases other than the exclusions specified.", "Description": "Queries sys.dm_io_virtual_file_stats to measure read/write latency, throughput, and overall I/O performance for database files. Returns performance ratings from \"Very Good\" to \"Serious I/O Bottleneck\" based on average stall times, helping you quickly identify storage issues that impact SQL Server performance. Can aggregate results by individual file, database, or disk level to pinpoint exactly where I/O problems exist. Essential for troubleshooting slow queries, validating storage upgrades, and proactive performance monitoring.", "Links": "https://dbatools.io/Test-DbaDiskSpeed", "Synopsis": "Analyzes database file I/O performance and identifies storage bottlenecks using SQL Server DMV statistics", "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 in the I/O performance analysis. Accepts database names as strings or arrays.\r\nUse this when you need to focus on specific databases instead of analyzing all databases on the instance.\r\nCommonly used to isolate performance issues in production databases or exclude system databases from analysis.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies which databases to exclude from the I/O performance analysis. Accepts database names as strings or arrays.\r\nUse this when you want to analyze most databases but skip specific ones like development databases or those with known issues.\r\nHelpful for excluding system databases (master, model, msdb) when focusing on user database performance.", "", false, "false", "", "" ], [ "AggregateBy", "Controls how I/O statistics are grouped and summarized in the results. Options are \u0027File\u0027 (default), \u0027Database\u0027, or \u0027Disk\u0027.\r\nUse \u0027File\u0027 for detailed analysis of individual data and log files, \u0027Database\u0027 to compare performance across databases, or \u0027Disk\u0027 to identify storage-level bottlenecks.\r\nFile-level analysis helps pinpoint specific problematic files, while disk-level aggregation is useful for storage capacity planning and identifying hardware issues.", "", false, "false", "File", "Database,Disk,File" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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": "Test-DbaEndpoint", "Name": "Test-DbaEndpoint", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Test-DbaEndpoint [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Endpoint] \u003cString[]\u003e] [[-InputObject] \u003cEndpoint[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per endpoint that has a TCP listener port. Each object contains the connection test results for both TCP and SSL connections.\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- Endpoint: The name of the endpoint being tested\r\n- Port: The TCP listener port for the endpoint\r\n- Connection: TCP connection status - \"Success\" for successful connection, or error message/exception if connection failed\r\n- SslConnection: SSL connection status - \"Success\" for successful SSL connection, \"None\" if no SSL port configured, or error message/exception if SSL connection failed\nEndpoints without TCP listener ports are automatically skipped and do not produce output.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaEndpoint -SqlInstance localhost\nTests all endpoints on the local default SQL Server instance.\nNote that if an endpoint does not have a tcp listener port, it will be skipped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaEndpoint -SqlInstance localhost, sql2016 -Endpoint Mirror | Test-DbaEndpoint\nTests all endpoints named Mirroring on sql2016 and localhost.\nNote that if an endpoint does not have a tcp listener port, it will be skipped.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaEndpoint -SqlInstance localhost, sql2016 -Endpoint Mirror\nTests all endpoints named Mirroring on sql2016 and localhost.\nNote that if an endpoint does not have a tcp listener port, it will be skipped.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eTest-DbaEndpoint -SqlInstance localhost -Verbose\nTests all endpoints on the local default SQL Server instance.\nSee all endpoints that were skipped due to not having a tcp listener port.", "Description": "Tests network connectivity to SQL Server endpoint TCP listener ports by attempting direct socket connections. This function validates that endpoint ports are accessible from the network level, which is essential for troubleshooting database mirroring, Service Broker, and availability group connectivity issues.\n\nThe function tests both standard TCP ports and SSL ports when configured, returning connection status rather than endpoint functionality. Endpoints without TCP listener ports (such as HTTP endpoints) are automatically skipped during testing.\n\nUse this when diagnosing connectivity problems between SQL Server instances or validating firewall rules before setting up features that rely on endpoints.", "Links": "https://dbatools.io/Test-DbaEndpoint", "Synopsis": "Tests network connectivity to SQL Server endpoint TCP listener ports.", "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", "", "" ], [ "Endpoint", "Specifies which endpoint names to test for network connectivity. Accepts multiple endpoint names to filter testing to specific endpoints.\r\nUse this when you need to validate connectivity for particular endpoints like database mirroring, Service Broker, or availability group listeners instead of testing all endpoints on the instance.", "", false, "false", "", "" ], [ "InputObject", "Accepts endpoint objects from Get-DbaEndpoint for pipeline processing. This allows you to filter endpoints first using Get-DbaEndpoint, then test only those specific endpoints.\r\nUse this approach when you need to apply complex filtering logic before testing connectivity, such as testing only endpoints of a specific type or state.", "", 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": [ "Identity", "Table", "Column" ], "CommandName": "Test-DbaIdentityUsage", "Name": "Test-DbaIdentityUsage", "Author": "Brandon Abshire, netnerds.net", "Syntax": "Test-DbaIdentityUsage [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-Threshold] \u003cInt32\u003e] [-ExcludeSystem] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per IDENTITY column found in accessible databases, containing seed consumption analysis and identity range usage metrics.\nDefault display properties (via Select-DefaultView with MaxNumberRows and NumberOfUses excluded):\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 database name containing the table with the identity column\r\n- Schema: The schema name containing the table\r\n- Table: The table name containing the identity column\r\n- Column: The column name with the identity property\r\n- SeedValue: The initial seed value of the identity column (bigint)\r\n- IncrementValue: The increment value for identity generation (bigint)\r\n- LastValue: The last identity value that was assigned (bigint)\r\n- PercentUsed: Percentage of the available seed range consumed based on data type limits (0-100, numeric with 2 decimal places)\nAdditional properties available via Select-Object *:\r\n- MaxNumberRows: Maximum number of rows possible for the data type (tinyint, smallint, int, or bigint)\r\n- NumberOfUses: Number of times the identity value has been used (calculated from seed and last values)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaIdentityUsage -SqlInstance sql2008, sqlserver2012\nCheck identity seeds for servers sql2008 and sqlserver2012.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaIdentityUsage -SqlInstance sql2008 -Database TestDB\nCheck identity seeds on server sql2008 for only the TestDB database\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaIdentityUsage -SqlInstance sql2008 -Database TestDB -Threshold 20\nCheck identity seeds on server sql2008 for only the TestDB database, limiting results to 20% utilization of seed range or higher", "Description": "Scans IDENTITY columns across databases to calculate how much of the available seed range has been consumed based on data type limits (tinyint, smallint, int, bigint). This helps DBAs proactively identify tables approaching identity exhaustion before they hit maximum values and cause application failures. The function calculates percentage used by comparing current identity values against theoretical maximums, so you can plan remediation like reseeding or changing data types before problems occur.", "Links": "https://dbatools.io/Test-DbaIdentityUsage", "Synopsis": "Analyzes IDENTITY column seed consumption and calculates percentage of available range used.", "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 IDENTITY column usage. Accepts multiple database names as an array.\r\nUse this when you need to focus analysis on specific databases rather than scanning all databases on the instance.", "", false, "false", "", "" ], [ "ExcludeDatabase", "The database(s) to exclude - this list is auto-populated from the server", "", false, "false", "", "" ], [ "Threshold", "Allows you to specify a minimum % of the seed range being utilized. This can be used to ignore seeds that have only utilized a small fraction of the range.", "", false, "false", "0", "" ], [ "ExcludeSystem", "Allows you to suppress output on 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": [ "SPN", "Instance", "Utility" ], "CommandName": "Test-DbaInstanceName", "Name": "Test-DbaInstanceName", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Test-DbaInstanceName [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-ExcludeSsrs] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance analyzed, containing instance identification, current vs. expected server names, rename requirements, and any blockers preventing safe rename operations.\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- ServerName: The current configured server name from @@servername\r\n- NewServerName: The expected server name based on hostname and instance name\r\n- RenameRequired: Boolean indicating whether a rename is needed (true when NewServerName differs from ServerName)\r\n- Updatable: Boolean or \"N/A\" - indicates if the instance can be safely renamed (false when blockers exist, true when safe, \"N/A\" when no rename needed)\r\n- Warnings: Warning message about SQL Server Reporting Services needing update if found, or \"N/A\" if not applicable\r\n- Blockers: Array of reasons preventing rename (database mirroring, replication, or remote logins), or \"N/A\" if no blockers exist", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaInstanceName -SqlInstance sqlserver2014a\nReturns ServerInstanceName, SqlServerName, IsEqual and RenameRequired for sqlserver2014a.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaInstanceName -SqlInstance sqlserver2014a, sql2016\nReturns ServerInstanceName, SqlServerName, IsEqual and RenameRequired for sqlserver2014a and sql2016.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaInstanceName -SqlInstance sqlserver2014a, sql2016 -ExcludeSsrs\nReturns ServerInstanceName, SqlServerName, IsEqual and RenameRequired for sqlserver2014a and sql2016, but skips validating if SSRS is installed on both instances.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eTest-DbaInstanceName -SqlInstance sqlserver2014a, sql2016 | Select-Object *\nReturns ServerInstanceName, SqlServerName, IsEqual and RenameRequired for sqlserver2014a and sql2016.\r\nIf a Rename is required, it will also show Updatable, and Reasons if the server name is not updatable.", "Description": "When a SQL Server\u0027s host OS is renamed, the SQL Server should be as well. This helps with Availability Groups and Kerberos.\n\nThis command compares the SQL Server instance name (from @@servername) with the actual hostname and instance combination to determine if they match. When they don\u0027t match, a rename is typically required to prevent authentication issues and ensure proper cluster functionality.\n\nThe function also performs critical safety checks by scanning for conditions that would prevent a safe rename, including active database mirroring, replication configurations (publishing, subscribing, or distribution), and remote login dependencies. Additionally, it identifies SQL Server Reporting Services installations that would require manual updates after a server rename.\n\nUse this before attempting any server rename operations to understand the scope of work involved and potential complications. The detailed output helps you plan the rename process and address blockers beforehand.\n\nhttps://www.mssqltips.com/sqlservertip/2525/steps-to-change-the-server-name-for-a-sql-server-machine/", "Links": "https://dbatools.io/Test-DbaInstanceName", "Synopsis": "Validates SQL Server instance name consistency with the host OS and identifies rename requirements and potential blockers.", "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", "", "" ], [ "ExcludeSsrs", "Skips checking for SQL Server Reporting Services installations that would require manual updates after a server rename.\r\nUse this switch when you know SSRS isn\u0027t installed or when you want to focus only on core SQL Server rename blockers.\r\nWithout this switch, the function will warn about SSRS configurations that need attention during rename 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": [ "Kerberos", "SPN", "Authentication", "Security" ], "CommandName": "Test-DbaKerberos", "Name": "Test-DbaKerberos", "Author": "Claude + Andreas Jordan + Chrissy LeMaire", "Syntax": "Test-DbaKerberos -SqlInstance \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Credential \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]\nTest-DbaKerberos -ComputerName \u003cDbaInstanceParameter[]\u003e [-SqlCredential \u003cPSCredential\u003e] [-Credential \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per diagnostic check performed (typically 20-25+ checks depending on configuration) with the following properties:\n- ComputerName (string) - The name of the computer or SQL Server host that was tested\r\n- InstanceName (string) - The SQL Server instance name if testing an instance; $null if testing at the computer level\r\n- Check (string) - Name of the specific diagnostic check (e.g., \"SPN Registration\", \"Time Synchronization (Client-Server)\", \"DNS Forward Lookup\")\r\n- Category (string) - Category grouping the check: SPN, Time Sync, DNS, Service Account, Authentication, Network, Security Policy, SQL Configuration, or Client\r\n- Status (string) - Result of the check: \"Pass\" (configuration is correct), \"Fail\" (configuration error or problem detected), or \"Warning\" (potential issue or unable to verify)\r\n- Details (string) - Specific details about the check result, including measurements (e.g., time differences in minutes, missing SPNs, port status)\r\n- Remediation (string) - Recommended action to resolve the issue (or \"None\" if the check passed)\nEach check returns a separate PSCustomObject, enabling filtering by Category, Status, or other properties to focus on specific diagnostic areas.\nOutput is returned immediately for each check, enabling real-time monitoring of diagnostic progress.\nThe function may return additional checks for Availability Group listeners if any exist on the instance, each with a check name like \"AG Listener SPN - \u003clistener-name\u003e\".", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaKerberos -SqlInstance sql2016\nPerforms comprehensive Kerberos diagnostic checks for the sql2016 instance, returning pass/fail/warning status for each check with remediation recommendations.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaKerberos -SqlInstance sql2016 -SqlCredential (Get-Credential) -Credential (Get-Credential)\nTests Kerberos configuration using SQL credentials to connect to the instance and separate AD credentials for remote WinRM and Active Directory queries.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaKerberos -SqlInstance sql2016, sql2019\nTests multiple SQL Server instances in a single command.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eTest-DbaKerberos -ComputerName SERVER01 -Credential (Get-Credential)\nTests Kerberos configuration at the computer level using specified credentials for WinRM and AD queries. SQL Server-specific checks are skipped.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaRegServer -SqlInstance sqlcentral | Test-DbaKerberos | Where-Object Status -eq \"Fail\"\nTests all registered servers and returns only the checks that failed, useful for identifying problems across your environment.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eTest-DbaKerberos -SqlInstance sql2016 | Where-Object Category -eq \"SPN\"\nReturns only the SPN-related checks for the specified instance.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eTest-DbaKerberos -SqlInstance sql2016 | Format-Table -AutoSize\nDisplays results in a formatted table for easier reading.", "Description": "This function performs a comprehensive suite of diagnostic checks to troubleshoot Kerberos authentication issues for SQL Server instances. It addresses the most common causes of Kerberos authentication failures including SPN configuration problems, DNS issues, time synchronization errors, service account configuration, network connectivity problems, and security policy misconfigurations.\n\nThe function performs 20 checks across 9 categories (plus additional checks per AG listener):\n\nSPN (1-2+ checks):\n- SPN Registration - Verifies required SPNs are registered using Test-DbaSpn\n- AG Listener SPN - One check per Availability Group listener (if any exist)\n\nTime Sync (2 checks):\n- Client-Server time synchronization (5-minute Kerberos threshold)\n- Server-DC time synchronization\n\nDNS (3 checks):\n- Forward lookup verification\n- Reverse lookup verification\n- CNAME detection (CNAMEs break Kerberos)\n\nService Account (3 checks):\n- Service account type validation (gMSA, domain account, built-in accounts)\n- Account lock status in Active Directory\n- Delegation settings (\"sensitive and cannot be delegated\" flag)\n\nAuthentication (1 check):\n- Current authentication scheme (Kerberos vs NTLM)\n\nNetwork (3 checks):\n- Kerberos port TCP/88 connectivity to DC\n- LDAP port TCP/389 connectivity to DC\n- Kerberos-Kdc port TCP/464 connectivity to DC\n\nSecurity Policy (3 checks):\n- Kerberos encryption types configuration\n- Computer secure channel health\n- Hosts file entries that may override DNS\n\nSQL Configuration (2 checks):\n- SQL Server service account configuration\n- Network protocol configuration (TCP/IP enabled)\n\nClient (1 check):\n- Kerberos ticket cache inspection via klist\n\nEach check returns a structured result with ComputerName, InstanceName, Check, Category, Status (Pass/Fail/Warning), Details, and Remediation recommendations.\n\nNote: When using -ComputerName instead of -SqlInstance, SQL Server-specific checks (service account, authentication scheme, network protocols) are skipped.", "Links": "https://dbatools.io/Test-DbaKerberos", "Synopsis": "Tests Kerberos authentication configuration for SQL Server instances by performing comprehensive diagnostic checks.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances to test Kerberos configuration.\r\nAccepts SQL Server instance names and supports pipeline input for bulk testing.\r\nAll checks including SQL Server-specific checks will be performed.", "", true, "true (ByValue)", "", "" ], [ "ComputerName", "Alternative parameter to specify target computers to test.\r\nUse this when you want to test Kerberos configuration at the computer level rather than for specific SQL instances.\r\nAccepts computer names, IP addresses, or fully qualified domain names.\r\nNote: SQL Server-specific checks will be skipped when using this parameter.", "", true, "true (ByValue)", "", "" ], [ "SqlCredential", "Login to the target SQL Server 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", "Credential for remote WinRM connections and Active Directory queries.\r\nUsed for Invoke-Command calls to remote servers and for querying AD to verify SPN registrations and service account properties.", "", 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": "Test-DbaLastBackup", "Name": "Test-DbaLastBackup", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Test-DbaLastBackup [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [[-Destination] \u003cDbaInstanceParameter\u003e] [[-DestinationSqlCredential] \u003cObject\u003e] [[-DataDirectory] \u003cString\u003e] [[-LogDirectory] \u003cString\u003e] [[-FileStreamDirectory] \u003cString\u003e] [[-Prefix] \u003cString\u003e] [-VerifyOnly] [-NoCheck] [-NoDrop] [-CopyFile] [[-CopyPath] \u003cString\u003e] [[-MaxSize] \u003cInt32\u003e] [[-DeviceType] \u003cString[]\u003e] [-IncludeCopyOnly] [-IgnoreLogBackup] [[-StorageCredential] \u003cString\u003e] [[-InputObject] \u003cDatabase[]\u003e] [[-MaxTransferSize] \u003cInt32\u003e] \r\n[[-BufferCount] \u003cInt32\u003e] [-IgnoreDiffBackup] [[-MaxDop] \u003cInt32\u003e] [-ReuseSourceFolderStructure] [-Checksum] [[-Wait] \u003cInt32\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database tested with the following properties:\n- SourceServer (string) - Name of the source SQL Server instance where the backup originated\r\n- TestServer (string) - Name of the destination SQL Server instance where the restore was tested\r\n- Database (string) - Name of the database being tested\r\n- FileExists (boolean) - Whether the backup files were found and accessible ($true, $false, or $null)\r\n- Size (dbasize) - Total size of the backup files; dbasize object convertible to Bytes, KB, MB, GB, TB\r\n- RestoreResult (string) - Result of the restore operation: \"Success\", \"Failure\", \"Skipped\", or error message\r\n- DbccResult (string) - Result of the DBCC CHECKDB operation: \"Success\", \"Failure\", \"Skipped\", or detailed error\r\n- RestoreStart (datetime) - Date and time when the restore operation started\r\n- RestoreEnd (datetime) - Date and time when the restore operation ended\r\n- RestoreElapsed (timespan as string) - Formatted duration of the restore operation (HH:mm:ss format)\r\n- DbccMaxDop (int) - Maximum degree of parallelism used for DBCC CHECKDB\r\n- DbccStart (datetime) - Date and time when the DBCC CHECKDB operation started\r\n- DbccEnd (datetime) - Date and time when the DBCC CHECKDB operation ended\r\n- DbccElapsed (timespan as string) - Formatted duration of the DBCC CHECKDB operation (HH:mm:ss format)\r\n- BackupDates (datetime array) - Array of backup start times for all backup files in the restore chain\r\n- BackupFiles (string array) - Array of backup file paths used for the restore operation\nOutput is returned immediately for each database processed, enabling real-time progress monitoring of multi-database restore tests.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaLastBackup -SqlInstance sql2016\nDetermines the last full backup for ALL databases, attempts to restore all databases (with a different name and file structure), then performs a DBCC CHECKDB. Once the test is complete, the test \r\nrestore will be dropped.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaLastBackup -SqlInstance sql2016 -Database SharePoint_Config\nDetermines the last full backup for SharePoint_Config, attempts to restore it, then performs a DBCC CHECKDB.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2016, sql2017 | Test-DbaLastBackup\nTests every database backup on sql2016 and sql2017\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaDatabase -SqlInstance sql2016, sql2017 -Database SharePoint_Config | Test-DbaLastBackup\nTests the database backup for the SharePoint_Config database on sql2016 and sql2017\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eTest-DbaLastBackup -SqlInstance sql2016 -Database model, master -VerifyOnly\nSkips performing an action restore of the database and simply verifies the backup using VERIFYONLY option of the restore.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eTest-DbaLastBackup -SqlInstance sql2016 -NoCheck -NoDrop\nSkips the DBCC CHECKDB check. This can help speed up the tests but makes it less tested. The test restores will remain on the server.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eTest-DbaLastBackup -SqlInstance sql2016 -DataDirectory E:\\bigdrive -LogDirectory L:\\bigdrive -MaxSize 10240\nRestores data and log files to alternative locations and only restores databases that are smaller than 10 GB.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eTest-DbaLastBackup -SqlInstance sql2014 -Destination sql2016 -CopyFile\nCopies the backup files for sql2014 databases to sql2016 default backup locations and then attempts restore from there.\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003eTest-DbaLastBackup -SqlInstance sql2014 -Destination sql2016 -CopyFile -CopyPath \"\\\\BackupShare\\TestRestore\\\"\nCopies the backup files for sql2014 databases to sql2016 default backup locations and then attempts restore from there.\n-------------------------- EXAMPLE 10 --------------------------\nPS C:\\\u003eTest-DbaLastBackup -SqlInstance sql2016 -NoCheck -MaxTransferSize 4194302 -BufferCount 24\nDetermines the last full backup for ALL databases, attempts to restore all databases (with a different name and file structure).\r\nThe Restore will use more memory for reading the backup files. Do not set these values to high or you can get an Out of Memory error!!!\r\nWhen running the restore with these additional parameters and there is other server activity it could affect server OLTP performance. Please use with caution.\r\nPrior to running, you should check memory and server resources before configure it to run automatically.\r\nMore information:\r\nhttps://www.mssqltips.com/sqlservertip/4935/optimize-sql-server-database-restore-performance/\n-------------------------- EXAMPLE 11 --------------------------\nPS C:\\\u003eTest-DbaLastBackup -SqlInstance sql2016 -MaxDop 4\nThe use of the MaxDop parameter will limit the number of processors used during the DBCC command\n-------------------------- EXAMPLE 12 --------------------------\nPS C:\\\u003eTest-DbaLastBackup -SqlInstance sql2016 -Database model, master -VerifyOnly -Checksum\nVerifies the backup files using RESTORE VERIFYONLY WITH CHECKSUM. This will fail if the backups do not contain checksums, ensuring that backups follow best practices.\n-------------------------- EXAMPLE 13 --------------------------\nPS C:\\\u003eTest-DbaLastBackup -SqlInstance sql2016 -Wait 5\nTests all database backups on sql2016 and waits 5 seconds between each database restore test. This helps prevent I/O errors on checkpoint files when restoring to network shares.\n-------------------------- EXAMPLE 14 --------------------------\nPS C:\\\u003eTest-DbaLastBackup -SqlInstance sql2022 -Database Sales -StorageCredential \"S3Credential\"\nTests the last backup of the Sales database where backups are stored in S3-compatible storage. Requires SQL Server 2022 or later for S3 support.", "Description": "Restores all or some of the latest backups and performs a DBCC CHECKDB.\n\n1. Gathers information about the last full backups\n2. Restores the backups to the Destination with a new name. If no Destination is specified, the originating SQL Server instance wil be used.\n3. The database is restored as \"dbatools-testrestore-$databaseName\" by default, but you can change dbatools-testrestore to whatever you would like using -Prefix\n4. The internal file names are also renamed to prevent conflicts with original database\n5. A DBCC CHECKDB is then performed\n6. And the test database is finally dropped", "Links": "https://dbatools.io/Test-DbaLastBackup", "Synopsis": "Quickly and easily tests the last set of full backups for a server.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. Unlike many of the other commands, you cannot specify more than one server.", "", 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 include in the backup test. Accepts wildcards for pattern matching.\r\nUse this to limit testing to specific databases instead of all databases on the instance.\r\nHelpful when you only want to verify critical databases or troubleshoot specific backup issues.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies databases to exclude from backup testing. Accepts wildcards for pattern matching.\r\nUse this to skip non-critical databases, large databases, or databases with known backup issues.\r\nCommonly used to exclude system databases or databases that would take too long to test.", "", false, "false", "", "" ], [ "Destination", "Specifies the SQL Server instance where test restores will be performed. Defaults to the source server if not specified.\r\nUse this when you want to test restores on a different server, such as isolating test operations from production workloads.\r\nWhen using a different destination server, backup files must be accessible from that server via shared storage or use -CopyFile.", "", false, "false", "", "" ], [ "DestinationSqlCredential", "Credentials for connecting to the destination SQL Server instance when different from the source.\r\nUse this when the destination server requires different authentication than the source server.\r\nAccepts PowerShell credentials (Get-Credential) and supports Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated.", "", false, "false", "", "" ], [ "DataDirectory", "Specifies the directory where restored database data files (.mdf, .ndf) will be placed. Defaults to the SQL Server\u0027s default data directory.\r\nUse this when you need to direct test restores to specific storage, such as faster drives for testing or isolated storage locations.\r\nThe SQL Server service account must have write permissions to this directory.", "", false, "false", "", "" ], [ "LogDirectory", "Specifies the directory where restored database log files (.ldf) will be placed. Defaults to the SQL Server\u0027s default log directory.\r\nUse this when you want to separate test database logs from production logs or direct them to faster storage for testing.\r\nThe SQL Server service account must have write permissions to this directory.", "", false, "false", "", "" ], [ "FileStreamDirectory", "Specifies the directory where FileStream data will be restored for databases that use FileStream storage.\r\nUse this when testing databases with FileStream-enabled tables to ensure the FileStream data is properly restored and accessible.\r\nRequired only for databases that contain FileStream data and when not using -ReuseSourceFolderStructure.", "", false, "false", "", "" ], [ "Prefix", "Specifies the naming prefix for test databases. Defaults to \u0027dbatools-testrestore-\u0027 resulting in names like \u0027dbatools-testrestore-MyDB\u0027.\r\nUse this to customize test database naming for organizational standards or to avoid naming conflicts.\r\nChoose prefixes that clearly identify databases as temporary test restores.", "", false, "false", "dbatools-testrestore-", "" ], [ "VerifyOnly", "Performs backup verification only without actually restoring the database. Uses T-SQL RESTORE VERIFYONLY command.\r\nUse this for faster backup validation when you only need to confirm backup file integrity without full restore testing.\r\nSkips DBCC CHECKDB since no actual database is restored.", "", false, "false", "False", "" ], [ "NoCheck", "Skips the DBCC CHECKDB operation after restoring the test database.\r\nUse this to speed up the testing process when you only need to verify that backups can be restored successfully.\r\nReduces testing time but provides less thorough validation of database integrity.", "", false, "false", "False", "" ], [ "NoDrop", "Prevents the test database from being automatically dropped after the test completes.\r\nUse this when you need to examine the restored database manually or perform additional testing.\r\nRemember to manually clean up test databases later to avoid storage issues.", "", false, "false", "False", "" ], [ "CopyFile", "Copies backup files to the destination server\u0027s default backup directory before attempting the restore.\r\nUse this when backup files are not accessible from the destination server, such as local backups on different servers.\r\nCannot be used with Azure SQL Database backups.", "", false, "false", "False", "" ], [ "CopyPath", "Specifies the destination directory where backup files will be copied when using -CopyFile. Defaults to the destination server\u0027s default backup directory.\r\nUse this to control where backup files are temporarily stored during testing, such as directing them to faster storage.\r\nPath must be accessible to the destination SQL Server service account.", "", false, "false", "", "" ], [ "MaxSize", "Maximum database size in MB. Databases with backups larger than this value will be skipped.\r\nUse this to avoid testing extremely large databases that would consume excessive time or storage resources.\r\nHelps focus testing on databases that can be practically tested within available resources.", "", false, "false", "0", "" ], [ "DeviceType", "Filters backups by device type such as \u0027Disk\u0027, \u0027Tape\u0027, or \u0027Virtual Device\u0027. Accepts multiple values.\r\nUse this when you need to test only backups from specific backup devices or exclude certain device types.\r\nCommonly used to test only disk backups or exclude tape backups that may be offline.", "", false, "false", "", "" ], [ "IncludeCopyOnly", "Includes copy-only backups when determining the most recent backup to test.\r\nUse this when you want to test copy-only backups that were created for specific purposes like migrations or testing.\r\nCopy-only backups don\u0027t break the backup chain but are normally excluded from \u0027last backup\u0027 queries.", "", false, "false", "False", "" ], [ "IgnoreLogBackup", "Skips transaction log backups during restore, stopping at the most recent full or differential backup.\r\nUse this for faster testing when point-in-time recovery precision isn\u0027t critical for the test.\r\nResults in some data loss compared to a complete restore chain but significantly reduces testing time.", "", false, "false", "False", "" ], [ "StorageCredential", "Specifies the name of the SQL Server credential for accessing cloud storage where backups are stored.\r\nFor Azure: Use credentials containing the storage account access key or configured for SAS authentication.\r\nFor S3: Use credentials with Identity = \u0027S3 Access Key\u0027 and Secret = \u0027AccessKeyID:SecretKeyID\u0027. Requires SQL Server 2022 or later.\r\nThe credential must already exist on the destination SQL Server instance.", "AzureCredential,S3Credential", false, "false", "", "" ], [ "InputObject", "Accepts database objects from Get-DbaDatabase for pipeline processing.\r\nUse this to test backups for databases selected through Get-DbaDatabase filtering options.\r\nEnables complex database selection scenarios beyond simple name matching.", "", false, "true (ByValue)", "", "" ], [ "MaxTransferSize", "Sets the data transfer unit size for backup restoration. Must be a multiple of 64KB with a maximum of 4GB.\r\nUse this to optimize restore performance by increasing buffer size, especially for large databases on high-speed storage.\r\nHigher values can improve performance but consume more memory during the restore operation.", "", false, "false", "0", "" ], [ "BufferCount", "Specifies the number of I/O buffers used during the restore operation.\r\nUse this to optimize restore performance by controlling memory allocation for the restore process.\r\nHigher values can improve performance but consume more memory, so balance against other server activity.", "", false, "false", "0", "" ], [ "IgnoreDiffBackup", "Skips differential backups during restore, using only full and transaction log backups.\r\nUse this to test restore scenarios that don\u0027t rely on differential backups or when differential backups are suspected to be problematic.\r\nMay significantly increase restore time due to processing more transaction log backups.", "", false, "false", "False", "" ], [ "MaxDop", "Sets the maximum degree of parallelism for the DBCC CHECKDB operation. Limits the number of parallel processes used.\r\nUse this to control resource usage during integrity checks, especially on busy servers or when testing multiple databases.\r\nLower values reduce CPU usage but increase DBCC runtime.", "", false, "false", "0", "" ], [ "ReuseSourceFolderStructure", "Maintains the original file paths and directory structure from the source database during restore.\r\nUse this when testing databases that have specific file location requirements or when simulating exact production restore scenarios.\r\nEnsures the destination server has the same directory structure as the source or the restore will fail.", "", false, "false", "False", "" ], [ "Checksum", "Enables backup checksum verification during restore operations. When used with -VerifyOnly, forces the RESTORE VERIFYONLY command to use WITH CHECKSUM.\r\nUse this to ensure backup files contain checksums and validate them during testing, following backup best practices.\r\nWithout this parameter, SQL Server verifies checksums if present but doesn\u0027t fail if checksums are missing. With this parameter, the operation fails if checksums are not present in the backup.", "", false, "false", "False", "" ], [ "Wait", "Specifies the number of seconds to wait between each database restore test.\r\nUse this to prevent I/O errors on checkpoint files by allowing time for cleanup between restore operations.\r\nHelpful when restoring to network shares or storage systems that need additional time to release file handles.", "", 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", "" ], [ "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": "LinkedServer", "CommandName": "Test-DbaLinkedServerConnection", "Name": "Test-DbaLinkedServerConnection", "Author": "Thomas LaRock, thomaslarock.com", "Syntax": "Test-DbaLinkedServerConnection [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Dataplat.Dbatools.Validation.LinkedServerResult\nReturns one object per linked server on each target instance, containing the connection test result and status information.\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- Name: The name of the linked server\r\n- DataSource: The data source or connection string of the linked server\r\n- Connectivity: Boolean indicating if the linked server connection was successful (true = connected, false = failed)\r\n- Result: Connection test result message - either \"Success\" or the specific error message explaining the connection failure", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaLinkedServerConnection -SqlInstance DEV01\nTest all Linked Servers for the SQL Server instance DEV01\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaLinkedServerConnection -SqlInstance sql2016 | Out-File C:\\temp\\results.txt\nTest all Linked Servers for the SQL Server instance sql2016 and output results to file\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaLinkedServerConnection -SqlInstance sql2016, sql2014, sql2012\nTest all Linked Servers for the SQL Server instances sql2016, sql2014 and sql2012\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$servers = \"sql2016\",\"sql2014\",\"sql2012\"\nPS C:\\\u003e $servers | Test-DbaLinkedServerConnection -SqlCredential sqladmin\nTest all Linked Servers for the SQL Server instances sql2016, sql2014 and sql2012 using SQL login credentials\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$servers = \"sql2016\",\"sql2014\",\"sql2012\"\nPS C:\\\u003e $servers | Get-DbaLinkedServer | Test-DbaLinkedServerConnection\nTest all Linked Servers for the SQL Server instances sql2016, sql2014 and sql2012", "Description": "Validates that linked servers are properly configured and accessible by attempting to establish connections to each one. This function iterates through all linked servers on the target instances and uses SQL Server\u0027s built-in TestConnection() method to verify connectivity. Returns detailed results including success/failure status and specific error messages for troubleshooting connection issues. Essential for validating linked server configurations after setup, during maintenance windows, or when diagnosing cross-server query failures.", "Links": "https://dbatools.io/Test-DbaLinkedServerConnection", "Synopsis": "Tests connectivity to all linked servers on specified 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": "Login", "CommandName": "Test-DbaLoginPassword", "Name": "Test-DbaLoginPassword", "Author": "Peter Samuelsson", "Syntax": "Test-DbaLoginPassword [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Login] \u003cString[]\u003e] [[-Dictionary] \u003cString[]\u003e] [[-InputObject] \u003cLogin[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL login with a weak password identified during testing. If no logins have weak passwords, nothing is returned.\nProperties:\r\n- ComputerName: The computer name of the SQL Server instance\r\n- InstanceName: The SQL Server instance name (defaults to \u0027MSSQLSERVER\u0027 for default instance)\r\n- SqlInstance: The full SQL Server instance name\r\n- SqlLogin: The name of the SQL login with weak password\r\n- WeakPassword: String value \u0027True\u0027 indicating weak password was found\r\n- Password: The weak password that matched (with @@Name placeholder replaced by actual login name for username-based matches)\r\n- Disabled: Boolean indicating if the login is currently disabled\r\n- CreatedDate: DateTime when the login was created\r\n- ModifiedDate: DateTime when the login was last modified\r\n- DefaultDatabase: The default database for the login", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaLoginPassword -SqlInstance Dev01\nTest all SQL logins that the password is null or same as username on SQL server instance Dev01\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaLoginPassword -SqlInstance Dev01 -Login sqladmin\nTest the \u0027sqladmin\u0027 SQL login that the password is null or same as username on SQL server instance Dev01\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaLoginPassword -SqlInstance Dev01 -Dictionary Test1,test2\nTest all SQL logins that the password is null, same as username or Test1,Test2 on SQL server instance Dev0\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaLogin -SqlInstance \"sql2017\",\"sql2016\" | Test-DbaLoginPassword\nTest all logins on sql2017 and sql2016\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$servers | Get-DbaLogin | Out-GridView -PassThru | Test-DbaLoginPassword\nTest selected logins on all servers in the $servers variable", "Description": "Tests SQL Server authentication logins for common weak password patterns using the PWDCOMPARE() function to validate password hashes stored in sys.sql_logins. This security audit function helps identify authentication vulnerabilities by checking for empty passwords, passwords that match the username, and passwords from a custom dictionary you provide. Use this during security reviews to find logins that could be easily compromised and require immediate password changes.", "Links": "https://dbatools.io/Test-DbaLoginPassword", "Synopsis": "Identifies SQL Server logins with weak passwords including empty, username-matching, or dictionary-based passwords", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The SQL Server instance you\u0027re checking logins on. You must have sysadmin access and server version must be SQL Server version 2008 or higher.", "", false, "false", "", "" ], [ "SqlCredential", "Allows you to login to servers using SQL Logins instead of Windows Authentication (AKA Integrated or Trusted). To use:\n$scred = Get-Credential, then pass $scred object to the -SqlCredential parameter.\nWindows Authentication will be used if SqlCredential is not specified. SQL Server does not accept Windows credentials being passed as credentials.\nTo connect as a different Windows user, run PowerShell as that user.", "", false, "false", "", "" ], [ "Login", "Specifies which SQL authentication logins to test for weak passwords instead of testing all SQL logins on the instance.\r\nAccepts single login names, arrays of login names, or wildcard patterns for filtering specific accounts.\r\nUseful when you want to focus testing on high-privilege logins or specific service accounts that need immediate attention.", "", false, "false", "", "" ], [ "Dictionary", "Specifies additional passwords to test against all SQL authentication logins using PWDCOMPARE().\r\nUse this to check for organization-specific weak passwords like company names, common words, or previously breached passwords.\r\nThese passwords are tested in addition to the default checks for empty passwords and username-matching passwords.", "", false, "false", "", "" ], [ "InputObject", "Accepts login objects from Get-DbaLogin to test for weak passwords, enabling pipeline operations and complex filtering scenarios.\r\nUse this when you need to filter logins by properties like creation date, last login time, or server roles before testing passwords.\r\nCommonly used with Get-DbaLogin to test logins across multiple servers or with specific criteria that can\u0027t be achieved with the Login parameter alone.", "", 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": "SMO", "CommandName": "Test-DbaManagementObject", "Name": "Test-DbaManagementObject", "Author": "Ben Miller (@DBAduck), dbaduck.com", "Syntax": "Test-DbaManagementObject [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [[-Credential] \u003cPSCredential\u003e] [-VersionNumber] \u003cInt32[]\u003e [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per queried SMO version on each target computer.\nProperties:\r\n- ComputerName: The name of the computer where the SMO assembly check was performed\r\n- Version: The major version number of SQL Server SMO assembly being checked (e.g., 13 for SQL 2016, 15 for SQL 2019)\r\n- Exists: Boolean indicating whether the specified SMO assembly version is installed in the Global Assembly Cache (True if found, False if not found)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaManagementObject -VersionNumber 13\nReturns True if the version exists, if it does not exist it will return False", "Description": "Checks the Global Assembly Cache (GAC) for Microsoft.SqlServer.Smo assemblies of specified versions. This function helps DBAs ensure the required SMO libraries are available before executing scripts that depend on specific SQL Server client tool versions. Returns detailed results showing which versions exist on each target computer, preventing runtime errors when SMO-dependent automation runs against systems with missing or incompatible client libraries.", "Links": "https://dbatools.io/Test-DbaManagementObject", "Synopsis": "Verifies if specific SQL Server Management Objects (SMO) library versions are installed on target computers.", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the target computer(s) to check for SMO assemblies. Accepts pipeline input and defaults to the local computer.\r\nUse this when verifying SMO library versions across multiple servers in your environment.", "", 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", "Specifies the major version number(s) of SQL Server SMO assemblies to verify in the Global Assembly Cache.\r\nCommon values include 11 (SQL 2012), 12 (SQL 2014), 13 (SQL 2016), 14 (SQL 2017), 15 (SQL 2019), and 16 (SQL 2022).", "", 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", "" ] ] }, { "Tags": [ "MaxDop", "Utility" ], "CommandName": "Test-DbaMaxDop", "Name": "Test-DbaMaxDop", "Author": "Claudio Silva (@claudioessilva)", "Syntax": "Test-DbaMaxDop [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance. For SQL Server 2016 and higher, also returns one object per user database with database-level MAXDOP settings.\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 format)\r\n- Database: The database name (N/A for instance-level results, database name for SQL 2016+ database-level results)\r\n- DatabaseMaxDop: The database-level MAXDOP setting (N/A for instance-level results, numeric for SQL 2016+)\r\n- CurrentInstanceMaxDop: The current instance-level MAXDOP configuration value (0 = unlimited, or specific number)\r\n- RecommendedMaxDop: The Microsoft-recommended MAXDOP value based on CPU cores and NUMA topology\r\n- Notes: Configuration guidance notes indicating whether the current setting matches recommendations\nAdditional properties available (via Select-Object *):\r\n- InstanceVersion: The full version of SQL Server (e.g., \"11.0.1234.56\")\r\n- NumaNodes: The number of NUMA nodes detected on the instance\r\n- NumberOfCores: The total number of logical processor cores visible to SQL Server", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaMaxDop -SqlInstance sql2008, sqlserver2012\nGet Max DOP setting for servers sql2008 and sqlserver2012 and also the recommended one.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaMaxDop -SqlInstance sql2014 | Select-Object *\nShows Max DOP setting for server sql2014 with the recommended value. Piping the output to Select-Object * will also show the \u0027NumaNodes\u0027 and \u0027NumberOfCores\u0027 of each instance\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaMaxDop -SqlInstance sqlserver2016 | Select-Object *\nGet Max DOP setting for servers sql2016 with the recommended value. Piping the output to Select-Object * will also show the \u0027NumaNodes\u0027 and \u0027NumberOfCores\u0027 of each instance. Because it is an 2016 \r\ninstance will be shown \u0027InstanceVersion\u0027, \u0027Database\u0027 and \u0027DatabaseMaxDop\u0027 columns.", "Description": "Analyzes your SQL Server\u0027s Max Degree of Parallelism (MAXDOP) settings and compares them against Microsoft\u0027s recommended values based on your server\u0027s hardware configuration. This function examines CPU cores, NUMA topology, and SQL Server version to calculate optimal MAXDOP settings for query performance.\n\nThe function helps you identify instances where MAXDOP may be misconfigured, which can lead to poor query performance, excessive parallelism overhead, or CXPACKET waits. It automatically detects single vs multi-NUMA configurations and applies version-specific calculation rules.\n\nFor SQL Server 2016 and higher, the function also examines database-level MAXDOP settings, since these versions support per-database parallelism configuration that can override instance-level settings.\n\nResults include current settings, recommended values, and guidance notes about whether changes should be considered. The recommendations follow Microsoft\u0027s official guidelines but include warnings for scenarios where custom MAXDOP values may be intentionally set for specific applications.\n\nInspired by Sakthivel Chidambaram\u0027s MAXDOP Calculator methodology and Microsoft\u0027s official guidance (KB 2806535).\n\nMore info:\nhttps://support.microsoft.com/en-us/kb/2806535\nhttps://blogs.msdn.microsoft.com/sqlsakthi/2012/05/23/wow-we-have-maxdop-calculator-for-sql-server-it-makes-my-job-easier/", "Links": "https://dbatools.io/Test-DbaMaxDop", "Synopsis": "Tests SQL Server MAXDOP configuration against recommended values based on CPU cores and NUMA topology.", "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": [ "MaxMemory", "Memory" ], "CommandName": "Test-DbaMaxMemory", "Name": "Test-DbaMaxMemory", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Test-DbaMaxMemory [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance analyzed, providing memory configuration analysis.\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 format)\r\n- InstanceCount: The number of running SQL Engine instances detected on the server\r\n- Total: Total system memory in megabytes (MB)\r\n- MaxValue: Current max server memory setting in megabytes (MB)\r\n- RecommendedValue: Calculated recommended max server memory in megabytes (MB) based on Jonathan Kehayias\u0027s algorithm, accounting for OS reserve and instance count\nAdditional properties available:\r\n- Server: Reference to the SMO Server object for the instance, allowing further server-specific queries or operations", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaMaxMemory -SqlInstance sqlcluster,sqlserver2012\nCalculate the \u0027Max Server Memory\u0027 for SQL Server instances sqlcluster and sqlserver2012\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eGet-DbaRegServer -SqlInstance sqlcluster | Test-DbaMaxMemory\nCalculate the \u0027Max Server Memory\u0027 settings for all servers within the SQL Server Central Management Server \"sqlcluster\"\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaRegServer -SqlInstance sqlcluster | Test-DbaMaxMemory | Where-Object { $_.MaxValue -gt $_.Total } | Set-DbaMaxMemory\nFind all servers in CMS that have Max SQL memory set to higher than the total memory of the server (think 2147483647) and set it to recommended value.", "Description": "Analyzes server memory and SQL Server instances to calculate optimal max memory configuration settings. Uses a tiered algorithm that reserves appropriate memory for the operating system based on total server memory, accounting for multiple SQL instances and other SQL services like SSAS, SSRS, or SSIS. Compares current max memory settings against recommended values to help identify misconfigured servers that could cause memory pressure or performance issues. Based on Jonathan Kehayias\u0027s memory calculation methodology, this provides general recommendations that should be validated against your specific environment and workload requirements.", "Links": "https://dbatools.io/Test-DbaMaxMemory", "Synopsis": "Calculates recommended SQL Server max memory settings to prevent OS memory pressure and optimize 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", "", "" ], [ "Credential", "Windows Credential with permission to log on to the server running the SQL 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": "Migration", "CommandName": "Test-DbaMigrationConstraint", "Name": "Test-DbaMigrationConstraint", "Author": "Claudio Silva (@ClaudioESSilva)", "Syntax": "Test-DbaMigrationConstraint [-Source] \u003cDbaInstanceParameter\u003e [[-SourceSqlCredential] \u003cPSCredential\u003e] [-Destination] \u003cDbaInstanceParameter\u003e [[-DestinationSqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cObject[]\u003e] [[-ExcludeDatabase] \u003cObject[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per database validated, providing detailed migration compatibility assessment.\nProperties:\r\n- SourceInstance: Name of the source SQL Server instance\r\n- DestinationInstance: Name of the destination SQL Server instance\r\n- SourceVersion: Source server edition, product level, and version number (e.g., \"Enterprise SP1 (13.0.5850.14)\")\r\n- DestinationVersion: Destination server edition, product level, and version number\r\n- Database: Name of the database being validated\r\n- FeaturesInUse: Comma-separated list of enterprise edition features detected (e.g., \"ChangeCapture,XTP\"), or empty string if none\r\n- IsMigratable: Boolean indicating whether the database can be successfully migrated to the destination (True/False)\r\n- Notes: Human-readable message explaining the migration status, including specific reasons if the database cannot be migrated (e.g., FileStream configuration mismatch, Express edition \r\nincompatibilities, or missing features on destination)", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaMigrationConstraint -Source sqlserver2014a -Destination sqlcluster\nAll databases on sqlserver2014a will be verified for features in use that can\u0027t be supported on sqlcluster.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaMigrationConstraint -Source sqlserver2014a -Destination sqlcluster -SourceSqlCredential $cred\nAll databases will be verified for features in use that can\u0027t be supported on the destination server. SQL credentials are used to authenticate against sqlserver2014a and Windows Authentication is \r\nused for sqlcluster.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaMigrationConstraint -Source sqlserver2014a -Destination sqlcluster -Database db1\nOnly db1 database will be verified for features in use that can\u0027t be supported on the destination server.", "Description": "Prevents migration failures by identifying databases that use features incompatible with the destination SQL Server edition.\nThis function queries sys.dm_db_persisted_sku_features to detect enterprise-level features that would cause migration issues when moving from higher editions (Enterprise/Developer) to lower ones (Standard/Express).\n\nCommon migration scenarios this helps validate include moving databases from development environments running Developer edition to production Standard edition, or consolidating databases from Enterprise to Standard during license optimization.\nThe function also checks FILESTREAM configuration compatibility and validates that Change Data Capture (CDC) isn\u0027t used when migrating to Express edition, since Express lacks SQL Server Agent.\n\nValidation works on SQL Server 2008 and higher versions using the sys.dm_db_persisted_sku_features DMV.\nSupported editions include Enterprise, Developer, Evaluation, Standard, and Express.\n\nSQL Server 2016 SP1 introduced feature parity across editions for many capabilities, so this function accounts for those changes when validating post-SP1 destinations.\nFor more details see: https://blogs.msdn.microsoft.com/sqlreleaseservices/sql-server-2016-service-pack-1-sp1-released/\n\nThe -Database parameter is auto-populated for command-line completion.", "Links": "https://dbatools.io/Test-DbaMigrationConstraint", "Synopsis": "Validates database migration compatibility between SQL Server instances by checking for edition-specific features.", "Availability": "Windows, Linux, macOS", "Params": [ [ "Source", "Specifies the source SQL Server instance containing databases to validate for migration compatibility.\r\nMust be SQL Server 2008 or higher since the function uses sys.dm_db_persisted_sku_features DMV to detect edition-specific features.\r\nRequires sysadmin access to query system views and database metadata.", "", true, "true (ByValue)", "", "" ], [ "SourceSqlCredential", "Credentials for authenticating to the source SQL Server instance when Windows Authentication is not available.\r\nUse this when running the function with a different account than your current Windows login, or when connecting to SQL instances that require SQL Authentication.\r\nCreate with Get-Credential or pass stored credential objects.", "", false, "false", "", "" ], [ "Destination", "Specifies the destination SQL Server instance where databases will be migrated to.\r\nThe function validates that database features are compatible with this target server\u0027s edition (Enterprise, Developer, Standard, or Express).\r\nMust be SQL Server 2008 or higher and requires sysadmin access to check server edition and configuration settings like FileStream access level.", "", true, "false", "", "" ], [ "DestinationSqlCredential", "Credentials for authenticating to the destination SQL Server instance when Windows Authentication is not available.\r\nRequired when the destination server uses different authentication than your current context, or when testing migrations across domains.\r\nUse Get-Credential to create or pass existing credential objects.", "", false, "false", "", "" ], [ "Database", "Specifies which databases to validate for migration compatibility.\r\nWhen omitted, checks all user databases on the source instance (excludes system databases master, msdb, tempdb).\r\nUse this to focus validation on specific databases when planning selective migrations or troubleshooting particular database features.", "", false, "false", "", "" ], [ "ExcludeDatabase", "Specifies databases to skip during the migration validation process.\r\nUseful when you know certain databases won\u0027t be migrated or when focusing validation efforts on a subset of databases.\r\nCommonly used to exclude test databases, archived databases, or databases with known compatibility 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": [ "Performance", "Network" ], "CommandName": "Test-DbaNetworkLatency", "Name": "Test-DbaNetworkLatency", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Test-DbaNetworkLatency [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Query] \u003cString\u003e] [[-Count] \u003cInt32\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance queried, with latency measurements comparing total time vs. query execution time to isolate network delays.\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- ExecutionCount: The number of times the query was executed (same as -Count parameter)\r\n- Total: Total elapsed time for all executions (including connection and network overhead)\r\n- Average: Average elapsed time per query execution\r\n- ExecuteOnlyTotal: Total time spent in query execution only (excluding network overhead)\r\n- ExecuteOnlyAverage: Average query execution time per iteration\r\n- NetworkOnlyTotal: Time spent on network latency and connection overhead\nAll time properties are returned as prettytimespan objects that display in human-readable format (ms, sec, etc.).\nThe difference between Total and ExecuteOnlyTotal represents network latency and connection establishment time, helping DBAs identify whether performance issues originate from the network or the SQL \r\nServer instance itself.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaNetworkLatency -SqlInstance sqlserver2014a, sqlcluster\nTests the round trip return of \"SELECT TOP 100 * FROM INFORMATION_SCHEMA.TABLES\" on sqlserver2014a and sqlcluster using Windows credentials.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaNetworkLatency -SqlInstance sqlserver2014a -SqlCredential $cred\nTests the execution results return of \"SELECT TOP 100 * FROM INFORMATION_SCHEMA.TABLES\" on sqlserver2014a using SQL credentials.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaNetworkLatency -SqlInstance sqlserver2014a, sqlcluster, sqlserver -Query \"select top 10 * from otherdb.dbo.table\" -Count 10\nTests the execution results return of \"select top 10 * from otherdb.dbo.table\" 10 times on sqlserver2014a, sqlcluster, and sqlserver using Windows credentials.", "Description": "This function is intended to help measure SQL Server network latency by establishing a connection and executing a simple query. This is a better than a simple ping because it actually creates the connection to the SQL Server and measures the time required for only the entire routine, but the duration of the query as well how long it takes for the results to be returned.\n\nBy default, this command will execute \"SELECT TOP 100 * FROM INFORMATION_SCHEMA.TABLES\" three times. It will then output how long the entire connection and command took, as well as how long *only* the execution of the command took.\n\nThis allows you to see if the issue is with the connection or the SQL Server itself.", "Links": "https://dbatools.io/Test-DbaNetworkLatency", "Synopsis": "Tests how long a query takes to return from SQL Server", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The SQL Server you want to run the test on.", "", 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", "", "" ], [ "Query", "Specifies the SQL query to execute for latency testing. Defaults to \"SELECT TOP 100 * FROM INFORMATION_SCHEMA.TABLES\" which provides consistent results across all SQL Server versions.\r\nUse a custom query when you need to test latency with queries similar to your actual workload, or when testing against specific databases using fully qualified object names.", "", false, "false", "SELECT TOP 100 * FROM INFORMATION_SCHEMA.TABLES", "" ], [ "Count", "Specifies how many times the query should be executed to calculate average latency measurements. Defaults to 3 executions.\r\nIncrease this value when you need more precise average measurements or when testing intermittent network issues. Higher counts provide better statistical accuracy but take longer to complete.", "", false, "false", "3", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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": [ "Configure", "SPConfigure" ], "CommandName": "Test-DbaOptimizeForAdHoc", "Name": "Test-DbaOptimizeForAdHoc", "Author": "Brandon Abshire, netnerds.net", "Syntax": "Test-DbaOptimizeForAdHoc [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance queried, with configuration details and recommendations.\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- CurrentOptimizeAdHoc: Current value of the optimize for ad-hoc workloads setting (0 or 1, where 1 is enabled)\r\n- RecommendedOptimizeAdHoc: The recommended value for this setting (always 1 for enabled)\r\n- Notes: Guidance message indicating if the setting is optimally configured or needs adjustment", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaOptimizeForAdHoc -SqlInstance sql2008, sqlserver2012\nValidates whether Optimize for AdHoc Workloads setting is enabled for servers sql2008 and sqlserver2012.", "Description": "Checks the current value of the \"optimize for ad-hoc workloads\" server configuration option and compares it against the recommended setting of 1 (enabled). This setting helps prevent plan cache bloat by storing only compiled plan stubs for single-use ad hoc queries instead of full execution plans. DBAs typically enable this on servers with high volumes of ad hoc queries to reduce memory pressure and improve overall performance. Returns the current configuration value, recommended value, and guidance notes for each SQL Server instance.\n\nMore info: https://msdn.microsoft.com/en-us/library/cc645587.aspx\nhttp://www.sqlservercentral.com/blogs/glennberry/2011/02/25/some-suggested-sql-server-2008-r2-instance-configuration-settings/\n\nThese are just general recommendations for SQL Server and are a good starting point for setting the \"optimize for ad-hoc workloads\" option.", "Links": "https://dbatools.io/Test-DbaOptimizeForAdHoc", "Synopsis": "Tests whether the SQL Server \"optimize for ad-hoc workloads\" configuration setting is enabled.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "A collection of one or more SQL Server instance names 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", "" ] ] }, { "Tags": [ "Storage", "Path", "Directory" ], "CommandName": "Test-DbaPath", "Name": "Test-DbaPath", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Test-DbaPath [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-Path] \u003cObject\u003e [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "System.Boolean (when testing a single path on a single instance)\nReturns $true if the file or directory is accessible to the SQL Server service account, $false otherwise.\nPSCustomObject (when testing multiple paths, multiple instances, or array input)\nReturns one object per file or directory path tested, with the following properties:\r\n- SqlInstance: Full instance name (computer\\instance format)\r\n- InstanceName: The SQL Server instance name\r\n- ComputerName: The computer name hosting the SQL Server instance\r\n- FilePath: The file or directory path that was tested\r\n- FileExists: Boolean indicating if the file or directory exists and is accessible\r\n- IsContainer: Boolean indicating if the path is a directory (container) rather than a file\nNote: FileExists is true if either the file exists OR the path is a container (directory). IsContainer specifically identifies if it\u0027s a directory.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaPath -SqlInstance sqlcluster -Path L:\\MSAS12.MSSQLSERVER\\OLAP\nTests whether the service account running the \"sqlcluster\" SQL Server instance can access L:\\MSAS12.MSSQLSERVER\\OLAP. Logs into sqlcluster using Windows credentials.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$credential = Get-Credential\nPS C:\\\u003e Test-DbaPath -SqlInstance sqlcluster -SqlCredential $credential -Path L:\\MSAS12.MSSQLSERVER\\OLAP\nTests whether the service account running the \"sqlcluster\" SQL Server instance can access L:\\MSAS12.MSSQLSERVER\\OLAP. Logs into sqlcluster using SQL authentication.", "Description": "Verifies file and directory accessibility from SQL Server\u0027s perspective using the master.dbo.xp_fileexist extended stored procedure. This is essential before backup operations, restore tasks, or any SQL Server process that requires file system access. The function tests from the SQL Server service account\u0027s security context, which may differ from your user account\u0027s permissions. Returns detailed information about file existence and whether the path is a container (directory).", "Links": "https://dbatools.io/Test-DbaPath", "Synopsis": "Tests if files or directories are accessible to the SQL Server service account.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The SQL Server you want to run the test on.", "", 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 file or directory paths to test for accessibility from the SQL Server service account\u0027s perspective. Accepts single paths, arrays of paths, or pipeline input.\r\nUse this to verify SQL Server can access backup destinations, restore source files, or any location needed for database operations.\r\nCritical for pre-validating paths before backup, restore, or bulk operations that would otherwise fail with access denied errors.", "", 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", "" ] ] }, { "Tags": [ "PowerPlan", "OS", "Utility" ], "CommandName": "Test-DbaPowerPlan", "Name": "Test-DbaPowerPlan", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Test-DbaPowerPlan [-ComputerName] \u003cDbaInstanceParameter[]\u003e [[-Credential] \u003cPSCredential\u003e] [[-PowerPlan] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per computer tested with power plan compliance information.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The target computer name\r\n- ActivePowerPlan: Name of the currently active Windows Power Plan\r\n- RecommendedPowerPlan: Name of the recommended power plan (High Performance by default, or custom if -PowerPlan specified)\r\n- IsBestPractice: Boolean indicating if the active power plan matches the recommended plan\nAdditional properties available:\r\n- ActiveInstanceId: UUID of the currently active power plan\r\n- RecommendedInstanceId: UUID of the recommended power plan\r\n- Credential: The PSCredential object used for authentication\nIf the recommended power plan is not found on the system, RecommendedPowerPlan will contain an error message like \"You do not have the high performance plan installed on this machine.\"", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaPowerPlan -ComputerName sqlserver2014a\nChecks the Power Plan settings for sqlserver2014a and indicates whether or not it complies with best practices.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaPowerPlan -ComputerName sqlserver2014a -PowerPlan \u0027Maximum Performance\u0027\nChecks the Power Plan settings for sqlserver2014a and indicates whether or not it is set to the Power Plan \"Maximum Performance\".\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e\u0027newserver1\u0027, \u0027newserver2\u0027 | Test-DbaPowerPlan\nChecks the Power Plan settings for newserver1 and newserver2 and indicates whether or not they comply with best practices.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaPowerPlan -ComputerName oldserver | Test-DbaPowerPlan -ComputerName newserver1, newserver2\nUses the Power Plan of oldserver as best practice and tests the Power Plan of newserver1 and newserver2 against that.", "Description": "Audits Windows Power Plan settings on SQL Server hosts to ensure compliance with Microsoft\u0027s performance recommendations. SQL Server runs optimally with the \"High Performance\" power plan, which prevents CPU throttling and ensures consistent performance under load.\n\nThis function compares the currently active power plan against the recommended \"High Performance\" plan (or a custom plan you specify) and returns a compliance report. This is essential for SQL Server environments where power management can significantly impact query performance and response times.\n\nReturns detailed information including the active power plan, recommended plan, and a clear IsBestPractice indicator for each system tested. Use this for regular compliance audits, new server validations, or troubleshooting performance issues that might be related to power management settings.\n\nIf your organization uses a different Power Plan that is considered best practice, specify -PowerPlan to test against that instead.\n\nReferences:\nhttps://support.microsoft.com/en-us/kb/2207548\nhttp://www.sqlskills.com/blogs/glenn/windows-power-plan-effects-on-newer-intel-processors/", "Links": "https://dbatools.io/Test-DbaPowerPlan", "Synopsis": "Tests Windows Power Plan settings against SQL Server best practices and identifies non-compliant systems.", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the SQL Server host(s) where you want to test Windows Power Plan compliance. Accepts server names, IP addresses, or DbaInstance objects.\r\nUse this to audit power settings across your SQL Server environment, especially important for performance-critical instances where CPU throttling can impact query response times.", "", true, "true (ByValue, ByPropertyName)", "", "" ], [ "Credential", "Specifies a PSCredential object to use in authenticating to the server(s), instead of the current user account.", "", false, "true (ByPropertyName)", "", "" ], [ "PowerPlan", "Specifies a custom power plan name to test against instead of the default \"High Performance\" plan. Use exact name matching as it appears in Windows Power Options.\r\nUseful when your organization has standardized on a specific custom power plan or when testing against plans like \"Ultimate Performance\" on Windows Server 2016+ or workstation operating systems.", "CustomPowerPlan", false, "true (ByPropertyName)", "", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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", "CommandName": "Test-DbaReplLatency", "Name": "Test-DbaReplLatency", "Author": "Colin Douglas", "Syntax": "Test-DbaReplLatency [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-Database] \u003cObject[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-PublicationName] \u003cObject[]\u003e] [[-TimeToLive] \u003cInt32\u003e] [-RetainToken] [-DisplayTokenHistory] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "Test-DbaRepLatency", "Outputs": "PSCustomObject\nReturns one object per tracer token result per subscriber in each transactional replication publication. When using -DisplayTokenHistory, multiple objects per token are returned for historical token \r\ndata. Each object represents the latency measurements for one tracer token\u0027s journey from publisher to a specific subscriber database.\nProperties:\r\n- ComputerName (string): The name of the computer hosting the publisher SQL Server instance\r\n- InstanceName (string): The SQL Server instance name of the publisher\r\n- SqlInstance (string): The full SQL Server instance name of the publisher (computer\\instance format)\r\n- TokenID (int): Unique identifier for the tracer token within the publication\r\n- TokenCreateDate (datetime): The date and time when the tracer token was created and inserted into the publication transaction log\r\n- PublicationServer (string): The name of the publisher SQL Server instance\r\n- PublicationDB (string): The name of the database containing the transactional replication publication\r\n- PublicationName (string): The name of the transactional replication publication\r\n- PublicationType (string): The type of replication publication (Transactional, Merge, or Snapshot)\r\n- DistributionServer (string): The name of the distributor SQL Server instance\r\n- DistributionDB (string): The name of the distribution database on the distributor\r\n- SubscriberServer (string): The name of the subscriber SQL Server instance receiving the replicated data\r\n- SubscriberDB (string): The name of the subscription database on the subscriber\r\n- PublisherToDistributorLatency (timespan or DBNull): Time in seconds for the tracer token to travel from the publisher transaction log to the distributor; may be DBNull if latency has not yet been \r\nrecorded\r\n- DistributorToSubscriberLatency (timespan or DBNull): Time in seconds for the tracer token to travel from the distributor to the subscriber; may be DBNull if the token has not yet reached the \r\nsubscriber\r\n- TotalLatency (timespan or DBNull): Combined latency (PublisherToDistributorLatency + DistributorToSubscriberLatency); DBNull if either component latency is not yet available", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaReplLatency -SqlInstance sql2008, sqlserver2012\nReturn replication latency for all transactional publications for servers sql2008 and sqlserver2012.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaReplLatency -SqlInstance sql2008 -Database TestDB\nReturn replication latency for all transactional publications on server sql2008 for only the TestDB database\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaReplLatency -SqlInstance sql2008 -Database TestDB -PublicationName TestDB_Pub\nReturn replication latency for the TestDB_Pub publication for the TestDB database located on the server sql2008.", "Description": "Creates tracer tokens in transactional replication publications and measures the time it takes for those tokens to travel from the publisher to the distributor, and from the distributor to each subscriber. This provides real-time latency measurements that help DBAs identify replication performance bottlenecks and validate that data changes are flowing through the replication topology within acceptable timeframes.\n\nThe function connects to both the publisher and distributor instances to inject tracer tokens and retrieve timing information. You can monitor latency for all publications on an instance, specific databases, or individual publications. The latency measurements include publisher-to-distributor time, distributor-to-subscriber time, and total end-to-end latency for each subscriber.\n\nThis is particularly useful when troubleshooting slow replication, validating replication performance after configuration changes, or establishing baseline performance metrics for replication monitoring.\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/Test-DbaReplLatency", "Synopsis": "Measures transactional replication latency using tracer tokens across publisher, distributor, and subscriber instances.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances.", "", true, "true (ByValue)", "", "" ], [ "Database", "Specifies which databases containing transactional replication publications to test for latency. Accepts wildcards for pattern matching.\r\nUse this when you need to focus on specific publication databases instead of testing all replicated databases on the 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", "", "" ], [ "PublicationName", "Specifies which transactional replication publications to test for latency. Accepts wildcards for pattern matching.\r\nUse this when you need to test specific publications instead of all transactional publications in the specified databases.", "", false, "false", "", "" ], [ "TimeToLive", "Sets the maximum time in seconds to wait for tracer tokens to travel from publisher through distributor to all subscribers.\r\nUse this to prevent the function from hanging indefinitely when replication is severely delayed or broken. If the timeout is reached, the function reports incomplete latency data and continues to the \r\nnext publication.", "", false, "false", "0", "" ], [ "RetainToken", "Keeps the tracer tokens in the distribution database after latency testing is complete instead of automatically cleaning them up.\r\nUse this when you need to preserve tracer token history for further analysis or troubleshooting. Without this switch, tokens are automatically removed to prevent distribution database bloat.", "", false, "false", "False", "" ], [ "DisplayTokenHistory", "Shows latency measurements for all existing tracer tokens in each publication instead of just the newly created token.\r\nUse this to see historical latency patterns and trends for ongoing replication monitoring. Without this switch, only the current test token results are displayed.", "", 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": "SPN", "CommandName": "Test-DbaSpn", "Name": "Test-DbaSpn", "Author": "Drew Furgiuele (@pittfurg), port1433.com | niphlod", "Syntax": "Test-DbaSpn [-ComputerName] \u003cDbaInstanceParameter[]\u003e [[-Credential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per Service Principal Name per SQL Server instance discovered on the target computer(s). For instances with multiple ports or dynamic port configurations, multiple SPN entries may \r\nbe returned per instance.\nProperties:\r\n- ComputerName (string): The name of the computer (or cluster virtual name for clustered instances) where the SQL Server instance is running\r\n- InstanceName (string): The name of the SQL Server instance (MSSQLSERVER for default instance, or the named instance name)\r\n- SqlProduct (string): The SQL Server product version and edition information (e.g., \"15.0.2154.1 Enterprise Edition\")\r\n- InstanceServiceAccount (string): The Windows service account under which the SQL Server instance runs (includes domain and username, e.g., \"DOMAIN\\sqlservice\" or \"NT SERVICE\\MSSQLSERVER\")\r\n- RequiredSPN (string): The Service Principal Name that should be registered in Active Directory for this instance and port (format: MSSQLSvc/hostname or MSSQLSvc/hostname:port)\r\n- IsSet (boolean): Boolean indicating whether the required SPN is currently registered in Active Directory under the service account\r\n- Cluster (boolean): Boolean indicating whether this is a clustered SQL Server instance\r\n- TcpEnabled (boolean): Boolean indicating whether TCP/IP protocol is enabled for this instance (instances without TCP/IP don\u0027t require SPNs)\r\n- Port (string or null): The port number on which this instance is listening (null if using default 1433 or if TCP is disabled)\r\n- DynamicPort (boolean): Boolean indicating whether this instance is using dynamic port assignment (port changes at each startup)\r\n- Warning (string): Warning message about the SPN configuration (e.g., \"Dynamic port is enabled\" or \"None\")\r\n- Error (string): Error message if the SPN configuration is invalid (e.g., \"SPN missing\" or \"None\")", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaSpn -ComputerName SQLSERVERA -Credential ad\\sqldba\nConnects to a computer (SQLSERVERA) and queries WMI for all SQL instances and return \"required\" SPNs. It will then take each SPN it generates\r\nand query Active Directory to make sure the SPNs are set.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaSpn -ComputerName SQLSERVERA,SQLSERVERB -Credential ad\\sqldba\nConnects to multiple computers (SQLSERVERA, SQLSERVERB) and queries WMI for all SQL instances and return \"required\" SPNs.\r\nIt will then take each SPN it generates and query Active Directory to make sure the SPNs are set.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaSpn -ComputerName SQLSERVERC -Credential ad\\sqldba\nConnects to a computer (SQLSERVERC) on a specified and queries WMI for all SQL instances and return \"required\" SPNs.\r\nIt will then take each SPN it generates and query Active Directory to make sure the SPNs are set. Note that the credential you pass must have be a valid login with appropriate rights on the domain", "Description": "This function discovers SQL Server instances on target computers and validates their Service Principal Name (SPN) configuration for Kerberos authentication. It addresses the common problem of missing or incorrect SPNs that cause authentication failures and double-hop issues in SQL Server environments.\n\nThe function performs a complete SPN audit by first discovering all SQL Server instances via WMI, then generating the required SPNs based on each instance\u0027s configuration. For instances with TCP/IP enabled, it determines which ports they\u0027re listening on and generates the appropriate MSSQLSvc SPNs. Named instances get both instance-based and port-based SPNs, while the function handles dynamic ports by identifying the current port assignment.\n\nAfter generating the required SPNs, the function queries Active Directory to verify whether each SPN is actually registered to the correct service account. This catches common configuration issues like SPNs registered to the wrong account, missing SPNs, or duplicate SPNs that prevent proper Kerberos authentication.\n\nThe function handles complex scenarios including clustered instances (using virtual server names), managed service accounts, LocalSystem accounts, and both static and dynamic port configurations. Results include detailed information about each instance\u0027s service account, required SPNs, registration status, and any configuration warnings.\n\nUse this function to troubleshoot Kerberos authentication issues, perform security audits, validate configurations before migrations, or as part of regular maintenance to ensure proper SPN setup across your SQL Server environment.", "Links": "https://dbatools.io/Test-DbaSpn", "Synopsis": "Validates Service Principal Name (SPN) configuration for SQL Server instances by comparing required SPNs against Active Directory registrations", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the target computer(s) to scan for SQL Server instances and validate their SPN configuration.\r\nAccepts computer names, IP addresses, or fully qualified domain names and supports pipeline input for bulk operations.\r\nThe function will discover all SQL Server instances on each specified computer and check their required SPNs against Active Directory.", "", true, "true (ByValue)", "", "" ], [ "Credential", "The credential you want to use to connect to the remote server and active directory.", "", 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": [ "Tempdb", "Configuration" ], "CommandName": "Test-DbaTempDbConfig", "Name": "Test-DbaTempDbConfig", "Author": "Michael Fal (@Mike_Fal), mikefal.net", "Syntax": "Test-DbaTempDbConfig [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns exactly 6 objects per SQL Server instance - one for each tempdb configuration rule evaluated. Each object contains compliance status for a single best practice rule.\nProperties (consistent across all 6 rule objects):\r\n- ComputerName: The computer name 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- Rule: The name of the configuration rule being evaluated (string):\r\n * \"TF 1118 Enabled\" - Trace Flag 1118 status for proportional fill algorithm\r\n * \"File Count\" - Number of tempdb data files compared to recommended count\r\n * \"File Growth in Percent\" - Whether any files use percentage-based growth (should be KB-based)\r\n * \"File Location\" - Whether any files are located on C:\\ drive\r\n * \"File MaxSize Set\" - Whether any files have maximum size limits set\r\n * \"Data File Size Equal\" - Whether all tempdb data files are equally sized\r\n- Recommended: The recommended value for this rule (bool or int):\r\n * Integer for \"File Count\" rule (recommended = min(8, processor count))\r\n * Boolean false for \"File Growth in Percent\", \"File Location\", \"File MaxSize Set\"\r\n * Boolean true for \"TF 1118 Enabled\" (SQL 2012 and below) or false (SQL 2016+)\r\n * Boolean true for \"Data File Size Equal\"\r\n- CurrentSetting: The actual current value on this instance (bool or int):\r\n * Integer for \"File Count\" rule (actual count of tempdb data files)\r\n * Boolean for all other rules\r\n- IsBestPractice: Boolean indicating whether the current setting meets Microsoft\u0027s best practice recommendations\r\n- Notes: Explanatory text describing the rule and recommendations\nAll properties are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaTempDbConfig -SqlInstance localhost\nChecks tempdb on the localhost machine.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaTempDbConfig -SqlInstance localhost | Select-Object *\nChecks tempdb on the localhost machine. All rest results are shown.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaRegServer -SqlInstance sqlserver2014a | Test-DbaTempDbConfig | Select-Object * | Out-GridView\nChecks tempdb configuration for a group of servers from SQL Server Central Management Server (CMS). Output includes all columns. Send output to GridView.", "Description": "Performs a comprehensive audit of tempdb configuration against Microsoft\u0027s recommended best practices, returning detailed compliance results for each rule. This saves DBAs from manually checking multiple tempdb settings and provides clear guidance on which configurations need attention.\n\nThe function evaluates six critical areas of tempdb configuration:\n\n* TF 1118 enabled - Is Trace Flag 1118 enabled (See KB328551).\n* File Count - Does the count of data files in tempdb match the number of logical cores, up to 8?\n* File Growth - Are any files set to have percentage growth? Best practice is all files have an explicit growth value.\n* File Location - Is tempdb located on the C:\\? Best practice says to locate it elsewhere.\n* File MaxSize Set (optional) - Do any files have a max size value? Max size could cause tempdb problems if it isn\u0027t allowed to grow.\n* Data File Size Equal - Are the sizes of all the tempdb data files the same?\n\nEach rule returns the current setting, recommended setting, and whether the configuration follows best practices. This is particularly useful during SQL Server health checks, performance troubleshooting, or compliance audits where tempdb configuration directly impacts system performance.", "Links": "https://dbatools.io/Test-DbaTempDbConfig", "Synopsis": "Tests tempdb configuration against SQL Server best practices and returns compliance status for each rule.", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance or instances. SQL Server 2005 and higher are supported.", "", 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": "Login", "CommandName": "Test-DbaWindowsLogin", "Name": "Test-DbaWindowsLogin", "Author": "Stephen Bennett, sqlnotesfromtheunderground.wordpress.com | Chrissy LeMaire (@cl)", "Syntax": "Test-DbaWindowsLogin [[-SqlInstance] \u003cDbaInstanceParameter[]\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Login] \u003cString[]\u003e] [[-ExcludeLogin] \u003cString[]\u003e] [[-FilterBy] \u003cString\u003e] [[-IgnoreDomains] \u003cString[]\u003e] [[-InputObject] \u003cLogin[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per Windows login or Active Directory group validated. Each object represents the validation results for a single Windows login or group on the SQL Server instance.\nWindows User and Computer Account Properties:\r\n- Server: Full SQL Server instance name (computer\\instance)\r\n- Domain: Active Directory domain name\r\n- Login: Windows login username\r\n- Type: Account type - either \"User\" or \"Computer\"\r\n- Found: Boolean indicating whether the account exists in Active Directory\r\n- SamAccountNameMismatch: Boolean indicating whether the SAM account name differs between SQL Server and AD\r\n- DisabledInSQLServer: Boolean indicating whether the login is disabled in SQL Server\r\n- Enabled: Boolean indicating whether the account is enabled in Active Directory (null for groups)\r\n- AccountNotDelegated: Boolean indicating whether the account is marked as non-delegated\r\n- LockedOut: Boolean indicating whether the account is currently locked out\r\n- PasswordExpired: Boolean indicating whether the password has expired\r\n- PasswordNeverExpires: Boolean indicating whether the password is set to never expire\r\n- PasswordNotRequired: Boolean indicating whether a password is required for the account\r\n- CannotChangePassword: Boolean indicating whether the user account is password-change protected\r\n- AllowReversiblePasswordEncryption: Boolean indicating whether reversible password encryption is allowed\r\n- SmartcardLogonRequired: Boolean indicating whether smartcard logon is required\r\n- TrustedForDelegation: Boolean indicating whether the account is trusted for delegation\r\n- UserAccountControl: Raw integer UserAccountControl value from Active Directory\nWindows Group Account Properties:\r\n- Server, Domain, Login, Type, Found, SamAccountNameMismatch, DisabledInSQLServer: Same as above\r\n- All security properties (Enabled, AccountNotDelegated, LockedOut, etc.): null for group accounts\nDefault display properties (via Select-DefaultView):\r\n- Server, Domain, Login, Type, Found, SamAccountNameMismatch, DisabledInSQLServer\nAll properties are accessible using Select-Object *.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eTest-DbaWindowsLogin -SqlInstance Dev01\nTests all logins in the current Active Directory domain that are either disabled or do not exist on the SQL Server instance Dev01\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eTest-DbaWindowsLogin -SqlInstance Dev01 -FilterBy GroupsOnly | Select-Object -Property *\nTests all Active Directory groups that have logins on Dev01, and shows all information for those logins\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eTest-DbaWindowsLogin -SqlInstance Dev01 -IgnoreDomains testdomain\nTests all Domain logins excluding any that are from the testdomain\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaLogin -SqlInstance Dev01 -Login DOMAIN\\User | Test-DbaWindowsLogin\nTests only the login returned by Get-DbaLogin", "Description": "Queries SQL Server for all Windows-based logins and groups, then validates each against Active Directory to identify security issues and cleanup opportunities. The function checks whether AD accounts still exist, are enabled, and match their SQL Server SID to detect orphaned logins from domain migrations or account deletions. This helps DBAs maintain login security by identifying stale Windows authentication accounts that should be removed from SQL Server.", "Links": "https://dbatools.io/Test-DbaWindowsLogin", "Synopsis": "Validates Windows logins and groups in SQL Server against Active Directory to identify orphaned, disabled, or problematic accounts", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The SQL Server instance you\u0027re checking logins on. You must have sysadmin access and server version must be SQL Server version 2000 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", "", "" ], [ "Login", "Specifies specific Windows logins to validate against Active Directory. Use this when you want to test only certain logins rather than all Windows accounts on the server.\r\nAccepts wildcards and multiple values. Helpful for focused security audits of high-privilege accounts or problem logins.", "", false, "false", "", "" ], [ "ExcludeLogin", "Excludes specific Windows logins from validation checks. Use this to skip service accounts or known system logins that you don\u0027t need to audit.\r\nAccepts wildcards and multiple values. Common exclusions include application service accounts and break-glass emergency accounts.", "", false, "false", "", "" ], [ "FilterBy", "Limits validation to either individual user accounts or Active Directory groups. Use \u0027LoginsOnly\u0027 when auditing user access or \u0027GroupsOnly\u0027 when reviewing group-based permissions.\r\nDefault of \u0027None\u0027 validates both types. GroupsOnly is useful for reviewing role-based access control implementation.", "", false, "false", "None", "LoginsOnly,GroupsOnly,None" ], [ "IgnoreDomains", "Excludes logins from specific Active Directory domains from validation. Use this in multi-domain environments to focus on specific domains or skip legacy/untrusted domains.\r\nHelpful when you have old domain trusts or want to audit only production domains while excluding development or test domains.", "", false, "false", "", "" ], [ "InputObject", "Accepts login objects from Get-DbaLogin for targeted validation. Use this when you want to validate a specific subset of logins already retrieved by another command.\r\nEnables powerful filtering scenarios by piping pre-filtered login objects instead of processing all Windows logins on the server.", "", 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": [ "Community", "SqlWatch" ], "CommandName": "Uninstall-DbaSqlWatch", "Name": "Uninstall-DbaSqlWatch", "Author": "Ken K (github.com/koglerk)", "Syntax": "Uninstall-DbaSqlWatch [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString\u003e] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "None\nThis command does not return any output objects. It performs a complete uninstallation of the SqlWatch monitoring solution by removing all associated database objects, SQL Agent jobs, Extended Events \r\nsessions, Service Broker components, and other related resources from the specified SQL Server instance.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eUninstall-DbaSqlWatch -SqlInstance server1\nDeletes all user objects, agent jobs, and historical data associated with SqlWatch from the master database.", "Description": "Performs a complete uninstallation of the SqlWatch performance monitoring solution by removing all associated database objects, SQL Agent jobs, and historical data. This includes dropping all SqlWatch tables (containing performance metrics history), views, stored procedures, functions, Extended Events sessions, Service Broker components, assemblies, and user-defined table types. The function also unpublishes the SqlWatch DACPAC registration to ensure clean removal. Use this when decommissioning SqlWatch or preparing for a fresh installation after configuration issues.", "Links": "https://dbatools.io/Uninstall-DbaSqlWatch", "Synopsis": "Completely removes SqlWatch monitoring solution from a SQL Server instance", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "SQL Server name or SMO object representing the SQL Server to connect to.", "", 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 the SqlWatch installation to remove. Defaults to master.\r\nUse this when SqlWatch was installed in a database other than the default master database.", "", false, "false", "master", "" ], [ "EnableException", "By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.\r\nThis avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting.\r\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 to confirm actions", "cf", false, "false", "", "" ] ] }, { "Tags": "Module", "CommandName": "Unregister-DbatoolsConfig", "Name": "Unregister-DbatoolsConfig", "Author": "Friedrich Weinmann (@FredWeinmann)", "Syntax": "Unregister-DbatoolsConfig [-ConfigurationItem \u003cConfig[]\u003e] [-FullName \u003cString[]\u003e] [-Scope {UserDefault | UserMandatory | SystemDefault | SystemMandatory | FileUserLocal | FileUserShared | FileSystem}] [\u003cCommonParameters\u003e]\nUnregister-DbatoolsConfig -Module \u003cString\u003e [-Name \u003cString\u003e] [-Scope {UserDefault | UserMandatory | SystemDefault | SystemMandatory | FileUserLocal | FileUserShared | FileSystem}] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "None\nThis command does not return any output objects. It removes persisted configuration settings from registry and configuration files based on the specified parameters.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eGet-DbatoolsConfig | Unregister-DbatoolsConfig\nCompletely removes all registered configurations currently loaded in memory.\r\nIn most cases, this will mean removing all registered configurations.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eUnregister-DbatoolsConfig -Scope SystemDefault -FullName \u0027MyModule.Path.DefaultExport\u0027\nUnregisters the setting \u0027MyModule.Path.DefaultExport\u0027 from the list of computer-wide defaults.\r\nNote: Changing system wide settings requires running the console with elevation.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eUnregister-DbatoolsConfig -Module MyModule\nUnregisters all configuration settings for the module MyModule.", "Description": "Removes dbatools configuration settings that have been persisted to Windows registry or JSON configuration files. This lets you clean up module settings that were previously saved using Register-DbatoolsConfig, removing them from user profiles or system-wide storage locations.\n\nThe function handles settings stored in multiple persistence scopes including user-specific registry entries, computer-wide registry settings, and JSON configuration files in various user and system directories. You can target specific settings by name or module, or remove entire configuration groups.\n\nNote: This command only removes persisted settings and has no effect on configuration values currently loaded in PowerShell memory.", "Links": "https://dbatools.io/Unregister-DbatoolsConfig", "Synopsis": "Removes persisted dbatools configuration settings from registry and configuration files.", "Availability": "Windows, Linux, macOS", "Params": [ [ "ConfigurationItem", "Specifies configuration objects to remove from persistent storage, as returned by Get-DbatoolsConfig.\r\nUse this when you want to unregister specific settings already identified through Get-DbatoolsConfig.", "", false, "true (ByValue)", "", "" ], [ "FullName", "Specifies the complete name of the configuration setting to remove from persistent storage.\r\nUse this when you know the exact setting name in the format \u0027module.category.setting\u0027.", "", false, "true (ByValue)", "", "" ], [ "Module", "Specifies the module name to target for configuration removal.\r\nUse this to remove all configuration settings belonging to a specific dbatools module or component.", "", true, "false", "", "" ], [ "Name", "Specifies the setting name pattern to match within the targeted module. Supports wildcards.\r\nUse with the Module parameter to narrow down which settings to remove, defaults to \u0027*\u0027 to match all settings.", "", false, "false", "*", "" ], [ "Scope", "Specifies which configuration storage locations to target for removal: user settings, computer-wide settings, or file-based configurations.\r\nDefaults to UserDefault which removes settings from the current user\u0027s registry. Use SystemDefault to remove computer-wide settings (requires elevation).", "", false, "false", "UserDefault", "" ] ] }, { "Tags": [ "Utility", "SqlBuild" ], "CommandName": "Update-DbaBuildReference", "Name": "Update-DbaBuildReference", "Author": "Simone Bizzotto (@niphold) | Friedrich Weinmann (@FredWeinmann)", "Syntax": "Update-DbaBuildReference [[-LocalFile] \u003cString\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "None\nThis function does not return pipeline objects. It updates the local build reference database file and provides informational messages via Write-Message at the Output level to indicate successful \r\nupdates.\nThe function modifies files on disk:\r\n- If the reference file needs updating, it writes the new version to the writable location (typically in the dbatools data directory)\r\n- Messages are written to indicate the update timestamp comparison and result\nTo track the update result, capture Write-Message output or monitor the exit status of the command.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eUpdate-DbaBuildReference\nLooks online if there is a newer version of the build reference\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eUpdate-DbaBuildReference -LocalFile \\\\fileserver\\Software\\dbatools\\dbatools-buildref-index.json\nUses the given file instead of downloading the file to update the build reference", "Description": "Refreshes the comprehensive SQL Server build reference database that powers Get-DbaBuild and Test-DbaBuild functions with current patch level information. This database contains detailed mappings between build numbers, service packs, cumulative updates, KB articles, release dates, and support lifecycle dates for all SQL Server versions.\n\nDBAs use this to maintain accurate patch compliance reporting and identify outdated installations that need security updates. The function downloads the latest reference data from the dbatools project repository, ensuring you have current information about newly released patches and updated support timelines.\n\nThe reference file is stored locally and automatically updated from newer module versions, but this command ensures you get the very latest patch data between dbatools releases. You can also specify a local file path instead of downloading, useful for air-gapped environments.\n\nUse Get-DbatoolsConfigValue -Name \u0027assets.sqlbuildreference\u0027 to see the current download URL.", "Links": "https://dbatools.io/Update-DbaBuildReference", "Synopsis": "Downloads the latest SQL Server build reference database used for patch compliance and version tracking", "Availability": "Windows, Linux, macOS", "Params": [ [ "LocalFile", "Specifies the path to a local JSON build reference file to use instead of downloading from the internet.\r\nUse this in air-gapped environments or when you need to use a specific version of the build reference data.\r\nThe file must be the dbatools-buildref-index.json format containing SQL Server build mappings and patch information.", "", 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", "Patching", "Update" ], "CommandName": "Update-DbaInstance", "Name": "Update-DbaInstance", "Author": "Kirill Kravtsov (@nvarscar), nvarscar.wordpress.com", "Syntax": "Update-DbaInstance [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [-Credential \u003cPSCredential\u003e] [-Version \u003cString[]\u003e] [-Type \u003cString[]\u003e] [-InstanceName \u003cString\u003e] [-Path \u003cString[]\u003e] [-Restart] [-Continue] [-Throttle \u003cInt32\u003e] [-Authentication \u003cString\u003e] [-UseSSL] [-Port \u003cNullable`1\u003e] [-ExtractPath \u003cString\u003e] [-ArgumentList \u003cString[]\u003e] [-Download] [-NoPendingRenameCheck] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nUpdate-DbaInstance [[-ComputerName] \u003cDbaInstanceParameter[]\u003e] [-Credential \u003cPSCredential\u003e] -KB \u003cString[]\u003e [-InstanceName \u003cString\u003e] [-Path \u003cString[]\u003e] [-Restart] [-Continue] [-Throttle \u003cInt32\u003e] [-Authentication \u003cString\u003e] [-UseSSL] [-Port \u003cNullable`1\u003e] [-ExtractPath \u003cString\u003e] [-ArgumentList \u003cString[]\u003e] [-Download] [-NoPendingRenameCheck] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per SQL Server instance updated, providing detailed information about the installation result and outcome.\nProperties:\r\n- ComputerName (string) - The computer name of the target instance\r\n- InstanceName (string) - The SQL Server instance name (MSSQLSERVER for default instance)\r\n- MajorVersion (int) - The SQL Server major version number (2008, 2012, 2016, 2019, 2022, etc.)\r\n- TargetLevel (string) - The target patch level that was applied (e.g., \"SP3CU15\")\r\n- KB (string) - The Knowledge Base number of the update that was installed\r\n- Installer (string) - Full path to the installer executable that was executed\r\n- Successful (bool) - Boolean indicating whether the patch installation completed successfully\r\n- Restarted (bool) - Boolean indicating whether the server was restarted after patching\r\n- Notes (object[]) - Array of messages describing the installation process, any warnings, or errors encountered", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eUpdate-DbaInstance -ComputerName SQL1 -Version SP3 -Path \\\\network\\share\nUpdates all applicable SQL Server installations on SQL1 to SP3.\r\nBinary files for the update will be searched among all files and folders recursively in \\\\network\\share.\r\nPrompts for confirmation before the update.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eUpdate-DbaInstance -ComputerName SQL1, SQL2 -Restart -Path \\\\network\\share -Confirm:$false\nUpdates all applicable SQL Server installations on SQL1 and SQL2 with the most recent patch (that has at least a \"CU\" flag).\r\nIt will install latest ServicePack, restart the computers, install latest Cumulative Update, and finally restart the computer once again.\r\nBinary files for the update will be searched among all files and folders recursively in \\\\network\\share.\r\nDoes not prompt for confirmation.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eUpdate-DbaInstance -ComputerName SQL1 -Version 2012 -Type ServicePack -Path \\\\network\\share\nUpdates SQL Server 2012 on SQL1 with the most recent ServicePack found in your patch repository.\r\nBinary files for the update will be searched among all files and folders recursively in \\\\network\\share.\r\nPrompts for confirmation before the update.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eUpdate-DbaInstance -ComputerName SQL1 -KB 123456 -Restart -Path \\\\network\\share -Confirm:$false\nInstalls KB 123456 on SQL1 and restarts the computer.\r\nBinary files for the update will be searched among all files and folders recursively in \\\\network\\share.\r\nDoes not prompt for confirmation.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eUpdate-DbaInstance -ComputerName Server1 -Version SQL2012SP3, SQL2016SP2CU3 -Path \\\\network\\share -Restart -Confirm:$false\nUpdates SQL 2012 to SP3 and SQL 2016 to SP2CU3 on Server1. Each update will be followed by a restart.\r\nBinary files for the update will be searched among all files and folders recursively in \\\\network\\share.\r\nDoes not prompt for confirmation.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003eUpdate-DbaInstance -ComputerName Server1 -Path \\\\network\\share -Restart -Confirm:$false -ExtractPath \"C:\\temp\"\nUpdates all applicable SQL Server installations on Server1 with the most recent patch. Each update will be followed by a restart.\r\nBinary files for the update will be searched among all files and folders recursively in \\\\network\\share.\r\nDoes not prompt for confirmation.\r\nExtracts the files in local driver on Server1 C:\\temp.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003eUpdate-DbaInstance -ComputerName Server1 -Path \\\\network\\share -ArgumentList \"/SkipRules=RebootRequiredCheck\"\nUpdates all applicable SQL Server installations on Server1 with the most recent patch.\r\nAdditional command line parameters would be passed to the executable.\r\nBinary files for the update will be searched among all files and folders recursively in \\\\network\\share.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003eUpdate-DbaInstance -ComputerName SQL1 -Version CU3 -Download -Path \\\\network\\share -Confirm:$false\nDownloads an appropriate CU KB to \\\\network\\share and installs it onto SQL1.\r\nDoes not prompt for confirmation.\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003eUpdate-DbaInstance -ComputerName \"db01.internal.local\" -Credential $cred -UseSSL -Port 5986 -Path \"\\\\fs01.internal.local\\SQL2022_Patch\\CU13\"\nUpdates SQL Server on db01.internal.local using SSL-encrypted WinRM connection on port 5986.\r\nRequires the remote server to be configured for HTTPS WinRM (typically port 5986).\r\nCredentials are provided to access both the remote server and the network share containing patch files.", "Description": "Automates the complete process of applying SQL Server patches to eliminate the manual effort of updating multiple instances. This function handles the entire patching workflow from detection through installation, replacing the tedious process of manually downloading, transferring, and applying updates across your SQL Server environment.\n\nThe patching process includes:\n* Discovering all SQL Server instances on target computers via registry scanning\n* Validating current versions against target update requirements\n* Locating appropriate KB installers in your patch repository\n* Establishing secure remote connections using CredSSP or other protocols\n* Extracting and executing patches from temporary directories\n* Managing restarts and chaining multiple updates when needed\n* Cleaning up temporary files after installation\n* Processing multiple computers in parallel for faster deployment\n\nThis replaces the manual process of RDP\u0027ing to each server, copying patch files, running installers, and tracking which systems need which updates. Perfect for monthly patching cycles, emergency security updates, or bringing development environments up to production patch levels.\n\nThe impact of this function is set to High. Use -Confirm:$false to suppress interactive prompts for automated deployments.\n\nFor CredSSP authentication, the function automatically configures PowerShell remoting when credentials are provided. This can be disabled by setting dbatools configuration \u0027commands.initialize-credssp.bypass\u0027 to $true. CredSSP configuration requires running from an elevated PowerShell session.\n\nAlways backup databases and configurations before applying any SQL Server updates.", "Links": "https://dbatools.io/Update-DbaInstance", "Synopsis": "Installs SQL Server Service Packs and Cumulative Updates across local and remote instances automatically.", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Target computer with SQL instance or instances.", "cn,host,Server", false, "true (ByValue)", "$env:COMPUTERNAME", "" ], [ "Credential", "Windows Credential with permission to log on to the remote server.\r\nMust be specified for any remote connection if update Repository is located on a network folder.\nAuthentication will default to CredSSP if -Credential is used.\r\nFor CredSSP see also additional information in DESCRIPTION.", "", false, "false", "", "" ], [ "Version", "Defines the target SQL Server version level to reach using pattern \u003cMajorVersion\u003e\u003cSPX\u003e\u003cCUX\u003e.\r\nUse this to standardize SQL Server instances to a specific patch level across your environment.\r\nExamples: 2008R2SP1 (SQL 2008R2 to SP1), 2016CU3 (SQL 2016 to CU3), SP1CU7 (all versions to SP1 then CU7).\r\nWhen omitted, installs the latest available patches for each detected SQL Server version.", "", false, "false", "", "" ], [ "Type", "Specifies which types of SQL Server updates to install: All, ServicePack, or CumulativeUpdate.\r\nUse this when you want to apply only specific update types, such as installing only Service Packs during maintenance windows.\r\nDefaults to All, which installs both Service Packs and Cumulative Updates in proper sequence.", "", false, "false", "@(\u0027All\u0027)", "All,ServicePack,CumulativeUpdate" ], [ "KB", "Installs a specific Knowledge Base update or list of updates by KB number.\r\nUse this when you need to apply a particular security patch or bug fix identified by Microsoft.\r\nAccepts formats like 123456 or KB123456, and supports multiple KB numbers for batch installations.", "", true, "false", "", "" ], [ "InstanceName", "Limits patching to a specific named SQL Server instance on the target computer.\r\nUse this when you have multiple SQL instances and need to patch only one, such as updating a development instance while leaving production untouched.\r\nOmit this parameter to update all SQL Server instances found on the target computers.", "Instance", false, "false", "", "" ], [ "Path", "Specifies the folder path containing SQL Server update files for installation.\r\nUse this to point to your centralized patch repository where you store downloaded SQL Server updates.\r\nFiles must follow Microsoft\u0027s naming pattern (SQLServer####*-KB###-*x##*.exe) and path must be accessible from both client and target servers.\r\nConfigure a default path with Set-DbatoolsConfig -Name Path.SQLServerUpdates to avoid specifying this repeatedly.", "", false, "false", "(Get-DbatoolsConfigValue -Name \u0027Path.SQLServerUpdates\u0027)", "" ], [ "Restart", "Automatically restarts the server after successful patch installation and waits for it to come back online.\r\nRequired for chaining multiple updates since SQL Server patches mandate a restart between installations.\r\nUse this during planned maintenance windows when you can afford server downtime for complete patch sequences.", "", false, "false", "False", "" ], [ "Continue", "Resumes a previously failed SQL Server update installation from where it left off.\r\nUse this when a patch installation was interrupted due to network issues, timeouts, or other temporary failures.\r\nWithout this switch, the function will abort and clean up any failed installation attempts.", "", false, "false", "False", "" ], [ "Throttle", "Controls the maximum number of servers that can be updated simultaneously during parallel operations.\r\nUse a lower value (5-10) for large production environments to limit network load and system resource usage.\r\nDefaults to 50, but consider your network bandwidth and the number of concurrent patch installations your infrastructure can handle.", "", false, "false", "50", "" ], [ "Authentication", "Specifies the PowerShell remoting authentication method for connecting to remote SQL Server hosts.\r\nDefaults to CredSSP when using -Credential to avoid double-hop authentication issues with network patch repositories.\r\nUse CredSSP when your patch files are stored on network shares that require credential delegation to remote servers.", "", false, "false", "@(\u0027Credssp\u0027, \u0027Default\u0027)[$null -eq $Credential]", "Default,Basic,Negotiate,NegotiateWithImplicitCredential,Credssp,Digest,Kerberos" ], [ "UseSSL", "Enables SSL encryption for PowerShell remoting connections to target servers.\r\nUse this when remote servers are configured to only accept encrypted WinRM connections (typically on port 5986).\r\nDefaults to the value configured in PSRemoting.PsSession.UseSSL configuration setting (false if not configured).\r\nExplicitly specifying this parameter overrides the configuration default.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \"PSRemoting.PsSession.UseSSL\" -Fallback $false)", "" ], [ "Port", "Specifies the WinRM port to use for PowerShell remoting connections.\r\nCommon values: 5985 (standard HTTP), 5986 (HTTPS/SSL).\r\nUse this when remote servers have WinRM configured on non-standard ports or when using SSL.\r\nDefaults to the value configured in PSRemoting.PsSession.Port configuration setting (standard ports if not configured).\r\nExplicitly specifying this parameter overrides the configuration default.", "", false, "false", "(Get-DbatoolsConfigValue -FullName \"PSRemoting.PsSession.Port\" -Fallback $null)", "" ], [ "ExtractPath", "Specifies the directory on target servers where SQL Server patch files will be extracted before installation.\r\nUse this to control where temporary installation files are placed, especially on servers with limited C: drive space.\r\nDefaults to system temporary directory if not specified, but consider using a dedicated drive with sufficient space.", "", false, "false", "", "" ], [ "ArgumentList", "Passes additional command-line parameters to the SQL Server patch installer executable.\r\nUse this to customize installation behavior such as skipping specific validation rules or running in quiet mode.\r\nCommon examples include /SkipRules=RebootRequiredCheck to bypass reboot checks, or /Q for silent installation.", "", false, "false", "", "" ], [ "Download", "Automatically downloads missing SQL Server update files from Microsoft when they\u0027re not found in your patch repository.\r\nUse this to ensure patches are available during installation without manually downloading them beforehand.\r\nFiles download to your local temp folder first, then get distributed to target servers or directly to network paths.", "", false, "false", "False", "" ], [ "NoPendingRenameCheck", "Bypasses the check for pending file rename operations that typically require a reboot before patching.\r\nUse this in environments where you\u0027re confident no pending renames exist or when system monitoring tools show false positives.\r\nExercise caution as installing patches with pending renames can lead to installation failures.", "", false, "false", "(Get-DbatoolsConfigValue -Name \u0027OS.PendingRename\u0027 -Fallback $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", "OlaHallengren" ], "CommandName": "Update-DbaMaintenanceSolution", "Name": "Update-DbaMaintenanceSolution", "Author": "Andreas Jordan, @JordanOrdix", "Syntax": "Update-DbaMaintenanceSolution [-SqlInstance] \u003cDbaInstanceParameter[]\u003e [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString\u003e] [[-Solution] \u003cString[]\u003e] [[-LocalFile] \u003cString\u003e] [-Force] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject\nReturns one object per maintenance solution procedure updated. The command will attempt to update all specified solution components (or all components if -Solution is not specified), returning status \r\nfor each attempt.\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- Solution: The maintenance solution component name (CommandExecute, Backup, IntegrityCheck, or IndexOptimize)\r\n- Procedure: The name of the stored procedure being updated\r\n- IsUpdated: Boolean indicating if the procedure was successfully updated\r\n- Results: Status or error message. Possible values: \"Updated\", \"Procedure not installed\", \"File not found\", or an error object if the update failed", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eUpdate-DbaMaintenanceSolution -SqlInstance RES14224 -Database DBA\nUpdates Ola Hallengren\u0027s Solution objects on RES14224 in the DBA database.", "Description": "Updates the stored procedures for Ola Hallengren\u0027s Maintenance Solution on SQL Server instances where it\u0027s already installed. This function downloads the latest version from GitHub and replaces only the procedure code, leaving all existing tables, jobs, and configurations intact.\n\nUse this when you need to get bug fixes or improvements in the maintenance procedures without disrupting your existing backup, integrity check, and index optimization jobs. The function checks for existing procedures before attempting updates and only updates what\u0027s currently installed.\n\nThis approach only works when the new procedure versions are compatible with your existing table structures and job configurations. If Ola releases changes that require schema modifications or new tables, you\u0027ll need to use Install-DbaMaintenanceSolution for a complete reinstallation instead.", "Links": "https://dbatools.io/Update-DbaMaintenanceSolution", "Synopsis": "Updates existing Ola Hallengren Maintenance Solution stored procedures to the latest version", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The target SQL Server instance onto which the Maintenance Solution will be updated.", "", 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 the existing Ola Hallengren maintenance solution stored procedures. Defaults to master.\r\nChange this if you installed the maintenance solution in a different database like DBA or Admin.", "", false, "false", "master", "" ], [ "Solution", "Controls which maintenance solution components to update. Valid options are All, Backup, IntegrityCheck, IndexOptimize, or CommandExecute.\r\nUse this when you only want to update specific procedures instead of the entire solution. Only procedures that already exist will be updated.", "", false, "false", "All", "All,Backup,IntegrityCheck,IndexOptimize,CommandExecute" ], [ "LocalFile", "Path to a local zip file containing Ola Hallengren\u0027s maintenance solution instead of downloading from GitHub.\r\nUse this in environments without internet access or when you need to deploy a specific version that differs from the latest release.", "", false, "false", "", "" ], [ "Force", "Forces download of the latest maintenance solution from GitHub even if a cached version exists locally.\r\nUse this when you want to ensure you\u0027re getting the absolute latest version or if the cached version is corrupted.", "", 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": [ "Service", "SqlServer", "Instance", "Connect" ], "CommandName": "Update-DbaServiceAccount", "Name": "Update-DbaServiceAccount", "Author": "Kirill Kravtsov (@nvarscar)", "Syntax": "Update-DbaServiceAccount [-ComputerName \u003cDbaInstanceParameter[]\u003e] [-Credential \u003cPSCredential\u003e] [-ServiceName] \u003cString[]\u003e [-Username \u003cString\u003e] [-ServiceCredential \u003cPSCredential\u003e] [-PreviousPassword \u003cSecureString\u003e] [-SecurePassword \u003cSecureString\u003e] [-NoRestart] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]\nUpdate-DbaServiceAccount [-Credential \u003cPSCredential\u003e] -InputObject \u003cObject[]\u003e [-Username \u003cString\u003e] [-ServiceCredential \u003cPSCredential\u003e] [-PreviousPassword \u003cSecureString\u003e] [-SecurePassword \u003cSecureString\u003e] [-NoRestart] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "Microsoft.SqlServer.Management.Smo.Wmi.SqlService\nReturns one service object per service that was updated, with additional properties added to indicate the result of the operation.\nDefault display properties (via Select-DefaultView):\r\n- ComputerName: The name of the computer hosting the SQL Server service\r\n- ServiceName: The Windows service name (e.g., MSSQLSERVER, SQLSERVERAGENT, MSSQL$INSTANCENAME)\r\n- State: The current state of the service after the update operation (Running, Stopped, Start Pending, Stop Pending)\r\n- StartName: The user account under which the service runs after the update\r\n- Status: Result of the operation (Successful, Failed, or \"No changes made - running in -WhatIf mode.\")\r\n- Message: Detailed message describing the outcome (e.g., \"The login account for the service has been successfully set.\" or error message)\nAdditional properties available on the service object (from SMO SqlService):\r\n- ServiceType: The type of SQL Server service (Engine, Agent, etc.)\r\n- InstanceName: The SQL Server instance name associated with the service\r\n- DisplayName: The friendly display name of the service\r\n- StartMode: The startup mode of the service (Automatic, Manual, Disabled)\nAll properties from the base SMO SqlService object are accessible using Select-Object * even though only the 6 default properties are displayed by default.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$SecurePassword = (Get-Credential NoUsernameNeeded).Password\nPS C:\\\u003e Update-DbaServiceAccount -ComputerName sql1 -ServiceName \u0027MSSQL$MYINSTANCE\u0027 -SecurePassword $SecurePassword\nChanges the current service account\u0027s password of the service MSSQL$MYINSTANCE to \u0027Qwerty1234\u0027\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$cred = Get-Credential\nPS C:\\\u003e Get-DbaService sql1 -Type Engine,Agent -Instance MYINSTANCE | Update-DbaServiceAccount -ServiceCredential $cred\nRequests credentials from the user and configures them as a service account for the SQL Server engine and agent services of the instance sql1\\MYINSTANCE\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eUpdate-DbaServiceAccount -ComputerName sql1,sql2 -ServiceName \u0027MSSQLSERVER\u0027,\u0027SQLSERVERAGENT\u0027 -Username NETWORKSERVICE\nConfigures SQL Server engine and agent services on the machines sql1 and sql2 to run under Network Service system user.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003eGet-DbaService sql1 -Type Engine -Instance MSSQLSERVER | Update-DbaServiceAccount -Username \u0027MyDomain\\sqluser1\u0027\nConfigures SQL Server engine service on the machine sql1 to run under MyDomain\\sqluser1. Will request user to input the account password.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003eGet-DbaService sql1 -Type Engine -Instance MSSQLSERVER | Update-DbaServiceAccount -Username \u0027MyDomain\\sqluser1\u0027 -NoRestart\nConfigures SQL Server engine service on the machine sql1 to run under MyDomain\\sqluser1. Will request user to input the account password.\nWill not restart, which means the changes will not go into effect, so you will still have to restart during your planned outage window.", "Description": "Updates the service account credentials or changes just the password for SQL Server Engine and Agent services. When changing the service account, the affected service will be automatically restarted to apply the changes. Password-only updates don\u0027t require a restart unless you want the changes to take effect immediately.\n\nThis function handles the complexities of SQL Server service management, including removing and reapplying network certificates during account changes to prevent SSL connection issues. It supports changing from local system accounts to domain accounts, rotating passwords for compliance, and updating multiple services across multiple instances.\n\nSupports SQL Server Engine and Agent services on supported SQL Server versions. Other services like Reporting Services or Analysis Services are not supported and may cause the function to fail on older SQL Server versions.", "Links": "https://dbatools.io/Update-DbaServiceAccount", "Synopsis": "Changes the service account or password for SQL Server Engine and Agent services.", "Availability": "Windows, Linux, macOS", "Params": [ [ "ComputerName", "Specifies the SQL Server computers where service account changes will be applied. Accepts multiple computer names for bulk operations.\r\nUse this when you need to update service accounts across multiple SQL Server instances in your environment.", "cn,host,Server", false, "false", "$env:COMPUTERNAME", "" ], [ "Credential", "Windows Credential with permission to log on to the server running the SQL instance", "", false, "false", "", "" ], [ "InputObject", "Accepts service objects from Get-DbaService for pipeline operations. Must contain ComputerName and ServiceName properties.\r\nUse this when you want to filter services first with Get-DbaService then update only specific services based on criteria like service type or instance name.", "ServiceCollection", true, "true (ByValue)", "", "" ], [ "ServiceName", "Specifies the exact SQL Server service name to update, such as \u0027MSSQLSERVER\u0027 for default instances or \u0027MSSQL$INSTANCENAME\u0027 for named instances.\r\nUse this when you need to target specific services rather than all SQL Server services on a computer. Supports SQL Server Agent services like \u0027SQLSERVERAGENT\u0027 or \u0027SQLAgent$INSTANCENAME\u0027.", "Name,Service", true, "false", "", "" ], [ "Username", "Specifies the service account username in DOMAIN\\\\Username format for domain accounts. Cannot be combined with -ServiceCredential parameter.\r\nUse this when you want to change to a specific domain account or local system account. For local system accounts, use LOCALSERVICE, NETWORKSERVICE, or LOCALSYSTEM without providing a password.", "User", false, "false", "", "" ], [ "ServiceCredential", "Provides a PSCredential object containing the domain account and password for the SQL Server service. Cannot be combined with -Username parameter.\r\nUse this when changing to a domain service account and you already have the credentials stored securely. For local system accounts, create credentials with usernames LOCALSERVICE, NETWORKSERVICE, or \r\nLOCALSYSTEM and empty passwords.", "", false, "false", "", "" ], [ "PreviousPassword", "Specifies the current password of the service account when performing password-only changes. Required for non-admin users but optional for local administrators.\r\nUse this when you\u0027re rotating passwords for compliance and need to provide the existing password to validate the change.", "", false, "false", "(New-Object System.Security.SecureString)", "" ], [ "SecurePassword", "Sets the new password for the service account as a SecureString object. If not provided, the function will prompt for password input.\r\nUse this when changing passwords for domain service accounts. Managed Service Accounts (MSAs) and local system accounts automatically ignore this parameter since they don\u0027t require passwords.", "Password,NewPassword", false, "false", "(New-Object System.Security.SecureString)", "" ], [ "NoRestart", "Prevents automatic restart of SQL Server services after account or password changes. Service changes will not take effect until services are manually restarted.\r\nUse this when you need to schedule service restarts during planned maintenance windows to avoid unexpected downtime during business hours.", "", 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": "Module", "CommandName": "Update-Dbatools", "Name": "Update-Dbatools", "Author": "Shawn Melton (@wsmelton), wsmelton.github.io", "Syntax": "Update-Dbatools [-Development] [-Cleanup] [-EnableException] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "None\nThis command is deprecated and returns no output. It displays a warning message to console directing users to use PowerShell\u0027s built-in Install-Module and Update-Module commands instead. No pipeline \r\nobjects are generated.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eUpdate-Dbatools\nUpdates dbatools. Deletes current copy and replaces it with freshest copy.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eUpdate-Dbatools -dev\nUpdates dbatools to the current development branch. Deletes current copy and replaces it with latest from github.", "Description": "Updates the dbatools module by removing the current installation and replacing it with the latest version from PowerShell Gallery or GitHub. This function has been deprecated in favor of PowerShell\u0027s native Install-Module and Update-Module commands which provide better dependency management and version control.", "Links": "https://dbatools.io/Update-Dbatools", "Synopsis": "Updates the dbatools PowerShell module to the latest version", "Availability": "Windows, Linux, macOS", "Params": [ [ "Development", "Installs the latest development branch from GitHub instead of the stable release from PowerShell Gallery. Use this when you need access to the newest features or bug fixes that haven\u0027t been \r\nofficially released yet. Development builds may contain untested changes, so avoid using this in production environments unless specifically needed for troubleshooting or testing.", "dev,devbranch", false, "false", "False", "" ], [ "Cleanup", "Removes previous versions of dbatools after installing the new version to free up disk space and avoid version conflicts. Use this when you have multiple dbatools versions installed and want to keep \r\nonly the latest version. Without this switch, old versions remain on the system which can occasionally cause module loading issues or consume unnecessary disk space.", "", 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": "Login", "CommandName": "Watch-DbaDbLogin", "Name": "Watch-DbaDbLogin", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Watch-DbaDbLogin [[-SqlInstance] \u003cDbaInstanceParameter\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Database] \u003cString\u003e] [[-Table] \u003cString\u003e] [[-SqlCms] \u003cString\u003e] [[-ServersFromFile] \u003cString\u003e] [[-InputObject] \u003cServer[]\u003e] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "None\nThis command does not return pipeline objects. It writes connection activity data directly to a database table specified by the -Database and -Table parameters. The function records login information \r\nfrom monitored instances and inserts the captured session details into the central tracking table for ongoing monitoring and audit purposes.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eWatch-DbaDbLogin -SqlInstance sqlserver -SqlCms SqlCms1\nA list of all database instances within the Central Management Server SqlCms1 is generated. Using this list, the script enumerates all the processes and gathers login information and saves it to the \r\ntable Dblogins in the DatabaseLogins database on SQL Server sqlserver.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eWatch-DbaDbLogin -SqlInstance sqlcluster -Database CentralAudit -ServersFromFile .\\sqlservers.txt\nA list of servers is gathered from the file sqlservers.txt in the current directory. Using this list, the script enumerates all the processes and gathers login information and saves it to the table \r\nDblogins in the CentralAudit database on SQL Server sqlcluster.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eWatch-DbaDbLogin -SqlInstance sqlserver -SqlCms SqlCms1 -SqlCredential $cred\nA list of servers is generated using database instance names within the SQL2014Clusters group on the Central Management Server SqlCms1. Using this list, the script enumerates all the processes and \r\ngathers login information and saves it to the table Dblogins in the DatabaseLogins database on sqlserver.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$instance1 = Connect-DbaInstance -SqlInstance sqldev01\nPS C:\\\u003e $instance2 = Connect-DbaInstance -SqlInstance sqldev02\r\nPS C:\\\u003e $instance1, $instance2 | Watch-DbaDbLogin -SqlInstance sqltest01 -Database CentralAudit\nPre-connects two instances sqldev01 and sqldev02 and then using pipelining sends them to Watch-DbaDbLogin to enumerate processes and gather login info. The resulting gathered info is stored to the \r\nDbaTools-WatchDbLogins table in the CentralAudit database on the sqltest01 instance.\nNote: This is the method to use if the instances have different credentials than the instance used to store the watch data.", "Description": "Watch-DbaDbLogin queries sys.dm_exec_sessions and sys.dm_exec_requests DMVs to capture real-time connection activity across multiple SQL Server instances. It records login names, client hostnames, application names, database usage, and timestamps into a central monitoring table. This solves the common problem of inadequate connection documentation when planning server migrations or application updates.\n\nThe function automatically filters out local server connections and system databases to focus on external client activity. Running this every 5-10 minutes over several weeks builds a comprehensive picture of who connects to what, from where, and when.\n\nYou can monitor servers from a Central Management Server, a text file list, or pipe in pre-connected instances. The captured data helps identify forgotten applications, validate connection strings during migrations, and document actual database usage patterns rather than relying on incomplete documentation.", "Links": "https://dbatools.io/Watch-DbaDbLogin", "Synopsis": "Monitors active connections across SQL Server instances and logs client details to a central tracking table", "Availability": "Windows, Linux, macOS", "Params": [ [ "SqlInstance", "The SQL Server that stores the Watch database.", "", 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 target database where connection monitoring data will be stored.\r\nThis database should be dedicated to audit and monitoring functions, separate from production databases.\r\nIf not specified, the function will attempt to use a default database on the SqlInstance.", "", false, "false", "", "" ], [ "Table", "Specifies the table name where login monitoring data will be inserted.\r\nDefaults to \"DbaTools-WatchDbLogins\" if not specified, and will be auto-created if it doesn\u0027t exist.\r\nUse a consistent naming convention across environments for easier reporting and analysis.", "", false, "false", "DbaTools-WatchDbLogins", "" ], [ "SqlCms", "Specifies a Central Management Server to retrieve registered SQL Server instances for monitoring.\r\nUse this when you need to monitor multiple servers that are already organized in CMS groups.\r\nThe function will connect to each registered server found in the CMS to capture login activity.", "", false, "false", "", "" ], [ "ServersFromFile", "Specifies a text file containing SQL Server instance names to monitor, with one instance per line.\r\nUse this when you have a custom list of servers not managed through CMS, or when scripting across different environments.\r\nSupports both named instances (SERVER\\INSTANCE) and default instances (SERVER).", "", false, "false", "", "" ], [ "InputObject", "Accepts pre-connected SQL Server instances from Connect-DbaInstance via pipeline.\r\nUse this method when monitoring servers with different authentication requirements than the storage instance.\r\nAllows for more granular credential control when connecting to multiple instances with varying security contexts.", "", 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": [ "ExtendedEvent", "XE", "XEvent" ], "CommandName": "Watch-DbaXESession", "Name": "Watch-DbaXESession", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Watch-DbaXESession [[-SqlInstance] \u003cDbaInstanceParameter\u003e] [[-SqlCredential] \u003cPSCredential\u003e] [[-Session] \u003cString\u003e] [[-InputObject] \u003cSession[]\u003e] [-Raw] [-EnableException] [\u003cCommonParameters\u003e]", "Alias": "", "Outputs": "PSCustomObject (default)\nReturns one object per Extended Event captured from the session. Each object contains dynamically generated properties based on the events, fields, and actions collected by the XE session.\nDefault properties include:\r\n- name: The Extended Event type name (e.g., sql_statement_completed, rpc_completed)\r\n- timestamp: The DateTime when the event was captured\r\n- Additional dynamic properties: All event fields (with \"collect_\" prefix removed) and all event actions (with the last part after dot separator)\nThe exact properties returned depend on which events, fields, and actions are configured in the Extended Events session being monitored. For example, monitoring sql_statement_completed might include \r\nproperties like statement, batch_text, duration, cpu_time, logical_reads, writes, etc.\nSystem.Object[] (when -Raw is specified)\nReturns raw XEvent enumeration objects from the SQL Server Extended Events infrastructure. These objects maintain the native Extended Events data structure and can be used for custom processing or \r\nintegration with other tools.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003eWatch-DbaXESession -SqlInstance sql2017 -Session system_health\nShows events for the system_health session as it happens.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003eWatch-DbaXESession -SqlInstance sql2017 -Session system_health | Export-Csv -NoTypeInformation -Path C:\\temp\\system_health.csv\nExports live events to CSV. Ctrl-C may not not cancel out of it - fastest way is to stop the session.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003eGet-DbaXESession -SqlInstance sql2017 -Session system_health | Start-DbaXESession | Watch-DbaXESession | Export-Csv -NoTypeInformation -Path C:\\temp\\system_health.csv\nExports live events to CSV. Ctrl-C may not not cancel out of this. The fastest way to do so is to stop the session.", "Description": "Streams live event data from running Extended Events sessions, allowing real-time monitoring of database activity, performance issues, or security events. Each captured event is processed into a PowerShell object with organized columns for event name, timestamp, fields, and actions. This command runs continuously until you stop the XE session, terminate the PowerShell session, or press Ctrl-C, making it ideal for interactive troubleshooting and live analysis workflows.\n\nThanks to Dave Mason (@BeginTry) for some straightforward code samples https://itsalljustelectrons.blogspot.be/2017/01/SQL-Server-Extended-Event-Handling-Via-Powershell.html", "Links": "https://dbatools.io/Watch-DbaXESession", "Synopsis": "Monitors Extended Events sessions in real-time, streaming live event data as it occurs", "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 the name of the Extended Events session to monitor for live event data. Use this when you want to watch a specific XE session instead of requiring pipeline input.\r\nCommon sessions include system_health for general diagnostics or custom sessions you\u0027ve created for specific monitoring needs.", "Name", false, "false", "", "" ], [ "InputObject", "Accepts one or more XESession objects from Get-DbaXESession via the pipeline. Use this approach when you want to filter, start, or configure XE sessions before monitoring them.\r\nThis enables workflows like \u0027Get-DbaXESession | Where Name -like \"*perf*\" | Start-DbaXESession | Watch-DbaXESession\u0027 for batch operations.", "", false, "true (ByValue)", "", "" ], [ "Raw", "Returns the raw XEvent enumeration object instead of processed PowerShell objects with organized columns. Use this when you need to work with the native Extended Events data structure for custom \r\nprocessing or integration with other tools.\r\nMost DBAs should use the default processed output which provides cleaner, more readable event data.", "", 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": [ "Table", "Data", "Insert" ], "CommandName": "Write-DbaDbTableData", "Name": "Write-DbaDbTableData", "Author": "Chrissy LeMaire (@cl), netnerds.net", "Syntax": "Write-DbaDbTableData -SqlInstance \u003cDbaInstanceParameter\u003e [-SqlCredential \u003cPSCredential\u003e] [-Database \u003cObject\u003e] -InputObject \u003cObject\u003e [-Table] \u003cString\u003e [[-Schema] \u003cString\u003e] [-BatchSize \u003cInt32\u003e] [-NotifyAfter \u003cInt32\u003e] [-AutoCreateTable] [-NoTableLock] [-CheckConstraints] [-FireTriggers] [-KeepIdentity] [-KeepNulls] [-Truncate] [-BulkCopyTimeOut \u003cInt32\u003e] [-ColumnMap \u003cHashtable\u003e] [-EnableException] [-UseDynamicStringLength] [-WhatIf] [-Confirm] [\u003cCommonParameters\u003e]", "Alias": "Write-DbaDataTable", "Outputs": "None\nThis command does not return any objects to the pipeline. It is an action command that performs bulk insert operations to load data into SQL Server tables. Progress information is displayed via \r\nWrite-Progress during the import operation, and verbose messages are written to the verbose stream for troubleshooting.", "Examples": "-------------------------- EXAMPLE 1 --------------------------\nPS C:\\\u003e$DataTable = Import-Csv C:\\temp\\customers.csv\nPS C:\\\u003e Write-DbaDbTableData -SqlInstance sql2014 -InputObject $DataTable -Table mydb.dbo.customers\nPerforms a bulk insert of all the data in customers.csv into database mydb, schema dbo, table customers. A progress bar will be shown as rows are inserted. If the destination table does not exist, \r\nthe import will be halted.\n-------------------------- EXAMPLE 2 --------------------------\nPS C:\\\u003e$tableName = \"MyTestData\"\nPS C:\\\u003e $query = \"SELECT name, create_date, owner_sid FROM sys.databases\"\r\nPS C:\\\u003e $dataset = Invoke-DbaQuery -SqlInstance \u0027localhost,1417\u0027 -SqlCredential $containerCred -Database master -Query $query -As DataSet\r\nPS C:\\\u003e $dataset | Write-DbaDbTableData -SqlInstance \u0027localhost,1417\u0027 -SqlCredential $containerCred -Database tempdb -Table $tableName -AutoCreateTable\nPulls data from a SQL Server instance and then performs a bulk insert of the dataset to a new, auto-generated table tempdb.dbo.MyTestData.\n-------------------------- EXAMPLE 3 --------------------------\nPS C:\\\u003e$DataTable = Import-Csv C:\\temp\\customers.csv\nPS C:\\\u003e Write-DbaDbTableData -SqlInstance sql2014 -InputObject $DataTable -Table mydb.dbo.customers -AutoCreateTable -Confirm\nPerforms a bulk insert of all the data in customers.csv. If mydb.dbo.customers does not exist, it will be created with inefficient but forgiving DataTypes.\nPrompts for confirmation before a variety of steps.\n-------------------------- EXAMPLE 4 --------------------------\nPS C:\\\u003e$DataTable = Import-Csv C:\\temp\\customers.csv\nPS C:\\\u003e Write-DbaDbTableData -SqlInstance sql2014 -InputObject $DataTable -Table mydb.dbo.customers -Truncate\nPerforms a bulk insert of all the data in customers.csv. Prior to importing into mydb.dbo.customers, the user is informed that the table will be truncated and asks for confirmation. The user is \r\nprompted again to perform the import.\n-------------------------- EXAMPLE 5 --------------------------\nPS C:\\\u003e$DataTable = Import-Csv C:\\temp\\customers.csv\nPS C:\\\u003e Write-DbaDbTableData -SqlInstance sql2014 -InputObject $DataTable -Database mydb -Table customers -KeepNulls\nPerforms a bulk insert of all the data in customers.csv into mydb.dbo.customers. Because Schema was not specified, dbo was used. NULL values in the destination table will be preserved.\n-------------------------- EXAMPLE 6 --------------------------\nPS C:\\\u003e$passwd = (Get-Credential NoUsernameNeeded).Password\nPS C:\\\u003e $AzureCredential = New-Object System.Management.Automation.PSCredential(\"AzureAccount\"),$passwd)\r\nPS C:\\\u003e $DataTable = Import-Csv C:\\temp\\customers.csv\r\nPS C:\\\u003e Write-DbaDbTableData -SqlInstance AzureDB.database.windows.net -InputObject $DataTable -Database mydb -Table customers -KeepNulls -SqlCredential $AzureCredential -BulkCopyTimeOut 300\nThis performs the same operation as the previous example, but against a SQL Azure Database instance using the required credentials.\n-------------------------- EXAMPLE 7 --------------------------\nPS C:\\\u003e$process = Get-Process\nPS C:\\\u003e Write-DbaDbTableData -InputObject $process -SqlInstance sql2014 -Table \"[[DbName]]].[Schema.With.Dots].[`\"[Process]]`\"]\" -AutoCreateTable\nCreates a table based on the Process object with over 60 columns, converted from PowerShell data types to SQL Server data types. After the table is created a bulk insert is performed to add process \r\ninformation into the table\r\nWrites the results of Get-Process to a table named: \"[Process]\" in schema named: Schema.With.Dots in database named: [DbName]\r\nThe Table name, Schema name and Database name must be wrapped in square brackets [ ]\r\nSpecial characters like \" must be escaped by a ` character.\r\nIn addition any actual instance of the ] character must be escaped by being duplicated.\nThis is an example of the type conversion in action. All process properties are converted, including special types like TimeSpan. Script properties are resolved before the type conversion starts \r\nthanks to ConvertTo-DbaDataTable.\n-------------------------- EXAMPLE 8 --------------------------\nPS C:\\\u003e$server = Connect-DbaInstance -SqlInstance SRV1\nPS C:\\\u003e $server.Invoke(\"CREATE TABLE tempdb.dbo.test (col1 INT, col2 VARCHAR(100))\")\r\nPS C:\\\u003e $data = Invoke-DbaQuery -SqlInstance $server -Query \"SELECT 123 AS value1, \u0027Hello world\u0027 AS value2\" -As DataSet\r\nPS C:\\\u003e $data | Write-DbaDbTableData -SqlInstance $server -Table \u0027tempdb.dbo.test\u0027 -ColumnMap @{ value1 = \u0027col1\u0027 ; value2 = \u0027col2\u0027 }\nThe dataset column \u0027value1\u0027 is inserted into SQL column \u0027col1\u0027 and dataset column value2 is inserted into the SQL Column \u0027col2\u0027. All other columns are ignored and therefore null or default values.\n-------------------------- EXAMPLE 9 --------------------------\nPS C:\\\u003e$DataTable = Import-Csv C:\\temp\\sales_data.csv\nPS C:\\\u003e Write-DbaDbTableData -SqlInstance sql2016 -InputObject $DataTable -Database mydb -Schema reporting -Table sales -AutoCreateTable\nImports sales_data.csv into mydb.reporting.sales. If the reporting schema doesn\u0027t exist, it will be automatically created with dbo as owner. The sales table will then be created with columns inferred \r\nfrom the CSV structure.", "Description": "Imports data from various sources (CSV files, DataTables, DataSets, PowerShell objects) into SQL Server tables using SqlBulkCopy for optimal performance. This command handles the heavy lifting of data type conversion from PowerShell to SQL Server, automatically creates missing tables when needed, and provides fine-grained control over bulk copy operations. Commonly used for data migration, ETL processes, and importing large datasets where INSERT statements would be too slow.", "Links": "https://dbatools.io/Write-DbaDbTableData", "Synopsis": "Performs high-speed bulk inserts of data into SQL Server tables using SqlBulkCopy.", "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 target database for the bulk insert operation. Required when using one or two-part table names.\r\nUse this when you need to target a specific database different from the default connection database.", "", false, "false", "", "" ], [ "InputObject", "Accepts various data formats including DataTable, DataSet, CSV files, or PowerShell objects for bulk insertion.\r\nUse DataSet for optimal performance as all records import in a single SqlBulkCopy call. DataTable also performs well but avoid piping directly as it converts to slower DataRow processing.\r\nPowerShell objects are automatically converted to DataTable format before import.", "DataTable", true, "true (ByValue)", "", "" ], [ "Table", "Specifies the destination table using one, two, or three-part naming (database.schema.table). Supports temp tables with # prefix.\r\nUse square brackets for special characters: [Schema.Name].[Table]] for tables containing brackets. Three-part names override the Database parameter.\r\nCombine with -AutoCreateTable to create missing tables, though manual table creation provides better data type control.", "", true, "false", "", "" ], [ "Schema", "Sets the schema for the destination table when not specified in the table name. Defaults to \u0027dbo\u0027.\r\nUse this when working with non-default schemas or when security policies require specific schema targeting.", "", false, "false", "dbo", "" ], [ "BatchSize", "Controls how many rows are sent to SQL Server in each batch operation. Defaults to 50,000 rows.\r\nLower values (5,000-10,000) work better for wide tables or limited memory, while higher values improve performance for narrow tables with sufficient resources.", "", false, "false", "50000", "" ], [ "NotifyAfter", "Determines how frequently progress notifications appear during the import operation. Defaults to every 5,000 rows.\r\nSet higher for less frequent updates on large imports, or lower for more granular progress tracking on smaller datasets.", "", false, "false", "5000", "" ], [ "AutoCreateTable", "Automatically creates the destination table and schema when they don\u0027t exist, using data types inferred from the source data.\r\nThe schema is created with dbo as owner. Convenient for quick imports but creates generic data types like NVARCHAR(MAX). For production use, manually create tables with appropriate data types and \r\nconstraints.\r\nNote: Schema creation is skipped for temp tables (tables starting with #).", "", false, "false", "False", "" ], [ "NoTableLock", "Disables the default TABLOCK hint during bulk insert operations, allowing concurrent access to the destination table.\r\nUse when importing to tables that need concurrent read access, though this may reduce import performance compared to the default exclusive lock.", "", false, "false", "False", "" ], [ "CheckConstraints", "Enforces check constraints during the bulk insert operation instead of the default behavior of bypassing them.\r\nUse when data integrity validation is critical, though this reduces import performance. Constraints are normally checked after bulk operations complete.", "", false, "false", "False", "" ], [ "FireTriggers", "Executes INSERT triggers during the bulk copy operation instead of bypassing them for performance.\r\nEssential when triggers maintain audit trails, calculated fields, or related table updates. Significantly impacts import speed but preserves all database logic.", "", false, "false", "False", "" ], [ "KeepIdentity", "Preserves identity column values from the source data instead of generating new sequential values.\r\nCritical for maintaining referential integrity when importing related tables or restoring data with existing identity dependencies.", "", false, "false", "False", "" ], [ "KeepNulls", "Maintains NULL values from source data instead of replacing them with column default values.\r\nUse when NULL has specific business meaning in your data or when you need to preserve exact source data representation including missing values.", "", false, "false", "False", "" ], [ "Truncate", "Removes all existing data from the destination table before performing the bulk insert operation.\r\nUseful for refreshing tables with new data while maintaining table structure, indexes, and permissions. Always prompts for confirmation before execution.", "", false, "false", "False", "" ], [ "BulkCopyTimeOut", "Sets the maximum time in seconds to wait for the bulk copy operation to complete. Defaults to 5,000 seconds.\r\nIncrease for very large datasets or slow storage systems. Set to 0 for unlimited timeout when importing millions of rows.", "", false, "false", "5000", "" ], [ "ColumnMap", "Defines custom mapping between source and destination columns using a hashtable when automatic column mapping fails.\r\nUse when column names differ between source and target, or when you need to import only specific columns. Format: @{SourceColumn=\u0027DestColumn\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", "" ], [ "UseDynamicStringLength", "Creates string columns with lengths based on source data MaxLength property instead of defaulting to NVARCHAR(MAX).\r\nImproves storage efficiency and query performance when AutoCreateTable is used, but requires source data to provide accurate length information.", "", 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", "", "" ] ] } ]